Skip to content

Studio NPU: run FastFlowLM without Lemonade on Windows - #18554

Merged
danielhanchen merged 16 commits into
mainfrom
npu-flm-direct
Nov 20, 2026
Merged

danielhanchen merged 16 commits into
mainfrom
npu-flm-direct

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Stacked on #18553 (signed FastFlowLM 1.0.13).

Even with FastFlowLM signed, lemond.exe is not: the Lemonade 2026.47.1 zip and the files inside its signed MSI are unsigned. Whether Smart App Control allows lemond.exe depends on cloud reputation and changes over time. On the test machine it was refused for most of a day, then allowed. This PR removes Lemonade from the Windows path, so everything Studio starts for the NPU is either Studio's own Python or AMD-signed.

Design

Studio only uses a small slice of lemond: /v1/health, /v1/models (plus /{id}/options), /v1/install, /v1/pull, /v1/load, /v1/unload, /v1/delete, /internal/set and the OpenAI chat routes. FastFlowLM's own CLI already covers that slice (flm list --json, pull, serve, remove, version).

  • core/inference/flm_host.py (new): serves that slice from Studio's Python and starts the signed flm.exe.
    • Catalog rows keep lemond's ids (qwen3:0.6b -> qwen3-0.6b-FLM) and labels, so saved chats and settings still resolve.
    • Load starts flm serve <tag> --ctx-len N with any flm_args. Health reports recipe_options.ctx_size the way lemond does.
    • Chat is proxied, with the model field rewritten to the tag.
    • flm's output is relayed to stdout, so Studio's load-failure explanations keep working.
    • It exits, stopping flm serve, if Studio dies.
  • install_lemonade_prebuilt.py: on Windows, install() downloads the pinned FastFlowLM zip, checks its sha256 and extracts it where lemond's /v1/install would. installed_lemond() then returns flm_host.py.
    • Linux runs the same way (see below).
    • UNSLOTH_NPU_LEMONADE=1 keeps Lemonade on Windows too.
  • lemonade_server.py: a .py binary runs on sys.executable.
  • npu_backend.py is otherwise unchanged. Enable stops a running server before an upgrade install, since Windows locks the files being replaced.

Existing installs migrate on first use. The old {"lemond": ...} marker reads as a pending upgrade, so the next catalog read runs Enable. That installs FastFlowLM directly and keeps every downloaded model, which lives in flm/, not in the binary folder.

Testing

On a Ryzen AI MAX+ 395 with Smart App Control on:

  • Fresh Enable takes 7 s: versions={'lemonade': None, 'fastflowlm': '1.0.13'} and 58 catalog rows, with the decision models hidden.
  • Download qwen3-0.6b-FLM through /api/npu/models/.../download, load it through /api/inference/load, then stream and non-stream /v1/chat/completions. No lemond process exists at any point.
  • A real UI run against the patched backend (built frontend): pick the model, it loads on the NPU, the answer streams with the Thinking block. Passed in Chromium and Edge.
  • Migration: a root installed by Lemonade 2026.44.1 with a validated marker switches to flm_host.py on first catalog read. The downloaded model still loads and chats.
  • Found and fixed during these runs: flm prints emoji, and the output relay died on Windows' cp1252 pipe. flm serve then blocked on a full stdout pipe and non-stream chats timed out after 300 s. The relay now writes UTF-8 and never stops draining (there is a regression test).

Parity with lemond, on one root (same flm.exe and model files), with the same requests sent to lemond.exe 2026.44.1 and to flm_host.py:

  • All 72 catalog rows match: ids, checkpoints, labels, sizes, downloaded flags and context windows.
  • Identical answers for auth, an unknown load (404), an unknown delete (422), pull of a downloaded model, load, health (ctx_size 4096), chat (non-stream and stream, same greedy output and usage fields), tools, /v1/completions, 3 concurrent chats and unload.
  • Prompt text kept in Studio's log: 0 for both. flm's output is tagged (Process) in lemond's line format, so Studio keeps it only while a load is open, as with lemond.
  • The one difference: lemond loads a model when a chat names one that is not loaded, flm_host answers 503. Studio never sends a chat without a resident model.

Switching paths, through LemonadeNpuBackend with a Studio restart each time: Lemonade, Lemonade, direct, direct, Lemonade, direct on the same root. Every run passes Enable twice, lists the same 58 rows, keeps the downloaded model, loads it and gets the same answer. lemond.exe runs only on the Lemonade runs. lfm2.5-it-1.2b-FLM downloaded fresh through each path gives byte-identical files, and loads, answers and deletes the same way.

