Skip to content

fix: decode subprocess output as UTF-8 in save.py on Windows - #6218

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
dylanschroers:fix/windows-utf8-subprocess-save
Jun 12, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
dylanschroers:fix/windows-utf8-subprocess-save

Conversation

@dylanschroers

@dylanschroers dylanschroers commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Part of #2660

Problem

On Windows, Python's default text encoding is the locale code page (cp1252), not UTF-8. The text-mode subprocess calls in unsloth/save.py (text=True / universal_newlines=True) don't set an encoding, so they decode llama.cpp and Ollama output as cp1252. That pipeline prints non-ASCII (progress and box-drawing glyphs, model names, file paths like C:\Users\José\...), so the moment a byte cp1252 can't map shows up (0x9d is a common one, it lives inside the UTF-8 encoding of ordinary curly quotes) the read raises UnicodeDecodeError and the export dies. Valid-but-wrong bytes corrupt the captured text silently instead.

Reproduced on Windows (cp1252, PYTHONUTF8 unset):

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 16: character maps to <undefined>

The original import-time crash in #2660 was already fixed in unsloth-zoo; this is the save/export half in this repo. The unsloth-zoo llama.cpp engine half is unslothai/unsloth-zoo#764.

Fix

  • unsloth/save.py
    • add encoding="utf-8", errors="replace" to all 8 text-mode subprocess calls (_quantize_q2_k_l quantize + capture, the two create_ollama_model / push_to_ollama_hub curl + Popen pairs, and the two convert-lora-to-ggml Popens). errors="replace" means a stray byte can neither crash an export nor silently corrupt the captured output.
  • tests/saving/test_save_subprocess_utf8_encoding.py (new)
    • AST drift test: parses save.py and fails if any text-mode subprocess call is missing encoding="utf-8". No unsloth import, so it runs without torch or a GPU. Red before the change, green after.
    • behavioural test: spawns a real subprocess emitting a curly quote, asserts the raw bytes fail under cp1252 and read cleanly with the new kwargs.

Validation: pytest tests/saving/test_save_subprocess_utf8_encoding.py passes 3/3 (the drift test fails before the fix); ruff check and the kwarg-spacing hook are clean.

On Windows the default text encoding is the locale code page (cp1252), not
UTF-8. The text-mode subprocess calls in save.py (text=True /
universal_newlines=True) set no explicit encoding, so they decode
llama.cpp / Ollama output with cp1252. When a child process emits a byte
undefined in cp1252 -- e.g. 0x9d, which appears inside the UTF-8 encoding
of common punctuation / box-drawing glyphs and in non-ASCII file paths --
the read raises UnicodeDecodeError and aborts GGUF export.

Add encoding="utf-8", errors="replace" to all 8 text-mode subprocess calls.
errors="replace" also avoids silent mojibake for inputs whose bytes happen
to be valid-but-wrong in cp1252.

Add tests/saving/test_save_subprocess_utf8_encoding.py:
- an AST drift detector asserting every text-mode subprocess call in
  save.py pins encoding="utf-8" (runs without importing torch/unsloth_zoo)
- a behavioural test reproducing the cp1252 failure and the utf-8 fix

Relates-to: unslothai#2660

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 resolves potential UnicodeDecodeError issues on Windows by explicitly specifying encoding='utf-8' and errors='replace' across multiple text-mode subprocess calls in unsloth/save.py. It also introduces a regression test suite in tests/saving/test_save_subprocess_utf8_encoding.py to prevent future occurrences of this issue. There are no review comments, and we have no additional feedback to provide.

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.

@dylanschroers dylanschroers changed the title Fix UnicodeDecodeError on Windows when reading subprocess output during save/export fix: decode subprocess output as UTF-8 in save.py on Windows Jun 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: ccb03ed377

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 51f1c87 into unslothai:main Jun 12, 2026
1 check passed
@danielhanchen

Copy link
Copy Markdown
Member

Thanks so much!

@dylanschroers
dylanschroers deleted the fix/windows-utf8-subprocess-save branch August 22, 2026 23:56
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Oct 23, 2026
Part of unslothai/unsloth#2660

## Problem

`unsloth_zoo/llama_cpp.py` clones, cmake-builds, quantizes and converts
llama.cpp through text-mode subprocess calls (`text=True` /
`universal_newlines=True`) that never set an `encoding`. On Windows the
output is decoded as cp1252 (the locale default) instead of UTF-8. The
build/convert pipeline prints non-ASCII along the way (localized cmake
and compiler messages on non-English Windows, progress and box-drawing
glyphs, model/tensor names, file paths), so when a byte cp1252 can't map
shows up (0x9d is the usual one, it sits inside the UTF-8 encoding of
common punctuation) the read raises `UnicodeDecodeError` and the build
or convert aborts, often after a long compile. Valid-but-wrong bytes
corrupt the captured text silently instead.

Reproduced on Windows (cp1252, `PYTHONUTF8` unset) using the
`try_execute()` pattern:

```
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 24: character maps to <undefined>
```

This is the shared-engine half of the bug, the one both unsloth and
Studio call under the hood. The `unsloth` save.py half is
unslothai/unsloth#6218.

## Scope

`install_llama_cpp` installs the `unslothai/llama.cpp` prebuilt first,
and Studio / Desktop export reuses the prebuilt their installers put at
`UNSLOTH_LLAMA_CPP_PATH`, so the clone / cmake / package-probe calls
below only run on the source-build fallback (no prebuilt for the host, a
failed download or checksum, `UNSLOTH_LLAMA_FORCE_COMPILE=1`) and on
Core's `just_clone_repo` paths. The converter child environment is on
every GGUF export, Studio included.

## Fix

- `unsloth_zoo/llama_cpp.py`
- `encoding="utf-8", errors="replace"` on every text-mode subprocess
call that lacked it (13 on current main): `try_execute`, the cmake
configure/build steps, `check_pip`, `check_llama_cpp`, the winget / dpkg
/ rpm / pacman / apk probes, and the uncalled `_convert_to_gguf`.
- `PYTHONIOENCODING=utf-8` for Python children: in
`_converter_child_env` (the live `convert_to_gguf` converter and its
gguf probe) and in `try_execute`. On Windows a Python child writes piped
output in the ANSI code page, so without it non-ASCII text (chat
templates with fullwidth tokens, output filenames) arrives escaped or
garbled, and a `print()` of a character outside cp1252 crashes the
child.
- `_find_lib_path` reads gcc's output as bytes and decodes it with
`os.fsdecode`, so a non-ASCII toolchain prefix still resolves to the
real file.
- `tests/test_llama_cpp_subprocess_utf8_encoding.py`: AST check that
every text-mode `subprocess` call in `llama_cpp.py` pins
`encoding="utf-8"`, `try_execute` on a raw UTF-8 child and on a Python
child printing non-ASCII text, and the converter env pin. Added to the
CPU gate in `consolidated-tests-ci.yml`.

Validation: under a non-UTF-8 locale, main raises `UnicodeDecodeError`
on raw UTF-8 output and the Python child dies with `UnicodeEncodeError`;
this branch returns both intact. The new tests pass on ubuntu-latest,
macos-15 and windows-latest.

On a real Windows 11 host (cp1252), base vs head vs head merged into
main:

| state | raw UTF-8 child | Python child printing `”é中` |
|---|---|---|
| main | `UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d` |
crashes |
| this PR | `tensor ” ok` | `”é中` |
| this PR merged into main | `tensor ” ok` | `”é中` |

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
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