onwx 1.2.0: model choice from the API, model limits in /v1/models, usage on a stream's last chunk; a closed model gives its NPU memory back
Browse filesFiles changed (13)
4 unmodified lines56789104 unmodified lines日付は日本時間です。各版は Hugging Face の `ryugyosoft/onwx` にタグ(`v0.2.0` 以降)付きで残っています。onwx ウィンドウは、新しい版があるとこのファイルから変更点を表示します(`## v…` の見出しで区切っています)。## v1.1.0 (2026-10-29)- **長い文脈の設定でもメモリを最初に取りすぎないように**:アテンションのキャッシュ(キーと値)を、設定した文脈の長さぶん読み込み時にまとめて確保するのをやめ、会話が長くなるのに合わせて広げるようにしました(最初は 4,096 トークン分。足りなくなると 2 倍以上に広げ、それまでの中身を写します。1 回 0.1 秒以下)。文脈を 262144 にしたとき、読み込み直後のメモリは Ternary Bonsai 2 27B で約 16.7 → 約 8.3 GB、Qwen3.5 9B で 10.5 → 5.8 GB、Qwen3.6 35B-A3B で 24.9 → 19.1 GB になります。出力と速さは前の版と同じです(Ryzen AI Max+ 395 で確認)。モデルの更新は不要です。- それに合わせて、「モデル」タブのメモリの目安を、読み込み直後の量で表示するようにしました。会話が長くなると、文脈 1k トークンあたり、モデルの表にある量ずつ増えます。4 unmodified lines56789101112131415164 unmodified lines日付は日本時間です。各版は Hugging Face の `ryugyosoft/onwx` にタグ(`v0.2.0` 以降)付きで残っています。onwx ウィンドウは、新しい版があるとこのファイルから変更点を表示します(`## v…` の見出しで区切っています)。## v1.2.0 (2026-10-30)- **API からモデルを切り替えられるように**:`/v1/models` にこのパソコンにあるモデルが全部出て、リクエストの `model` に別のモデルの ID を指定すると、今のモデルを閉じてそのモデルを読み込んでから答えます(同時に読み込むのは 1 つだけ)。知らない名前のときは今のモデルが答えます。設定「API からモデルを切り替えられるようにする」でオフにできます。- `/v1/models` にモデルの上限(`context_length`・`max_model_len`・`max_context_length`・`meta.n_ctx`、`max_output_tokens`)を入れました。- ストリームの応答でも、最後のチャンクにトークン数(`usage`)が付くようにしました(`stream_options.include_usage` を送らないアプリでも分かります)。- モデルを閉じたとき、NPU のバッファとコンテキストをすべて返すようにしました(切り替え後もメモリが増えません)。## v1.1.0 (2026-10-29)- **長い文脈の設定でもメモリを最初に取りすぎないように**:アテンションのキャッシュ(キーと値)を、設定した文脈の長さぶん読み込み時にまとめて確保するのをやめ、会話が長くなるのに合わせて広げるようにしました(最初は 4,096 トークン分。足りなくなると 2 倍以上に広げ、それまでの中身を写します。1 回 0.1 秒以下)。文脈を 262144 にしたとき、読み込み直後のメモリは Ternary Bonsai 2 27B で約 16.7 → 約 8.3 GB、Qwen3.5 9B で 10.5 → 5.8 GB、Qwen3.6 35B-A3B で 24.9 → 19.1 GB になります。出力と速さは前の版と同じです(Ryzen AI Max+ 395 で確認)。モデルの更新は不要です。- それに合わせて、「モデル」タブのメモリの目安を、読み込み直後の量で表示するようにしました。会話が長くなると、文脈 1k トークンあたり、モデルの表にある量ずつ増えます。
4 unmodified lines56789104 unmodified linesDates are Japan time. Every version is kept on Hugging Face `ryugyosoft/onwx` with a tag (from `v0.2.0` on).The onwx window shows what changed from this file when there is a newer version (sections start at `## v…`).## v1.1.0 (2026-10-29)- **Long context settings no longer take the memory up front**: the attention cache (keys and values) is no longer allocated for the whole context setting at load; it grows with the conversation (4,096 tokens at first, then at least doubled when more is needed, the records so far copied over - under 0.1 s each time). With the context at 262144, the memory right after loading drops for Ternary Bonsai 2 27B from ~16.7 to ~8.3 GB, for Qwen3.5 9B from 10.5 to 5.8 GB, for Qwen3.6 35B-A3B from 24.9 to 19.1 GB. Output and speed are the same as before (checked on a Ryzen AI Max+ 395). No model update needed.- The memory estimate in the Models tab now shows the memory right after loading; a longer conversation adds the amount per 1k tokens of context the model table lists.4 unmodified lines56789101112131415164 unmodified linesDates are Japan time. Every version is kept on Hugging Face `ryugyosoft/onwx` with a tag (from `v0.2.0` on).The onwx window shows what changed from this file when there is a newer version (sections start at `## v…`).## v1.2.0 (2026-10-30)- **Model choice from the API**: `/v1/models` lists every model on this PC, and a request whose `model` names another one closes the running model and loads that one first (one model at a time). A name the server does not know is answered by the running model. The setting "Let API requests switch models" turns it off.- `/v1/models` carries the model's limits (`context_length`, `max_model_len`, `max_context_length`, `meta.n_ctx`, `max_output_tokens`).- Streamed answers carry the token counts (`usage`) on their last chunk too (apps that do not send `stream_options.include_usage` see them).- A closed model gives all its NPU buffers and contexts back (switching does not pile up memory).## v1.1.0 (2026-10-29)- **Long context settings no longer take the memory up front**: the attention cache (keys and values) is no longer allocated for the whole context setting at load; it grows with the conversation (4,096 tokens at first, then at least doubled when more is needed, the records so far copied over - under 0.1 s each time). With the context at 262144, the memory right after loading drops for Ternary Bonsai 2 27B from ~16.7 to ~8.3 GB, for Qwen3.5 9B from 10.5 to 5.8 GB, for Qwen3.6 35B-A3B from 24.9 to 19.1 GB. Output and speed are the same as before (checked on a Ryzen AI Max+ 395). No model update needed.- The memory estimate in the Models tab now shows the memory right after loading; a longer conversation adds the amount per 1k tokens of context the model table lists.
138 unmodified lines139140141142143144138 unmodified lines## API`/v1/chat/completions`(ストリーミング可)、`/v1/models`、`/v1/messages`(Anthropic 形式)、`/v1/responses` に対応しています。思考モードは `"chat_template_kwargs": {"enable_thinking": true}` か `"reasoning_effort"` で切り替えます。設定で LAN からの接続を許可すると、他の PC からも使えます(API キーの設定をおすすめします)。アプリが `max_tokens` を送らないときの回答の長さの上限は、設定の「API の最大出力トークン」で変えられます(既定 8192)。138 unmodified lines139140141142143144145138 unmodified lines## API`/v1/chat/completions`(ストリーミング可)、`/v1/models`、`/v1/messages`(Anthropic 形式)、`/v1/responses` に対応しています。`/v1/models` にはこのパソコンのモデルが全部出て(文脈長 `context_length`、最大出力 `max_output_tokens` つき)、リクエストの `model` に別のモデルの ID を指定するとそのモデルに切り替わります(設定でオフにできます)。思考モードは `"chat_template_kwargs": {"enable_thinking": true}` か `"reasoning_effort"` で切り替えます。設定で LAN からの接続を許可すると、他の PC からも使えます(API キーの設定をおすすめします)。アプリが `max_tokens` を送らないときの回答の長さの上限は、設定の「API の最大出力トークン」で変えられます(既定 8192)。
121 unmodified lines122123124125126127121 unmodified lines## API`/v1/chat/completions` (streaming too), `/v1/models`, `/v1/messages` (Anthropic format) and `/v1/responses`.Thinking: `"chat_template_kwargs": {"enable_thinking": true}` or `"reasoning_effort"`. Allow LAN connections in thesettings to use it from other PCs (set an API key then). The longest answer when an app sends no `max_tokens` is the setting "API max output tokens" (default 8192).121 unmodified lines122123124125126127128121 unmodified lines## API`/v1/chat/completions` (streaming too), `/v1/models`, `/v1/messages` (Anthropic format) and `/v1/responses`.`/v1/models` lists every model on this PC (with `context_length` and `max_output_tokens`); a request whose `model` names another one switches to it (a setting turns this off).Thinking: `"chat_template_kwargs": {"enable_thinking": true}` or `"reasoning_effort"`. Allow LAN connections in thesettings to use it from other PCs (set an API key then). The longest answer when an app sends no `max_tokens` is the setting "API max output tokens" (default 8192).
1 unmodified line2345671 unmodified line(A working name: the product's name is set here and in the install scripts.)"""__version__ = "1.1.0"NAME = "onwx"TITLE = "onwx (AMD Ryzen AI NPU)"1 unmodified line2345671 unmodified line(A working name: the product's name is set here and in the install scripts.)"""__version__ = "1.2.0"NAME = "onwx"TITLE = "onwx (AMD Ryzen AI NPU)"
62 unmodified lines63646566676869604 unmodified lines67467567667767867962 unmodified lines"autostart_server": True, "login_start": False, "models_dir": "", "model_folders": [], "update_check": True,"think_default": False, "lang": "auto", "cpu_glue": False, "api_max_tokens": 8192, "expert_gb": "auto","api_sampling": "greedy", "api_temperature": 0.7, "api_top_p": 0.95, "api_top_k": 20, "api_presence": 0.0,"model_prefs": {}}CONTEXTS = ["1024", "2048", "3840", "8192", "16384", "32768", "65536", "131072", "262144"] # (models built before the# pair-major cache take 3840 at most - engine.json's max_position_embeddings caps it)604 unmodified linesif str(cfg.get("expert_gb", "auto")) != "auto": # [0.9] the MoE's experts in memory (the rest from the SSD)env["ONWX_EXPERT_GB"] = str(cfg["expert_gb"])env["ONWX_MAX_TOKENS"] = str(int(cfg.get("api_max_tokens", 8192))) # [0.6.1] requests without max_tokensenv["ONWX_MODEL_KEY"] = cfg["model"] # the server reads this model's defaults (model_prefs) itself# API requests that send no sampling values (agent apps like OpenCode): greedy, the model's recommendation or setif cfg.get("api_sampling") == "recommended":62 unmodified lines6364656667686970604 unmodified lines67567667767867968068162 unmodified lines"autostart_server": True, "login_start": False, "models_dir": "", "model_folders": [], "update_check": True,"think_default": False, "lang": "auto", "cpu_glue": False, "api_max_tokens": 8192, "expert_gb": "auto","api_sampling": "greedy", "api_temperature": 0.7, "api_top_p": 0.95, "api_top_k": 20, "api_presence": 0.0,"model_prefs": {},"api_model_switch": True} # an API request naming another model loads itCONTEXTS = ["1024", "2048", "3840", "8192", "16384", "32768", "65536", "131072", "262144"] # (models built before the# pair-major cache take 3840 at most - engine.json's max_position_embeddings caps it)604 unmodified linesif str(cfg.get("expert_gb", "auto")) != "auto": # [0.9] the MoE's experts in memory (the rest from the SSD)env["ONWX_EXPERT_GB"] = str(cfg["expert_gb"])env["ONWX_MAX_TOKENS"] = str(int(cfg.get("api_max_tokens", 8192))) # [0.6.1] requests without max_tokensenv["ONWX_API_SWITCH"] = "1" if cfg.get("api_model_switch", True) else "0" # model choice from the APIenv["ONWX_MODEL_KEY"] = cfg["model"] # the server reads this model's defaults (model_prefs) itself# API requests that send no sampling values (agent apps like OpenCode): greedy, the model's recommendation or setif cfg.get("api_sampling") == "recommended":
206 unmodified lines207208209210211212157 unmodified lines370371372373374375206 unmodified linesb = await _body(request)if not isinstance(b.get("messages"), list):raise HTTPException(400, "messages (a list) is required")msgs, kw = await prepare(_parse(anthropic_to_chat, b))mid, model = f"msg_{uuid.uuid4().hex[:24]}", S.MODEL_IDif not b.get("stream"):157 unmodified linesb = await _body(request)if "input" not in b:raise HTTPException(400, "input is required")chat, history = _parse(responses_to_chat, b)msgs, kw = await prepare(chat)rid = f"resp_{uuid.uuid4().hex[:24]}"206 unmodified lines207208209210211212213157 unmodified lines371372373374375376377206 unmodified linesb = await _body(request)if not isinstance(b.get("messages"), list):raise HTTPException(400, "messages (a list) is required")await S.ensure_model(b.get("model")) # another installed model named: load itmsgs, kw = await prepare(_parse(anthropic_to_chat, b))mid, model = f"msg_{uuid.uuid4().hex[:24]}", S.MODEL_IDif not b.get("stream"):157 unmodified linesb = await _body(request)if "input" not in b:raise HTTPException(400, "input is required")await S.ensure_model(b.get("model"))chat, history = _parse(responses_to_chat, b)msgs, kw = await prepare(chat)rid = f"resp_{uuid.uuid4().hex[:24]}"
4 unmodified lines5678910371 unmodified lines3823833843853863874 unmodified lines"API の最大出力トークン": "API max output tokens","文脈の残りまで": "Up to the rest of the context","アプリが上限を指定しないときの、1 回の回答の長さの上限です(エージェントがファイルを書くときなどに効きます)。大きくしても使用メモリは増えません。": "The longest single answer when an app sets no limit (matters when agents write files). A larger value uses no more memory.","CPU も使ってプロンプトの読み込みを速くする(消費電力が増えます)": "Use the CPU too, to read prompts faster (uses more power)","長いプロンプトほど効きます。ノート PC ではファンの音が大きくなることがあります。": "Helps most with long prompts. On a laptop the fan may get louder."," + 画像 {0}秒": " + image {0} s",371 unmodified lines"API の最大出力トークン": "API 最大输出 token 数","文脈の残りまで": "直到上下文用完","アプリが上限を指定しないときの、1 回の回答の長さの上限です(エージェントがファイルを書くときなどに効きます)。大きくしても使用メモリは増えません。": "应用未指定上限时,单次回答长度的上限(智能体写文件时会用到)。调大不会增加内存占用。","CPU も使ってプロンプトの読み込みを速くする(消費電力が増えます)": "同时使用 CPU 加快读取提示词(耗电增加)","長いプロンプトほど効きます。ノート PC ではファンの音が大きくなることがあります。": "提示词越长效果越明显。笔记本电脑的风扇可能会更响。"," + 画像 {0}秒": " + 图像 {0} 秒",4 unmodified lines56789101112371 unmodified lines3843853863873883893903914 unmodified lines"API の最大出力トークン": "API max output tokens","文脈の残りまで": "Up to the rest of the context","アプリが上限を指定しないときの、1 回の回答の長さの上限です(エージェントがファイルを書くときなどに効きます)。大きくしても使用メモリは増えません。": "The longest single answer when an app sets no limit (matters when agents write files). A larger value uses no more memory.","API からモデルを切り替えられるようにする": "Let API requests switch models","API のリクエストが、このパソコンにある別のモデルの名前(/v1/models に出る ID)を指定すると、今のモデルを閉じてそのモデルを読み込みます(数十秒かかります。同時に読み込むのは 1 つだけです)。知らない名前のときは今のモデルが答えます。": "When an API request names another model on this PC (an id from /v1/models), the running model is closed and that one loads (some tens of seconds; one model at a time). A name it does not know is answered by the running model.","CPU も使ってプロンプトの読み込みを速くする(消費電力が増えます)": "Use the CPU too, to read prompts faster (uses more power)","長いプロンプトほど効きます。ノート PC ではファンの音が大きくなることがあります。": "Helps most with long prompts. On a laptop the fan may get louder."," + 画像 {0}秒": " + image {0} s",371 unmodified lines"API の最大出力トークン": "API 最大输出 token 数","文脈の残りまで": "直到上下文用完","アプリが上限を指定しないときの、1 回の回答の長さの上限です(エージェントがファイルを書くときなどに効きます)。大きくしても使用メモリは増えません。": "应用未指定上限时,单次回答长度的上限(智能体写文件时会用到)。调大不会增加内存占用。","API からモデルを切り替えられるようにする": "允许通过 API 切换模型","API のリクエストが、このパソコンにある別のモデルの名前(/v1/models に出る ID)を指定すると、今のモデルを閉じてそのモデルを読み込みます(数十秒かかります。同時に読み込むのは 1 つだけです)。知らない名前のときは今のモデルが答えます。": "API 请求指定本机上的另一个模型名称(/v1/models 中的 ID)时,会关闭当前模型并加载该模型(需要数十秒;同一时间只加载一个)。名称未知时由当前模型回答。","CPU も使ってプロンプトの読み込みを速くする(消費電力が増えます)": "同时使用 CPU 加快读取提示词(耗电增加)","長いプロンプトほど効きます。ノート PC ではファンの音が大きくなることがあります。": "提示词越长效果越明显。笔记本电脑的风扇可能会更响。"," + 画像 {0}秒": " + 图像 {0} 秒",
450 unmodified lines45145245345445545645716 unmodified lines474475476477478479480450 unmodified linesif new.get("lang", "auto") not in ("auto", *LANGS):new = {k: v for k, v in new.items() if k != "lang"}old = dict(cfg)for k in ("lan", "api_key", "autostart_server", "login_start", "update_check", "lang", "think_default", "cpu_glue"):if k in new:cfg[k] = new[k]if str(new.get("expert_gb", "")) in EXPERT_GB:16 unmodified linescfg["context_chosen"] = True # (the old 1024 default moves up; a choice stays)cfg["port"], cfg["context"] = port, ctxserver_keys = ("lan", "api_key", "port", "context", "think_default", "cpu_glue", "api_max_tokens", "expert_gb","api_sampling", "api_temperature", "api_top_p", "api_top_k", "api_presence")app.save_config(cfg)i18n.current(cfg) # messages switch language right awaytry:450 unmodified lines45145245345445545645716 unmodified lines474475476477478479480450 unmodified linesif new.get("lang", "auto") not in ("auto", *LANGS):new = {k: v for k, v in new.items() if k != "lang"}old = dict(cfg)for k in ("lan", "api_key", "autostart_server", "login_start", "update_check", "lang", "think_default", "cpu_glue", "api_model_switch"):if k in new:cfg[k] = new[k]if str(new.get("expert_gb", "")) in EXPERT_GB:16 unmodified linescfg["context_chosen"] = True # (the old 1024 default moves up; a choice stays)cfg["port"], cfg["context"] = port, ctxserver_keys = ("lan", "api_key", "port", "context", "think_default", "cpu_glue", "api_max_tokens", "expert_gb","api_sampling", "api_temperature", "api_top_p", "api_top_k", "api_presence", "api_model_switch")app.save_config(cfg)i18n.current(cfg) # messages switch language right awaytry:
12345678910451 unmodified lines46246346446546646746846947047147221 unmodified lines49449549649749849950050150250350450550650750850951051151251331 unmodified lines54554654754854955033 unmodified lines58458558658758858959088 unmodified lines6796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107112 unmodified lines7147157167177187197207217227237247257267275 unmodified lines733734735736737738"""OpenAI-compatible API server for an onwx model on the AMD Ryzen AI NPU (point other apps at http://HOST:PORT/v1).GET / what this server is: model, OpenAI base URL, endpoints (JSON)GET /v1/modelsGET /v1/models/{id}POST /v1/chat/completions (stream true/false; text parts - the models take no images); responsesalso carry "onwx_stats" (prefill / decode speed, reused tokens) - extra fieldGET /health 200 when the model is loadedGET /chat browser chat UI for trying the modelGET /check verification page: speed, multi-turn reuse451 unmodified lines"openai_base_url": base + "/v1", "api_key_required": bool(API_KEY),"endpoints": {"models": "/v1/models", "chat_completions": "/v1/chat/completions", "health": "/health","chat_ui": "/chat", "check_page": "/check", "info": "/api/info"},"context": info.get("max_context"), "vision": info.get("vision")}@app.get("/health")def health():return {"status": "ok", "model": MODEL_ID}21 unmodified linesSTARTED = int(time.time())def _model_card():return {"id": MODEL_ID, "object": "model", "created": STARTED, "owned_by": "local-npu"}@app.get("/v1/models")def models():return {"object": "list", "data": [_model_card()]}@app.get("/v1/models/{model_id:path}")def model(model_id: str):if model_id != MODEL_ID:raise HTTPException(404, f"model {model_id!r} not found (this server runs {MODEL_ID!r})")return _model_card()def finalize(text, tools, finish):31 unmodified linesraise HTTPException(400, "the request body is not valid JSON")if not isinstance(body, dict) or not isinstance(body.get("messages"), list):raise HTTPException(400, "messages (a list) is required")kw = gen_args(body)loop = asyncio.get_running_loop()try: # images may be downloaded: not on the event loop33 unmodified linesyield chunk({"content": rest[sent:]})for i, tc in enumerate(calls):yield chunk({"tool_calls": [dict(tc, index=i)]})yield chunk({}, finish, onwx_stats=stats_of(d))if (body.get("stream_options") or {}).get("include_usage"): # OpenAI: its own last chunkyield f"data: {json.dumps({'id': cid, 'object': 'chat.completion.chunk', 'created': created, 'model': MODEL_ID, 'choices': [], 'usage': usage_of(d)})}\n\n"elif tools:88 unmodified linesk32.SetPriorityClass(k32.GetCurrentProcess(), 0x8000 if busy and want == "above" else 0x20)def main(argv=None):global pipe, MODEL_ID, API_KEY, API_SAMPLINGap = argparse.ArgumentParser(prog="onwx serve", description="chat UI + OpenAI-compatible API on the AMD Ryzen AI NPU")ap.add_argument("model", help="onwx model folder, or a Hugging Face repo id (downloaded into ./models)")ap.add_argument("--host", default="127.0.0.1")ap.add_argument("--port", type=int, default=8100)ap.add_argument("--device", default="NPU", help=argparse.SUPPRESS) # (the NPU only; kept for old launchers)ap.add_argument("--name", help="model id / title (default: engine directory name)")ap.add_argument("--context", type=int, default=None,help="context length in tokens (default 32768, at most the model's maximum); no recompile")ap.add_argument("--open", action="store_true", help="open the chat UI in the default browser once loaded")ap.add_argument("--no-pld", action="store_true", help="disable prompt lookup decoding")ap.add_argument("--api-key", help="require this key as a Bearer token on /v1 from other machines ""(e.g. with --host 0.0.0.0)")a = ap.parse_args(argv)API_KEY = a.api_key or os.environ.get("ONWX_API_KEY") or Nonefrom onwx.hub import resolvea.engine = resolve(a.model)from onwx.xdna import amd_npunpu = amd_npu()print(f"[onwx] {__version__} | {npu or 'no AMD NPU found'}", flush=True)if not npu:sys.exit("ERROR: no AMD Ryzen AI NPU (XDNA2) found - is the NPU driver installed?")from onwx.chat import ChatEnginepipe = ChatEngine(a.engine, a.device, context=a.context, pld=not a.no_pld)set_priority(False)MODEL_ID = a.name or os.path.basename(os.path.normpath(a.engine))v = pipe.visioninfo.update(model=MODEL_ID, title=MODEL_ID, devices={"lm": "NPU"}, fast=False, vision=bool(v),image_px=v.get("image_px") if v else None,2 unmodified linesnote=f"文脈は約{pipe.max_context}トークン", context=pipe.max_context, pld=pipe.pld,mtp=getattr(pipe.model, "mtp", None) is not None)try:with open(os.path.join(a.engine, "config.json"), encoding="utf8") as f:arch = json.load(f).get("model_type") or ""except (OSError, ValueError):arch = ""# greedy Gemma on the NPU can fall into repeating one word (fp16 on the NPU tips a near tie; the same happens with# any onwx version): the pages suggest a repetition penalty, the API default stays 1.0 (OpenAI behaviour)info.update(arch=arch, rep_hint=1.2 if arch.startswith("gemma") else None, sampling=recommended_sampling(arch, a.engine))want = os.environ.get("ONWX_API_SAMPLING")if want == "recommended":API_SAMPLING = {k: v for k, v in (info["sampling"] or {}).items() if k != "source"} or Noneelif want:5 unmodified lines"custom" if API_SAMPLING else "greedy")if API_SAMPLING:print(f"[api] requests without sampling values use {API_SAMPLING}", flush=True)if a.open:import webbrowserthreading.Timer(1.5, webbrowser.open, [f"http://{'localhost' if a.host in ('0.0.0.0', '127.0.0.1') else a.host}:{a.port}/chat"]).start()12345678910111213141516451 unmodified lines46846947047147247347447547647747847948021 unmodified lines50250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254331 unmodified lines57557657757857958058133 unmodified lines61561661761861962062162262388 unmodified lines7127137147157167177187197207217227237242 unmodified lines7277287297307317327337347357367377387397407415 unmodified lines747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889"""OpenAI-compatible API server for an onwx model on the AMD Ryzen AI NPU (point other apps at http://HOST:PORT/v1).GET / what this server is: model, OpenAI base URL, endpoints (JSON)GET /v1/models the loaded model with its limits: context_length (= max_model_len, max_context_length,meta.n_ctx) and max_output_tokens (what a request without max_tokens gets), "loaded":true; then the app's other models ("loaded": false). A request whose "model" names oneof them loads it first (the running one is closed: one model in memory at a time); aname this server does not know is answered by the loaded model. ONWX_API_SWITCH=0 (theapp's setting off): only the loaded model is listed / usedGET /v1/models/{id}POST /v1/chat/completions (stream true/false; text parts - the models take no images); responsesalso carry "onwx_stats" (prefill / decode speed, reused tokens) - extra field;"usage" (token counts) in a whole answer and on a stream's last chunkGET /health 200 when the model is loadedGET /chat browser chat UI for trying the modelGET /check verification page: speed, multi-turn reuse451 unmodified lines"openai_base_url": base + "/v1", "api_key_required": bool(API_KEY),"endpoints": {"models": "/v1/models", "chat_completions": "/v1/chat/completions", "health": "/health","chat_ui": "/chat", "check_page": "/check", "info": "/api/info"},"context": info.get("max_context"), "max_output_tokens": max_output_tokens(), "vision": info.get("vision")}@app.get("/health")def health():if SWITCHING.is_set() or pipe is None: # a model switch under wayreturn JSONResponse({"status": "loading", "model": MODEL_ID}, status_code=503)return {"status": "ok", "model": MODEL_ID}21 unmodified linesSTARTED = int(time.time())def max_output_tokens():"""The answer length a request without max_tokens gets (the setting; 0 = up to the context's end)."""ctx = info.get("max_context") or 0mx = int(os.environ.get("ONWX_MAX_TOKENS", "8192") or 0)return min(mx, ctx) if mx and ctx else (mx or ctx or None)def _model_card(mid=None):# the limits under the names clients read them from: context_length (OpenRouter / Open WebUI), max_model_len# (vLLM), max_context_length (LM Studio), meta.n_ctx (llama.cpp's server). Another installed model (mid): the# context setting it would load with (at most its own maximum, which shows once it is loaded).loaded = mid is None or mid == MODEL_IDctx = info.get("max_context") if loaded else SERVE.get("context")mx = int(os.environ.get("ONWX_MAX_TOKENS", "8192") or 0)out = max_output_tokens() if loaded else (min(mx, ctx) if mx and ctx else (mx or ctx or None))return {"id": MODEL_ID if loaded else mid, "object": "model", "created": STARTED, "owned_by": "local-npu","loaded": loaded, "context_length": ctx, "max_model_len": ctx, "max_context_length": ctx,"max_output_tokens": out, "meta": {"n_ctx": ctx}}@app.get("/v1/models")def models():"""The loaded model first, then (when switching is allowed) every other model the app has: a request naming oneloads it."""others = [m for m in installed_models() if m != MODEL_ID] if switch_allowed() else []return {"object": "list", "data": [_model_card()] + [_model_card(m) for m in others]}@app.get("/v1/models/{model_id:path}")def model(model_id: str):if model_id == MODEL_ID:return _model_card()hit = next((m for m, (k, _) in installed_models().items() if model_id in (m, k)), None) if switch_allowed() else Noneif hit is None:raise HTTPException(404, f"model {model_id!r} not found (this server runs {MODEL_ID!r})")return _model_card(hit)def finalize(text, tools, finish):31 unmodified linesraise HTTPException(400, "the request body is not valid JSON")if not isinstance(body, dict) or not isinstance(body.get("messages"), list):raise HTTPException(400, "messages (a list) is required")await ensure_model(body.get("model")) # another installed model named: load itkw = gen_args(body)loop = asyncio.get_running_loop()try: # images may be downloaded: not on the event loop33 unmodified linesyield chunk({"content": rest[sent:]})for i, tc in enumerate(calls):yield chunk({"tool_calls": [dict(tc, index=i)]})# the token counts on the last chunk too (as llama.cpp's server does): clients that do not# send stream_options.include_usage still see themyield chunk({}, finish, usage=usage_of(d), onwx_stats=stats_of(d))if (body.get("stream_options") or {}).get("include_usage"): # OpenAI: its own last chunkyield f"data: {json.dumps({'id': cid, 'object': 'chat.completion.chunk', 'created': created, 'model': MODEL_ID, 'choices': [], 'usage': usage_of(d)})}\n\n"elif tools:88 unmodified linesk32.SetPriorityClass(k32.GetCurrentProcess(), 0x8000 if busy and want == "above" else 0x20)def load_model(path, name=None):"""Load a model as the one this server runs: pipe, MODEL_ID, info and the sampling defaults. main() and amodel switch (switch_model) both come here."""global pipe, MODEL_ID, API_SAMPLINGfrom onwx.chat import ChatEnginepipe = ChatEngine(path, SERVE["device"], context=SERVE["context"], pld=SERVE["pld"])MODEL_ID = name or os.path.basename(os.path.normpath(path))v = pipe.visioninfo.update(model=MODEL_ID, title=MODEL_ID, devices={"lm": "NPU"}, fast=False, vision=bool(v),image_px=v.get("image_px") if v else None,2 unmodified linesnote=f"文脈は約{pipe.max_context}トークン", context=pipe.max_context, pld=pipe.pld,mtp=getattr(pipe.model, "mtp", None) is not None)try:with open(os.path.join(path, "config.json"), encoding="utf8") as f:arch = json.load(f).get("model_type") or ""except (OSError, ValueError):arch = ""# greedy Gemma on the NPU can fall into repeating one word (fp16 on the NPU tips a near tie; the same happens with# any onwx version): the pages suggest a repetition penalty, the API default stays 1.0 (OpenAI behaviour)info.update(arch=arch, rep_hint=1.2 if arch.startswith("gemma") else None, sampling=recommended_sampling(arch, path))want = os.environ.get("ONWX_API_SAMPLING")API_SAMPLING = Noneif want == "recommended":API_SAMPLING = {k: v for k, v in (info["sampling"] or {}).items() if k != "source"} or Noneelif want:5 unmodified lines"custom" if API_SAMPLING else "greedy")if API_SAMPLING:print(f"[api] requests without sampling values use {API_SAMPLING}", flush=True)# ---------------------------------------------------------------- model choice from the API# A request's "model" naming another model the app has (its id in /v1/models, or the app's key) unloads the running one# and loads that one first (one model in memory at a time), as Ollama and LM Studio do. A name this server does not# know - clients send their own defaults ("gpt-4o", ...) - is served by the loaded model, as before. The app's setting# "api_model_switch" (ONWX_API_SWITCH=0) turns switching off.MODEL_KEY = None # the app's key of the loaded model (catalog repo id or folder name; ONWX_MODEL_KEY)SERVE = {} # how main() loads models: device, context, pld, portSWITCHING = threading.Event() # set while a switch unloads / loads (/health answers 503: the window shows loading)def switch_allowed():return os.environ.get("ONWX_API_SWITCH", "1") != "0"def installed_models():"""{API id: (app key, path)} of every model the app finds in its folders (the ids of /v1/models)."""try:from onwx import app as Afound = A.installed(A.load_config())except Exception:return {}out = {}for key, path in found.items():if path and os.path.isdir(path):out.setdefault(key.split("/")[-1], (key, path))return outdef resolve_model(name):"""(app key, path) when a request's model names another installed model, else None (the loaded one serves)."""if not name or not switch_allowed():return Nonen = str(name).strip().lower()if n in ((MODEL_ID or "").lower(), (MODEL_KEY or "").lower()):return Nonefor mid, (key, path) in installed_models().items():if n in (mid.lower(), key.lower()):return None if key == MODEL_KEY else (key, path)return Nonedef switch_model(key, path):"""Unload the running model and load `key` (called with `lock` held, so no generation runs). If the new one doesnot load, the old one is loaded again and the error goes to the client."""global pipe, MODEL_KEYimport gcold_key = MODEL_KEYold_path = installed_models().get((MODEL_KEY or "").split("/")[-1], (None, None))[1]print(f"[api] switching model: {MODEL_ID} -> {key.split('/')[-1]}", flush=True)SWITCHING.set()t = time.time()try:old = pipepipe = Noneclose = getattr(getattr(old, "model", None), "close", None)if close:close()del oldgc.collect()try:os.environ["ONWX_MODEL_KEY"] = keyload_model(path, key.split("/")[-1])MODEL_KEY = keyexcept Exception:if old_path: # back to the model that ranos.environ["ONWX_MODEL_KEY"] = old_key or ""load_model(old_path, (old_key or "").split("/")[-1] or None)raiseprint(f"[api] {MODEL_ID} loaded in {time.time() - t:.1f}s", flush=True)_record_model(key, path)finally:SWITCHING.clear()async def ensure_model(name):"""Before a request's arguments are read (the sampling defaults and thinking style are the model's): the model itnames loaded, after any generation that runs now (the same lock). A failed load: 500 with why."""if resolve_model(name) is None:returndef work():with lock:want = resolve_model(name) # (another request may have switched to it meanwhile)if want:switch_model(*want)try:await asyncio.get_running_loop().run_in_executor(None, work)except Exception as e:raise HTTPException(500, f"model {name!r} could not be loaded: {type(e).__name__}: {e}")def _record_model(key, path):"""The window and the next start follow the switch: the server record (pid file) and the chosen model."""try:from onwx import app as Ap = A.PIDFILE()with open(p, encoding="utf8") as f:d = json.load(f)if int(d.get("port", -1)) == int(SERVE.get("port", -2)) and not d.get("stopping"):d.update(model=key, path=path)with open(p + ".tmp", "w") as f:json.dump(d, f)os.replace(p + ".tmp", p)A.update_config(model=key)except Exception as e:print(f"[api] could not record the model switch: {e}", flush=True)def main(argv=None):global API_KEY, MODEL_KEYap = argparse.ArgumentParser(prog="onwx serve", description="chat UI + OpenAI-compatible API on the AMD Ryzen AI NPU")ap.add_argument("model", help="onwx model folder, or a Hugging Face repo id (downloaded into ./models)")ap.add_argument("--host", default="127.0.0.1")ap.add_argument("--port", type=int, default=8100)ap.add_argument("--device", default="NPU", help=argparse.SUPPRESS) # (the NPU only; kept for old launchers)ap.add_argument("--name", help="model id / title (default: engine directory name)")ap.add_argument("--context", type=int, default=None,help="context length in tokens (default 32768, at most the model's maximum); no recompile")ap.add_argument("--open", action="store_true", help="open the chat UI in the default browser once loaded")ap.add_argument("--no-pld", action="store_true", help="disable prompt lookup decoding")ap.add_argument("--api-key", help="require this key as a Bearer token on /v1 from other machines ""(e.g. with --host 0.0.0.0)")a = ap.parse_args(argv)API_KEY = a.api_key or os.environ.get("ONWX_API_KEY") or Nonefrom onwx.hub import resolvea.engine = resolve(a.model)from onwx.xdna import amd_npunpu = amd_npu()print(f"[onwx] {__version__} | {npu or 'no AMD NPU found'}", flush=True)if not npu:sys.exit("ERROR: no AMD Ryzen AI NPU (XDNA2) found - is the NPU driver installed?")SERVE.update(device=a.device, context=a.context, pld=not a.no_pld, port=a.port)MODEL_KEY = os.environ.get("ONWX_MODEL_KEY") or a.nameload_model(a.engine, a.name)set_priority(False)if a.open:import webbrowserthreading.Timer(1.5, webbrowser.open, [f"http://{'localhost' if a.host in ('0.0.0.0', '127.0.0.1') else a.host}:{a.port}/chat"]).start()
241 unmodified lines242243244245246247182 unmodified lines430431432433434435116 unmodified lines552553554555556557558241 unmodified lines<span class="desc">会話で使える最大の長さ(モデルの上限まで。長いほどメモリを使い、長い会話ほど遅くなります)。</span></div><div class="opt"><span class="k">API の最大出力トークン</span><select id="f-api_max_tokens" style="width:150px"><option value="2048">2048</option><option value="4096">4096</option><option value="8192">8192</option><option value="16384">16384</option><option value="32768">32768</option><option value="0">文脈の残りまで</option></select><span class="desc">アプリが上限を指定しないときの、1 回の回答の長さの上限です(エージェントがファイルを書くときなどに効きます)。大きくしても使用メモリは増えません。</span></div><label class="swrow"><span class="switch"><input type="checkbox" id="f-lan"><i></i></span><span>LAN からの接続を許可する<span class="desc">他の PC から API を使えるようにします。API キーの設定をおすすめします。</span></span></label><div class="opt"><span class="k">MoE のエキスパートのメモリ</span><select id="f-expert_gb" style="width:150px"><option value="auto">自動</option><option value="all">すべてメモリに</option><option value="4">4 GB</option><option value="6">6 GB</option><option value="8">8 GB</option><option value="12">12 GB</option></select><span class="desc">MoE のモデル(Qwen3.6 35B-A3B)で、エキスパートの重みをどれだけメモリに置くか。足りない分は SSD から読みます。自動:モデル全体がメモリの 7 割に収まればすべてメモリに、収まらなければ残りの分だけ。少なくすると使用メモリが減り、生成が少し遅くなります(4 GB で約 7 GB・約 15 tok/s、すべてなら約 20 GB・約 20 tok/s)。</span></div>182 unmodified linesfor (const k of ["autostart_server", "login_start", "lan", "update_check"]) $("f-" + k).checked = c[k] !== false && !!(c[k] ?? true);$("f-cpu_glue").checked = !!c.cpu_glue; // (off unless chosen)$("f-api_max_tokens").value = String(c.api_max_tokens ?? 8192);$("f-expert_gb").value = String(c.expert_gb ?? "auto");}}116 unmodified linesasync function saveSettings() {const body = {port: $("f-port").value, context: $("f-context").value, api_key: $("f-api_key").value.trim(), lang: $("f-lang").value,api_max_tokens: $("f-api_max_tokens").value, expert_gb: $("f-expert_gb").value};for (const k of ["autostart_server", "login_start", "lan", "update_check", "cpu_glue"]) body[k] = $("f-" + k).checked;const oldLang = S.config.lang || "auto";const r = await post("settings", body);if (r.error) return;241 unmodified lines242243244245246247248182 unmodified lines431432433434435436437116 unmodified lines554555556557558559560241 unmodified lines<span class="desc">会話で使える最大の長さ(モデルの上限まで。長いほどメモリを使い、長い会話ほど遅くなります)。</span></div><div class="opt"><span class="k">API の最大出力トークン</span><select id="f-api_max_tokens" style="width:150px"><option value="2048">2048</option><option value="4096">4096</option><option value="8192">8192</option><option value="16384">16384</option><option value="32768">32768</option><option value="0">文脈の残りまで</option></select><span class="desc">アプリが上限を指定しないときの、1 回の回答の長さの上限です(エージェントがファイルを書くときなどに効きます)。大きくしても使用メモリは増えません。</span></div><label class="swrow"><span class="switch"><input type="checkbox" id="f-api_model_switch"><i></i></span><span>API からモデルを切り替えられるようにする<span class="desc">API のリクエストが、このパソコンにある別のモデルの名前(/v1/models に出る ID)を指定すると、今のモデルを閉じてそのモデルを読み込みます(数十秒かかります。同時に読み込むのは 1 つだけです)。知らない名前のときは今のモデルが答えます。</span></span></label><label class="swrow"><span class="switch"><input type="checkbox" id="f-lan"><i></i></span><span>LAN からの接続を許可する<span class="desc">他の PC から API を使えるようにします。API キーの設定をおすすめします。</span></span></label><div class="opt"><span class="k">MoE のエキスパートのメモリ</span><select id="f-expert_gb" style="width:150px"><option value="auto">自動</option><option value="all">すべてメモリに</option><option value="4">4 GB</option><option value="6">6 GB</option><option value="8">8 GB</option><option value="12">12 GB</option></select><span class="desc">MoE のモデル(Qwen3.6 35B-A3B)で、エキスパートの重みをどれだけメモリに置くか。足りない分は SSD から読みます。自動:モデル全体がメモリの 7 割に収まればすべてメモリに、収まらなければ残りの分だけ。少なくすると使用メモリが減り、生成が少し遅くなります(4 GB で約 7 GB・約 15 tok/s、すべてなら約 20 GB・約 20 tok/s)。</span></div>182 unmodified linesfor (const k of ["autostart_server", "login_start", "lan", "update_check"]) $("f-" + k).checked = c[k] !== false && !!(c[k] ?? true);$("f-cpu_glue").checked = !!c.cpu_glue; // (off unless chosen)$("f-api_max_tokens").value = String(c.api_max_tokens ?? 8192);$("f-api_model_switch").checked = c.api_model_switch !== false; // (on unless turned off)$("f-expert_gb").value = String(c.expert_gb ?? "auto");}}116 unmodified linesasync function saveSettings() {const body = {port: $("f-port").value, context: $("f-context").value, api_key: $("f-api_key").value.trim(), lang: $("f-lang").value,api_max_tokens: $("f-api_max_tokens").value, expert_gb: $("f-expert_gb").value};for (const k of ["autostart_server", "login_start", "lan", "update_check", "cpu_glue", "api_model_switch"]) body[k] = $("f-" + k).checked;const oldLang = S.config.lang || "auto";const r = await post("settings", body);if (r.error) return;
236 unmodified lines23723823924024124228 unmodified lines2712722732742752763 unmodified lines28028128228328428528628728828929029129224 unmodified lines31731831932032132217 unmodified lines340341342343344345895 unmodified lines124112421243124412451246236 unmodified lines"""[0.7] release this context (its buffers must be gone): the objects go, XRT frees them"""self.kern = self.ctx = Noneclass ShimDev:"""bin/xdna_shim.dll (Windows) or bin/libxdna_shim.so: a C face over XRT's C++ API."""28 unmodified linesself.ctx = x.xs_open(str(xclbin).encode(), b"MLIR_AIE")if not self.ctx:raise RuntimeError("NPU open: " + x.xs_error().decode())def _chk(self, h, what):if not h:3 unmodified linesdef buf(self, nbytes, arg, cacheable=False):n = max(nbytes, 4)h = self._chk(self.x.xs_bo(self.ctx, n, int(cacheable), arg), "buffer")p = self._chk(self.x.xs_map(h), "map")return h, np.ctypeslib.as_array((C.c_uint8 * n).from_address(p))def sub(self, parent, nbytes, offset):return self._chk(self.x.xs_subbo(parent, nbytes, offset), "sub-buffer")def free(self, h):self.x.xs_bo_free(h)def sync(self, bo, to_dev):24 unmodified linesh = self.x.xs_prep(self.ctx, ins, n, b0, b1, b2, b3) if self.has_prep else Noneif self.has_prep and not h:raise RuntimeError("NPU prep: " + self.x.xs_error().decode())return hdef setarg(self, run, i, bo):17 unmodified linesself.x.xs_close(self.ctx)self.ctx = Nonedef open_device(xclbin):if os.name == "nt" or os.environ.get("ONWX_SHIM"):895 unmodified linesmtp = Noneexact_truncate = Falsedef __init__(self, d, context=None):self.dir = dself.rt = Bonsai(d, context)236 unmodified lines23723823924024124224324424528 unmodified lines2742752762772782792802812822833 unmodified lines28728828929029129229329429529629729829930030130230330424 unmodified lines32933033133233333433533617 unmodified lines354355356357358359360361362363364365366367368369370371372373374895 unmodified lines12701271127212731274127512761277127812791280128112821283236 unmodified lines"""[0.7] release this context (its buffers must be gone): the objects go, XRT frees them"""self.kern = self.ctx = Nonedef release(self): # [1.2] (see ShimDev.release)self.close()class ShimDev:"""bin/xdna_shim.dll (Windows) or bin/libxdna_shim.so: a C face over XRT's C++ API."""28 unmodified linesself.ctx = x.xs_open(str(xclbin).encode(), b"MLIR_AIE")if not self.ctx:raise RuntimeError("NPU open: " + x.xs_error().decode())# [1.2] what this context made, so release() can give it all back (a model switch in the server)self._bufs, self._subs, self._preps, self._kids = set(), set(), set(), []if base is not None:base._kids.append(self)def _chk(self, h, what):if not h:3 unmodified linesdef buf(self, nbytes, arg, cacheable=False):n = max(nbytes, 4)h = self._chk(self.x.xs_bo(self.ctx, n, int(cacheable), arg), "buffer")self._bufs.add(h)p = self._chk(self.x.xs_map(h), "map")return h, np.ctypeslib.as_array((C.c_uint8 * n).from_address(p))def sub(self, parent, nbytes, offset):h = self._chk(self.x.xs_subbo(parent, nbytes, offset), "sub-buffer")self._subs.add(h)return hdef free(self, h):self._subs.discard(h)self._bufs.discard(h)self.x.xs_bo_free(h)def sync(self, bo, to_dev):24 unmodified linesh = self.x.xs_prep(self.ctx, ins, n, b0, b1, b2, b3) if self.has_prep else Noneif self.has_prep and not h:raise RuntimeError("NPU prep: " + self.x.xs_error().decode())if h:self._preps.add(h)return hdef setarg(self, run, i, bo):17 unmodified linesself.x.xs_close(self.ctx)self.ctx = Nonedef release(self):"""[1.2] everything this context and the ones opened from it made: prepared runs, sub-buffers, buffers, thenthe contexts (children first). The numpy views of the buffers must not be used after this."""for k in reversed(self._kids):k.release()self._kids = []for h in self._preps:self.x.xs_unprep(h)for h in self._subs:self.x.xs_bo_free(h)for h in self._bufs:self.x.xs_bo_free(h)self._preps, self._subs, self._bufs = set(), set(), set()self.close()def open_device(xclbin):if os.name == "nt" or os.environ.get("ONWX_SHIM"):895 unmodified linesmtp = Noneexact_truncate = Falsedef close(self):"""[1.2] give the model's NPU memory back (the server switches models): every context, buffer and run itsruntime made from the root device. The model is unusable afterwards."""rt, self.rt = getattr(self, "rt", None), Nonedev = getattr(rt, "dev", None)if dev is not None:dev.release()def __init__(self, d, context=None):self.dir = dself.rt = Bonsai(d, context)
3 unmodified lines456789103 unmodified lines[project]name = "onwx"version = "1.1.0"description = "LLMs entirely on the AMD Ryzen AI NPU (XDNA2)"readme = "README.md"license = {text = "Apache-2.0"}3 unmodified lines456789103 unmodified lines[project]name = "onwx"version = "1.2.0"description = "LLMs entirely on the AMD Ryzen AI NPU (XDNA2)"readme = "README.md"license = {text = "Apache-2.0"}
CHANGELOG.md+6
CHANGELOG_en.md+6
README.md+1
README_en.md+1
onwx/__init__.py+1-1
onwx/app.py+3-1
onwx/compat.py+2
onwx/i18n.json+4
onwx/manager.py+2-2
onwx/server.py+188-37
onwx/web/manage.html+3-1
onwx/xdna.py+38-1
pyproject.toml+1-1