Unit tests in tests/test_npu_flm_host.py (17 cases) pass on Windows and Linux. They cover:

  • catalog mapping, the context window from the downloaded config, and auth (only /live is open)
  • flm output tagged (Process) so prompts stay out of Studio's log
  • install, plus pull complete and error events
  • load with ctx and flm_args, health, a chat proxied by tag, and unload
  • a failed load naming flm's reason, and delete of a serving model
  • [ERROR] printed with exit code 0 counting as a failure
  • the direct install's layout, reuse and pin change
  • when Lemonade is still used, and the .py launcher

Existing NPU suites: 475 passed on Linux, 188 on Windows. ruff-unsloth format is AST-identical and ruff check passes.

Not covered: macOS (no NPU path), and Linux NPU hardware. Linux behaviour is unchanged.

Linux too, and hardware results

Linux now runs FastFlowLM through flm_host.py as well, so no platform starts Lemonade. UNSLOTH_NPU_LEMONADE=1 still selects lemond.

Checked on the AMD Strix Halo runners (Windows 11 and Ubuntu 24.04, XDNA2 NPU), current main against this branch on the same machine, plus lemond 2026.44.1 on the same FastFlowLM 1.0.13 files as a reference:

  • Windows main starts lemond.exe and nothing else unsigned; this branch starts only python.exe (PSF), conhost.exe and AMD-signed flm.exe, and never lemond.exe.
  • flm_host matches lemond on all 72 FastFlowLM catalog rows, the Studio catalog before and after a download, load context, health, options, greedy answers (stream and non-stream), usage tokens, finish reasons, the 404 / 422 error statuses and pull.
  • A second Enable after a restart changes none of FastFlowLM's files and downloads nothing. A main install with a downloaded model switches to flm_host on first use and keeps the model.
  • xrt-smi examine -r aie-partitions lists the flm serve process during generation, on both hosts.
  • Decode speed through flm_host equals lemond's (101 tok/s on Qwen3-0.6B), and time to first token matches (0.61 s each) after pooling the upstream client and turning off Nagle for the event stream.

Settings > About for an NPU running FastFlowLM without Lemonade (the NPU status is stubbed the same on both sides; the llama.cpp and environment rows differ only because they had not loaded yet on the left):

Before and after

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T15:44:59.391980Z 134af29 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen danielhanchen added edge case# security# Moves a security boundary: sandbox, allowlist, permission or network guard labels Nov 20, 2026
@danielhanchen danielhanchen self-assigned this Nov 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b358c80fa

ℹ️ 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".

self.send_header("Content-Type", "text/event-stream")
self.send_header("Connection", "close")
self.end_headers()
code, output = flm.run("pull", row["checkpoint"], timeout = 24 * 3600.0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Emit pull events while the download is running

When LemonadeNpuBackend._download falls back to FastFlowLM because the model's file manifest is unreadable, flm.run buffers all output until the entire pull finishes, so this SSE response sends no events during the download. The backend checks its cancellation flag only inside response.iter_lines(), leaving the download job stuck in cancelling until completion; a download lasting over an hour also exceeds LemonadeServer.stream's read timeout despite this subprocess allowing 24 hours. Stream progress or heartbeat events while the subprocess runs so cancellation and long downloads remain functional.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This path only runs when Studio cannot read FastFlowLM's file list for the model. Every entry in the pinned 1.0.13 model_list.json carries one, so Studio downloads the files itself with progress and cancel, and /v1/pull only registers them. Not changing it for a corrupt install.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 7352563810

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 0864c13f28

ℹ️ 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".

Base automatically changed from flm-1.0.13-signed to main November 20, 2026 15:11
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 134af2938e

ℹ️ 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 pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 20, 2026
@danielhanchen
danielhanchen merged commit 175bd28 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the npu-flm-direct branch November 20, 2026 15:56
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…18651)

## Summary

`Repo tests (CPU, studio-install)` is red on `main` (seen on #18650, and
reproduced on current `main`):

```
FAILED tests/studio/install/test_install_lemonade_prebuilt.py::test_install_verifies_and_pins_fastflowlm
FAILED tests/studio/install/test_install_lemonade_prebuilt.py::test_a_complete_install_is_not_downloaded_again
FAILED tests/studio/install/test_install_lemonade_prebuilt.py::test_a_fastflowlm_only_pin_bump_repins_lemond
FAILED tests/studio/install/test_install_lemonade_prebuilt.py::test_a_digest_mismatch_installs_nothing
FAILED tests/studio/install/test_install_lemonade_prebuilt.py::test_a_cancelled_download_installs_nothing
urllib.error.HTTPError: HTTP Error 404: File not found
```

## Cause

#18554 made the direct FastFlowLM install the default on every supported
host (Windows and Linux x86_64, as its description says). The lemond
path now only runs with `UNSLOTH_NPU_LEMONADE=1`. The installer change
is intended. These tests, though, were written for the lemond path and
never opted in. So `install()` now took the direct path and asked the
test's local server for a FastFlowLM archive that does not exist there,
which returned the 404. The tests are out of date, not the installer.

## Change

All changes are in
`tests/studio/install/test_install_lemonade_prebuilt.py`; the installer
is unchanged.

- Two fixtures pin the path each test means to cover:
- `lemond_path` sets `UNSLOTH_NPU_LEMONADE=1` and asserts `direct_flm()`
is False;
  - `direct_path` unsets it and asserts the default is the direct path.
A future change of default therefore fails at the fixture instead of
quietly testing one path against the other's assets.
- The five existing tests use `lemond_path`, so the opt-in lemond path
keeps its coverage.
- The local server now also serves a real FastFlowLM archive (a tar.gz,
or a zip on Windows), and the pins carry its actual digest.
- Three new tests cover the default direct path, which had no installer
test:
- it installs the pinned FastFlowLM with no Lemonade, writes the marker,
and does not download again once installed;
  - a digest mismatch installs nothing;
  - a cancelled download installs nothing.

## Testing

- On `main` the file fails 5 of 6. With this change: 9 passed.
- Sabotage, installer side:
- dropping the reuse check in `_install_flm_direct` fails the new test
with "a complete FastFlowLM install was downloaded again";
- disabling the sha256 check in `_download` fails both digest-mismatch
tests (the lemond one and the direct one).
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…ort and FLM host tests (#18654)

## Summary

`Repo tests (CPU, rest-2)` is red on `main` (seen on #18650, reproduced
on current `main`). `tests/test_source_read_encoding.py` flags three new
reads that use the platform default encoding:

```
AssertionError: 2 file reads in the test trees touch a checked-in file with the platform default encoding ...: ['tests/test_run_report.py:246: read_text()', 'tests/test_run_report.py:267: read_text()']
AssertionError: 1 file reads in the test trees touch a checked-in file with the platform default encoding ...: ['studio/backend/tests/test_npu_flm_host.py:286: read_text()']
```

## Cause

- #18603 (opt-in memory and batch efficiency reports) added the two
reads in `tests/test_run_report.py`.
- #18554 (FastFlowLM without Lemonade) added the read in
`studio/backend/tests/test_npu_flm_host.py`.

All three are bare `read_text()` calls on checked-in files. On Windows
they would decode with the locale code page as soon as one of those
files gains a non-ASCII byte. The guard is right; the reads are what
needs fixing.

## Change

- `encoding = "utf-8"` on those three `read_text` calls. No behaviour
change.

## Testing

- `tests/test_source_read_encoding.py` lists the three offenders on
`main` and passes with this change.
- `tests/test_source_read_encoding.py` and `tests/test_run_report.py`:
30 passed.
- `studio/backend/tests/test_npu_flm_host.py`: 21 passed.
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Nov 20, 2026
…slothai#18658)

Since unslothai#18554 Studio runs FastFlowLM directly on Windows and Linux and
never starts lemond, but an install that had lemond kept its folder
(`<studio home>/lemonade/2026.44.1/`, lemond plus its DLLs). It is never
run, so it does nothing, but it is an unsigned `lemond.exe` sitting in
the Studio folder for no reason.

## Changes

- `install_lemonade_prebuilt.py`: after the FastFlowLM-only install
verifies, delete every lemond version folder, identified by the
`UNSLOTH_LEMONADE_INFO.json` marker the lemond install writes.
FastFlowLM, the downloaded models and `config/` carry no such marker and
are left alone.
- Each folder is renamed before it is deleted. Windows refuses to rename
a folder whose `lemond.exe` is still running, so a live lemond is left
whole and retried on the next Enable. A removal interrupted halfway
leaves a `.lemond-remove-*` folder, which the next run finishes.
- Nothing is removed when `UNSLOTH_NPU_LEMONADE=1` asks for lemond.
Turning it back on later downloads lemond again (about 6 MB).

Re-running is a no-op: the second install finds no marked folder.

## Testing

- New tests in `test_npu_flm_host.py`: an old lemond folder and an
interrupted removal are deleted while a downloaded model and `config/`
stay, a second install changes nothing, and a lemond that cannot be
moved is left whole. Both fail on `main`. FastFlowLM host and NPU
backend suites: 119 passed.
oobabooga added a commit that referenced this pull request Nov 20, 2026
…of an empty reason (#18648)

**Problem:** On Windows, when Smart App Control or an App Control policy
refuses one of FastFlowLM's DLLs, `flm.exe` exits with 0xC0E90002 and
prints nothing. Since #18554, Enable NPU then fails with "Installing
FastFlowLM failed: FastFlowLM does not run:" and no reason.

**Change:** `flm_host.py` reports the exit code when flm prints nothing.
Enable recognizes the code integrity status in that error and shows the
message Studio already uses for these blocks, which names the blocked
folder.

**Status:** Tested on the AMD DevLab Windows runner (Strix Halo), `main`
against this branch, with `flm.exe` replaced by a stub that exits
0xC0E90002 without output.

![Before and
after](https://raw.githubusercontent.com/oobabooga/unsloth/pr-media/pr/npu-silent-refusal/npu-silent-refusal-61cb676a7901.png)

## Details

- `flm_host.py`: `Flm.run` turns a failed run with no output into
`[ERROR] exit code N (0xC0E90002)`.
- `npu_backend.py`: when FastFlowLM's install check fails, the reason
goes through the existing `_blocked_message`. Any other failure keeps
"Installing FastFlowLM failed: ...".
- Loading a model already explained a silent refusal through `_explain`,
so the load path is unchanged. A test now covers it.

## Not covered

The runner has Smart App Control off, so the refusal comes from the
stub, not from a real policy. The exit status and the empty output match
what #18549 recorded on a machine with Smart App Control on.

## Testing

- New tests for the install message, an ordinary install failure, the
load message, and the exit code text. The install-message and exit-code
tests fail on `main`.
- NPU backend suites: 729 passed, 1 skipped.
danielhanchen added a commit to NilayYadav/unsloth that referenced this pull request Nov 23, 2026
… it (unslothai#18806)

Related to unslothai#18763

## What this changes

Since unslothai#18554, Studio lists NPU models through `flm_host.py` on Windows
and Linux. `Flm.catalog()` ran `flm list --json`, joined stdout and
stderr, and passed everything from the first `{` to `json.loads`. When
flm prints anything after the JSON (a runtime notice on stderr, a status
line on stdout), `json.loads` raises `Extra data: line N column 1`, and
the whole NPU model list fails with that message, as in the report
(v0.1.922, FastFlowLM 1.0.13).

`catalog()` now reads only the JSON object that holds `models`
(`json.JSONDecoder().raw_decode`, tried at the first brace and at braces
that start a line) and skips the text around it. If no such object is
found, the error names flm's output (`flm list failed: ...`) instead of
a JSON parser position.

## Tests

- `test_npu_flm_host.py`: the model list with a line after it on stderr,
a line after it on stdout, and a status line before it; a truncated list
reports flm's output.
- End to end on Windows (no NPU here): a stand-in `flm.exe` printing the
FastFlowLM 1.0.13 model list (rebuilt from its `model_list.json` the way
`flm list --json` dumps it) followed by one stderr line. Only the NPU
hardware probe was replaced; Studio started the real `flm_host.py`
process and `GET /api/npu/models` went through `routes/npu.py`.
- main: `409 Listing NPU models failed: Extra data: line 2580 column 1
(char 93218)`
  - this PR: `200`, 45 chat models
  - without the extra line, both list the same 45 models.
- `test_npu_flm_host.py` + `test_npu_backend.py`: 28 passed with this
change, 24 on main (`test_npu_backend.py` is skipped on Windows).

| Before | After |
|---|---|
|
![before](https://raw.githubusercontent.com/debojyoti-dev/unsloth/pr-media-18763/before.png)
|
![after](https://raw.githubusercontent.com/debojyoti-dev/unsloth/pr-media-18763/after.png)
|

Not tested on a real Ryzen AI NPU or on Linux.


## Maintainer validation (AMD CI, real Strix Halo NPU)

Ran on the gfx1151 pool with the pinned FastFlowLM 1.0.13 (`flm list
--json`, `validate`, `version`) and `Flm.catalog()` at main versus this
branch:

| host | scenario | main | this PR |
|---|---|---|---|
| Linux, amdxdna loaded, `/dev/accel/accel0` | no models, 2 models
pulled by 1.0.13, 2 pulled by 1.0.12 then listed by 1.0.13, 8 MiB
memlock, a second `flm serve` holding the NPU | 59 models listed | 59
models listed |
| Windows 11, NPU Compute Accelerator (17F0), `validate` ready | default
| 72 models listed | 72 models listed |

On these hosts flm prints nothing around the JSON, so they list on main
too and this is a no-regression check. The reporter's error offset (line
2025, char 73430) is exactly the end of the 1.0.13 model list JSON with
7 models installed, so the failure is text printed after the list, which
this change skips.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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

edge case# security# Moves a security boundary: sandbox, allowlist, permission or network guard

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants