ryugyosoft commited on
Commit
48c6032
·
verified ·
1 Parent(s): dd42376

onwx 0.5.0: faster long-prompt attention, prompts past 32K, long-context fixes, MTP off past 24K, FLM comparison

Browse files
README.md CHANGED
@@ -26,6 +26,26 @@ LLM を **AMD Ryzen AI の NPU(XDNA2)だけで** 動かすアプリです。
26
  > Intel の NPU(Core Ultra)向けは姉妹アプリの [onw](https://huggingface.co/ryugyosoft/onw) です。onwx は AMD Ryzen AI 専用で、
27
  > モデルも NPU 用プログラムも別物です(互いのモデルは使えません)。
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  ## インストール(コマンドを 1 行貼るだけ)
30
 
31
  **Windows**
@@ -82,16 +102,16 @@ onwx chat ryugyosoft/Ternary-Bonsai-2-27B-onwx # 端末でチャット
82
  | モデル | ダウンロード | メモリ | プロンプトの読み込み(1,000 / 4,000 トークン) | 文章の生成 |
83
  |---|---|---|---|---|
84
  | [Ternary Bonsai 2 27B](https://huggingface.co/ryugyosoft/Ternary-Bonsai-2-27B-onwx)(三値・2 ビット、Qwen3.8-27B ベース) | 7.6 GB | 約 8.8 GB + 文脈 1k トークンあたり約 34 MB | 約 9.3 秒 / 約 28 秒 | 約 6.9 tok/s |
85
- | [Qwen3.5 9B](https://huggingface.co/ryugyosoft/Qwen3.5-9B-onwx)(int4、画像も読める) | 7.6 GB | 約 5.8 GB + 文脈 1k トークンあたり約 15 MB | 約 3.8 秒 / 約 9.8 秒 | 約 12 tok/s、温度 0 なら MTP で約 15 tok/s |
86
- | [Qwen3.5 4B](https://huggingface.co/ryugyosoft/Qwen3.5-4B-onwx)(int4、画像も読める) | 4.8 GB | 約 3.4 GB + 文脈 1k トークンあたり約 13 MB | 約 2.8 秒 / 約 7.9 秒 | 約 17 tok/s |
87
  | [llm-jp-4.1 8B thinking](https://huggingface.co/ryugyosoft/llm-jp-4.1-8b-onwx)(int4、日本語に強い) | 5.8 GB | 約 4.8 GB + 文脈 1k トークンあたり約 65 MB | 約 6.3 秒 / 約 13 秒 | 約 11 tok/s |
88
 
89
- (Ryzen AI Max+ 395・Windows・onwx 0.4.0 で測定。プロンプトの読み込みは 0.3.0 の 2〜7 倍の速さです)
90
 
91
  - プロンプトは NPU でまとめて読み込みます。256 トークン以上(llm-jp は 32 トークン以上)は 1,024 / 2,048 トークンずつ、NPU の 32 個の AI エンジン全部で 1 層ずつ計算します(行列計算は bfp16 の行列ユニット。重みはその層の直前に NPU 上で展開するので、使用メモリの増加は作業領域の約 0.5 GB だけです)。短いプロンプトは従来どおり 128 / 32 トークンずつの経路で読みます。
92
  - アテンションのキャッシュ(キーと値)は int8 で持つので、文脈 1k トークンあたりのメモリは 0.3.0 の半分です。
93
- - Qwen3.5 9B は温度 0(API の既定)のとき、モデルの MTP 層で次のトークンを先読みして速く生成します。出力は 1 トークンずつ生成したときと同じです(チャッ��画面の既定のサンプリングでは使いません。`ONWX_MTP=0` で止められます)。
94
- - 文脈は最大 262144 トークン(モデルの上限。llm-jp は 65536)です。既定は 3840 トークンで、設定で変えられます。文脈が長いほど遅くなります。
95
  - 思考モード(考えてから答える)とツール呼び出しに対応しています。画像は Qwen3.5 9B / 4B で読めます(画像のエンコーダーは CPU で動きます)。
96
  - 速度は NPU の電力モードを performance にして測った値です(管理者の PowerShell で `C:\Windows\System32\AMD\xrt-smi.exe configure --pmode performance`)。標準のままだと NPU のクロックが下がって 2 割ほど遅くなります。Ryzen AI 300 シリーズ(HX 370 など)も NPU は同じ 32 個の AI エンジンで、同じプログラムが動きます。Windows の AI 機能(Copilot+ の機能)が NPU を使っていると遅くなることがあります。
97
 
 
26
  > Intel の NPU(Core Ultra)向けは姉妹アプリの [onw](https://huggingface.co/ryugyosoft/onw) です。onwx は AMD Ryzen AI 専用で、
27
  > モデルも NPU 用プログラムも別物です(互いのモデルは使えません)。
28
 
29
+ ## 速さ(FastFlowLM との比較)
30
+
31
+ AMD Ryzen AI の NPU で LLM を動かす代表的なアプリ [FastFlowLM](https://github.com/FastFlowLM/FastFlowLM)(FLM)1.0.8 と、
32
+ **同じ測り方**で比べました(Qwen3.5 9B、Ryzen AI Max+ 395、NPU は performance モード)。プロンプトは FLM の `flm bench`
33
+ と同じ文章(長さ 128〜32K トークン)で、プロンプトを読み終わるまでの時間(TTFT)と、そのあと 32 トークンの生成を測っています。
34
+
35
+ **生成速度はどちらも MTP なし**(温度 0 で 1 トークンずつ)の値です。FLM の Qwen3.5 には MTP がないので、条件はそろっています。
36
+ onwx の MTP(温度 0 のときの先読み)を使った値は、生成のグラフに別の点で示しました。
37
+
38
+ <img src="images/answer_speed_vs_flm.svg" alt="512 トークンの回答の実効速度: どの長さでも onwx が速い" width="760">
39
+
40
+ <img src="images/prefill_vs_flm.svg" alt="プロンプトの読み込み速度" width="760">
41
+
42
+ <img src="images/decode_vs_flm.svg" alt="生成速度" width="760">
43
+
44
+ - 512 トークンの回答をプロンプトから書き終えるまでの実効速度(512 ÷ 合計時間)は、128〜32K のどの長さでも onwx が上です(MTP なしでも)。
45
+ - プロンプトの読み込みは 2K〜8K で onwx が速く、16K〜32K と 256〜1K では FLM が少し速いです(512 トークンで FLM 1.4 秒、onwx 2.7 秒)。
46
+ - 生成はどの長さでも onwx が 3〜4 割速く、MTP を使うと 8K までの文脈で約 14〜18 tok/s です(24K を超えると MTP は自動で止まります)。
47
+ - Ryzen AI 9 HX 370 でも傾向は同じでした(32K のプロンプト:FLM 379 tok/s、onwx 339 tok/s、生成 FLM 6.0 tok/s、onwx 8.9 tok/s)。
48
+
49
  ## インストール(コマンドを 1 行貼るだけ)
50
 
51
  **Windows**
 
102
  | モデル | ダウンロード | メモリ | プロンプトの読み込み(1,000 / 4,000 トークン) | 文章の生成 |
103
  |---|---|---|---|---|
104
  | [Ternary Bonsai 2 27B](https://huggingface.co/ryugyosoft/Ternary-Bonsai-2-27B-onwx)(三値・2 ビット、Qwen3.8-27B ベース) | 7.6 GB | 約 8.8 GB + 文脈 1k トークンあたり約 34 MB | 約 9.3 秒 / 約 28 秒 | 約 6.9 tok/s |
105
+ | [Qwen3.5 9B](https://huggingface.co/ryugyosoft/Qwen3.5-9B-onwx)(int4、画像も読める) | 7.6 GB | 約 5.8 GB + 文脈 1k トークンあたり約 15 MB | 約 2.9 秒 / 約 8.4 秒 | 約 12 tok/s、温度 0 なら MTP で約 15 tok/s |
106
+ | [Qwen3.5 4B](https://huggingface.co/ryugyosoft/Qwen3.5-4B-onwx)(int4、画像も読める) | 4.8 GB | 約 3.4 GB + 文脈 1k トークンあたり約 13 MB | 約 2.4 秒 / 約 7.2 秒 | 約 18 tok/s |
107
  | [llm-jp-4.1 8B thinking](https://huggingface.co/ryugyosoft/llm-jp-4.1-8b-onwx)(int4、日本語に強い) | 5.8 GB | 約 4.8 GB + 文脈 1k トークンあたり約 65 MB | 約 6.3 秒 / 約 13 秒 | 約 11 tok/s |
108
 
109
+ (Ryzen AI Max+ 395・Windows・onwx 0.5.0 で測定。プロンプトの読み込みは 0.3.0 の 2〜7 倍、32K のような長いプロンプトは 0.4.0 よりさらに約 2 割速くなりました)
110
 
111
  - プロンプトは NPU でまとめて読み込みます。256 トークン以上(llm-jp は 32 トークン以上)は 1,024 / 2,048 トークンずつ、NPU の 32 個の AI エンジン全部で 1 層ずつ計算します(行列計算は bfp16 の行列ユニット。重みはその層の直前に NPU 上で展開するので、使用メモリの増加は作業領域の約 0.5 GB だけです)。短いプロンプトは従来どおり 128 / 32 トークンずつの経路で読みます。
112
  - アテンションのキャッシュ(キーと値)は int8 で持つので、文脈 1k トークンあたりのメモリは 0.3.0 の半分です。
113
+ - Qwen3.5 9B は温度 0(API の既定)のとき、モデルの MTP 層で次のトークンを先読みして速く生成します。出力は 1 トークンずつ生成したときと同じです(チャット画面の既定のサンプリングでは使いません。`ONWX_MTP=0` で止められます)。文脈が 24K トークンを超えると、先読みの検証のほうが重くなるので自動で使わなくなります(`ONWX_MTP_MAX` で変更)。
114
+ - 文脈は最大 262144 トークン(モデルの上限。llm-jp は 65536)です。Qwen3.5 9B / 4B は 32K を超える長いプロンプトも NPU の新しい経路で読みます(9B、64K トークンで約 340 tok/s)。既定は 3840 トークンで、設定で変えられます。文脈が長いほど遅くなります。
115
  - 思考モード(考えてから答える)とツール呼び出しに対応しています。画像は Qwen3.5 9B / 4B で読めます(画像のエンコーダーは CPU で動きます)。
116
  - 速度は NPU の電力モードを performance にして測った値です(管理者の PowerShell で `C:\Windows\System32\AMD\xrt-smi.exe configure --pmode performance`)。標準のままだと NPU のクロックが下がって 2 割ほど遅くなります。Ryzen AI 300 シリーズ(HX 370 など)も NPU は同じ 32 個の AI エンジンで、同じプログラムが動きます。Windows の AI 機能(Copilot+ の機能)が NPU を使っていると遅くなることがあります。
117
 
README_en.md CHANGED
@@ -14,6 +14,26 @@ between them, settings).
14
  > For Intel NPUs (Core Ultra) see the sister app [onw](https://huggingface.co/ryugyosoft/onw). onwx is AMD Ryzen AI
15
  > only, with its own models and NPU programs (the two apps' models are not interchangeable).
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ## Install (paste one line)
18
 
19
  **Windows** - open "Windows PowerShell" from the Start menu (no administrator needed) and paste:
@@ -65,16 +85,16 @@ onwx chat ryugyosoft/Ternary-Bonsai-2-27B-onwx # chat in the terminal
65
  | Model | Download | Memory | Prompt reading (1,000 / 4,000 tokens) | Generation |
66
  |---|---|---|---|---|
67
  | [Ternary Bonsai 2 27B](https://huggingface.co/ryugyosoft/Ternary-Bonsai-2-27B-onwx) (ternary / 2-bit, from Qwen3.8-27B) | 7.6 GB | ~8.8 GB + ~34 MB per 1k tokens of context | ~9.3 s / ~28 s | ~6.9 tok/s |
68
- | [Qwen3.5 9B](https://huggingface.co/ryugyosoft/Qwen3.5-9B-onwx) (int4, reads images) | 7.6 GB | ~5.8 GB + ~15 MB per 1k tokens of context | ~3.8 s / ~9.8 s | ~12 tok/s, ~15 tok/s with MTP at temperature 0 |
69
- | [Qwen3.5 4B](https://huggingface.co/ryugyosoft/Qwen3.5-4B-onwx) (int4, reads images) | 4.8 GB | ~3.4 GB + ~13 MB per 1k tokens of context | ~2.8 s / ~7.9 s | ~17 tok/s |
70
  | [llm-jp-4.1 8B thinking](https://huggingface.co/ryugyosoft/llm-jp-4.1-8b-onwx) (int4, strong in Japanese) | 5.8 GB | ~4.8 GB + ~65 MB per 1k tokens of context | ~6.3 s / ~13 s | ~11 tok/s |
71
 
72
- (Measured on a Ryzen AI Max+ 395, Windows, onwx 0.4.0. Prompts read 2-7x faster than with 0.3.0.)
73
 
74
  - Prompts are read on the NPU in batches. From 256 tokens on (llm-jp: 32) 1,024 / 2,048 tokens at a time, each layer on all 32 AI Engines of the NPU (bfp16 matrix products; the weights are expanded on the NPU right before their layer, so only a ~0.5 GB work area is added to the memory). Short prompts take the 128 / 32-token paths as before.
75
  - The attention cache (keys and values) is kept as int8: half the memory per 1k tokens of context of 0.3.0.
76
- - At temperature 0 (the API default) Qwen3.5 9B drafts the next token with the model's MTP layer and generates faster; the output is the same as one token at a time (not used with the chat window's default sampling; `ONWX_MTP=0` turns it off).
77
- - Context: up to 262144 tokens (the model's limit; llm-jp 65536). The default is 3840 tokens, changeable in the settings. Longer contexts are slower.
78
  - Thinking mode and tool calls are supported. Images work with Qwen3.5 9B / 4B (the image encoder runs on the CPU).
79
  - Speeds are measured with the NPU power mode set to performance (administrator PowerShell: `C:\Windows\System32\AMD\xrt-smi.exe configure --pmode performance`); in the default mode the NPU clocks lower and it is about 20% slower. The Ryzen AI 300 series (HX 370 and others) has the same 32-AI-Engine NPU and runs the same programs. Windows AI features (Copilot+) using the NPU can slow it down.
80
 
 
14
  > For Intel NPUs (Core Ultra) see the sister app [onw](https://huggingface.co/ryugyosoft/onw). onwx is AMD Ryzen AI
15
  > only, with its own models and NPU programs (the two apps' models are not interchangeable).
16
 
17
+ ## Speed (compared with FastFlowLM)
18
+
19
+ Measured against [FastFlowLM](https://github.com/FastFlowLM/FastFlowLM) (FLM) 1.0.8, the well-known LLM app for the AMD Ryzen AI
20
+ NPU, **the same way** (Qwen3.5 9B, Ryzen AI Max+ 395, NPU power mode performance): the prompt of FLM's own `flm bench`
21
+ (128 to 32K tokens), the time to the first token (TTFT), then 32 generated tokens.
22
+
23
+ **Generation is without MTP on both** (temperature 0, one token at a time). FLM's Qwen3.5 has no MTP, so the conditions
24
+ match. onwx with its MTP drafts (temperature 0) is shown apart, as separate dots in the generation chart.
25
+
26
+ <img src="images/answer_speed_vs_flm.svg" alt="A 512-token answer, start to finish: onwx is faster at every length" width="760">
27
+
28
+ <img src="images/prefill_vs_flm.svg" alt="Prompt reading speed" width="760">
29
+
30
+ <img src="images/decode_vs_flm.svg" alt="Generation speed" width="760">
31
+
32
+ - A 512-token answer, start to finish (512 / total time): onwx is ahead at every length from 128 to 32K, even without MTP.
33
+ - Prompt reading: onwx is faster from 2K to 8K; FLM is a little faster at 16K-32K and 256-1K (512 tokens: FLM 1.4 s, onwx 2.7 s).
34
+ - Generation: onwx is 30-40% faster at every length; with MTP about 14-18 tok/s up to 8K of context (past 24K MTP turns itself off).
35
+ - The Ryzen AI 9 HX 370 shows the same picture (a 32K prompt: FLM 379 tok/s, onwx 339 tok/s; generation FLM 6.0, onwx 8.9 tok/s).
36
+
37
  ## Install (paste one line)
38
 
39
  **Windows** - open "Windows PowerShell" from the Start menu (no administrator needed) and paste:
 
85
  | Model | Download | Memory | Prompt reading (1,000 / 4,000 tokens) | Generation |
86
  |---|---|---|---|---|
87
  | [Ternary Bonsai 2 27B](https://huggingface.co/ryugyosoft/Ternary-Bonsai-2-27B-onwx) (ternary / 2-bit, from Qwen3.8-27B) | 7.6 GB | ~8.8 GB + ~34 MB per 1k tokens of context | ~9.3 s / ~28 s | ~6.9 tok/s |
88
+ | [Qwen3.5 9B](https://huggingface.co/ryugyosoft/Qwen3.5-9B-onwx) (int4, reads images) | 7.6 GB | ~5.8 GB + ~15 MB per 1k tokens of context | ~2.9 s / ~8.4 s | ~12 tok/s, ~15 tok/s with MTP at temperature 0 |
89
+ | [Qwen3.5 4B](https://huggingface.co/ryugyosoft/Qwen3.5-4B-onwx) (int4, reads images) | 4.8 GB | ~3.4 GB + ~13 MB per 1k tokens of context | ~2.4 s / ~7.2 s | ~18 tok/s |
90
  | [llm-jp-4.1 8B thinking](https://huggingface.co/ryugyosoft/llm-jp-4.1-8b-onwx) (int4, strong in Japanese) | 5.8 GB | ~4.8 GB + ~65 MB per 1k tokens of context | ~6.3 s / ~13 s | ~11 tok/s |
91
 
92
+ (Measured on a Ryzen AI Max+ 395, Windows, onwx 0.5.0. Prompts read 2-7x faster than with 0.3.0; long ones like 32K another ~20% faster than with 0.4.0.)
93
 
94
  - Prompts are read on the NPU in batches. From 256 tokens on (llm-jp: 32) 1,024 / 2,048 tokens at a time, each layer on all 32 AI Engines of the NPU (bfp16 matrix products; the weights are expanded on the NPU right before their layer, so only a ~0.5 GB work area is added to the memory). Short prompts take the 128 / 32-token paths as before.
95
  - The attention cache (keys and values) is kept as int8: half the memory per 1k tokens of context of 0.3.0.
96
+ - At temperature 0 (the API default) Qwen3.5 9B drafts the next token with the model's MTP layer and generates faster; the output is the same as one token at a time (not used with the chat window's default sampling; `ONWX_MTP=0` turns it off). Past 24K tokens of context the drafts' check costs more than it saves, so it turns itself off (`ONWX_MTP_MAX` changes that).
97
+ - Context: up to 262144 tokens (the model's limit; llm-jp 65536). Qwen3.5 9B / 4B read prompts past 32K on the new NPU path too (9B: ~340 tok/s at 64K tokens). The default is 3840 tokens, changeable in the settings. Longer contexts are slower.
98
  - Thinking mode and tool calls are supported. Images work with Qwen3.5 9B / 4B (the image encoder runs on the CPU).
99
  - Speeds are measured with the NPU power mode set to performance (administrator PowerShell: `C:\Windows\System32\AMD\xrt-smi.exe configure --pmode performance`); in the default mode the NPU clocks lower and it is about 20% slower. The Ryzen AI 300 series (HX 370 and others) has the same 32-AI-Engine NPU and runs the same programs. Windows AI features (Copilot+) using the NPU can slow it down.
100
 
images/answer_speed_vs_flm.svg ADDED
images/decode_vs_flm.svg ADDED
images/prefill_vs_flm.svg ADDED
onwx/__init__.py CHANGED
@@ -2,6 +2,6 @@
2
 
3
  (A working name: the product's name is set here and in the install scripts.)
4
  """
5
- __version__ = "0.4.0"
6
  NAME = "onwx"
7
  TITLE = "onwx (AMD Ryzen AI NPU)"
 
2
 
3
  (A working name: the product's name is set here and in the install scripts.)
4
  """
5
+ __version__ = "0.5.0"
6
  NAME = "onwx"
7
  TITLE = "onwx (AMD Ryzen AI NPU)"
onwx/app.py CHANGED
@@ -443,6 +443,8 @@ PKG_REV = 2 # xdna.json "rev" of the catalog models on the hub: 2 = onwx 0.3.0
443
  PKG_REV_OF = {r: 3 for r in ("ryugyosoft/Ternary-Bonsai-2-27B-onwx", "ryugyosoft/Qwen3.5-9B-onwx",
444
  "ryugyosoft/Qwen3.5-4B-onwx", "ryugyosoft/llm-jp-4.1-8b-onwx")}
445
  # [0.4] rev 3: the int8 KV cache (q8) and the chunked all-NPU prefill (plans/pfx)
 
 
446
 
447
 
448
  def outdated(repo, p):
 
443
  PKG_REV_OF = {r: 3 for r in ("ryugyosoft/Ternary-Bonsai-2-27B-onwx", "ryugyosoft/Qwen3.5-9B-onwx",
444
  "ryugyosoft/Qwen3.5-4B-onwx", "ryugyosoft/llm-jp-4.1-8b-onwx")}
445
  # [0.4] rev 3: the int8 KV cache (q8) and the chunked all-NPU prefill (plans/pfx)
446
+ PKG_REV_OF.update({r: 4 for r in ("ryugyosoft/Qwen3.5-9B-onwx", "ryugyosoft/Qwen3.5-4B-onwx")})
447
+ # [0.5] rev 4: the faster prefill attention (plans/pfx/m*/pfa5r1, pfa5r2), long prompts past 32K on it
448
 
449
 
450
  def outdated(repo, p):
onwx/npu_pfx.py CHANGED
@@ -11,6 +11,7 @@ Package files (plans/<dir>/, xdna.json "pfx": {"dir": "pfx", "ms": [1024, 2048],
11
  (default, the 9B's: gemm.xclbin with in13312 / out / gu / d0..d2.bin, wq.xclbin + wq.bin,
12
  dnp.xclbin + dnl.bin, dnr.xclbin + dnr.bin, glue.xclbin + <op>.bin)
13
  m<M>/pfa3/ the attention (+ its glue): final.xclbin, insts_0 / insts_1024 / insts_d.bin, case.json
 
14
  small.npz per layer: in<l>, post<l> (the RMSNorm weights as the glue's 1 + w; padded to H),
15
  dn<l> (the gated norm), qn<l> / kn<l> (q / k norms), ab<l> (the DeltaNet a/b tiles)
16
  "dims" (default from the package): H (padded hidden), hreal, I (MLP), ND (down K-splits), NIN (attention in_proj
@@ -122,7 +123,8 @@ def pfa3_aux(c, theta, T0, kind="pfa3"):
122
  core, rope 64), pfa3l (Llama: a pass 16, 2 a core, rope 128), pfa3b (Bonsai: a pass 16, 2 a core, rope 64)"""
123
  M, P = c["M"], c["passes"]
124
  tp, per, rot, nq = {"pfa3l": (16, 2, 128, 2), "pfa3b": (16, 2, 64, 4)}.get(kind, (32, 4, 64, 4))
125
- nkb = [((T0 + tp * p + tp + 3) // 4 + 7) // 8 * 8 for p in range(P)]
 
126
  inv = 1.0 / (theta ** (np.arange(0, rot, 2) / rot))
127
  ang = (T0 + np.arange(M + 16, dtype=np.float64))[:, None] * inv[None]
128
  R = np.concatenate([np.cos(ang), np.sin(ang)], 1).astype(np.float32)
@@ -133,7 +135,7 @@ def pfa3_aux(c, theta, T0, kind="pfa3"):
133
  h2 = a[c["H2"]:c["H2"] + P * 32 * BW].reshape(P, 8, 4, BW)
134
  f2 = f[c["H2"]:c["H2"] + P * 32 * BW].reshape(P, 8, 4, BW)
135
  h2[..., 0], h2[..., 5], h2[..., 9] = 2, nq, nq
136
- h2[..., 6] = (np.array(nkb) // 2)[:, None, None]
137
  for p in range(P):
138
  for col in range(8):
139
  for r in range(4):
@@ -272,9 +274,11 @@ class BigPrefill:
272
  self.MS = tuple(sorted(cfg.get("ms", self.MS)))
273
  caps = [] # (the attention templates' extent: a chunk ends by CAP tokens)
274
  for M in self.MS:
275
- with open(os.path.join(self.d, f"m{M}", "pfa3", "case.json")) as f:
276
  caps.append(int(json.load(f).get("cap", 32768)))
277
  self.CAP = min(caps)
 
 
278
  self.cost = cfg.get("cost", {"1024": 2.5, "2048": 4.3})
279
  self.old_tps = float(cfg.get("old_tps", 95.0))
280
  self.D = D = dims_of(b)
@@ -305,7 +309,7 @@ class BigPrefill:
305
  self.part_of.setdefault(dn, {})[k] = i
306
  self.bh = self._buf(Mx * H * 9 // 8 * 4, 3, "activations")
307
  self.bX4 = self._buf(Mx * max(H, D["KO"]) * 9 // 8, 4, "activations")
308
- self.cases = {M: json.load(open(os.path.join(self.d, f"m{M}", "pfa3", "case.json"))) for M in self.MS}
309
  self.nsc = max(max(o + n for o, n in self._regions(M).values()) for M in self.MS)
310
  self.scr = self._buf((self.nsc + KB64 - 1) // KB64 * KB64, 5, "activations")
311
  self.dq = {(dn, i): self._prog(self._cx(f"dqg_{k}", os.path.join(self.d, f"dqg_{k}{sf}", "final.xclbin")),
@@ -377,6 +381,14 @@ class BigPrefill:
377
  "Yq": (0, c["NY"] * 4), "Ao": (al(c["NY"] * 4), c["NO"] * 4), "Yn": (0, self.NO * H // 2 * w),
378
  "Ygu": (0, I * w), "X12": (al(I * w), M * I * 9 // 8), "Yd": (0, ND * H // 2 * w)}
379
 
 
 
 
 
 
 
 
 
380
  def _setup(self, M):
381
  if M in self.per:
382
  return self.per[M]
@@ -388,11 +400,11 @@ class BigPrefill:
388
  q[name] = self._prog(self._cx(f"{xb}{M}", os.path.join(d, xb)), os.path.join(d, ins))
389
  q["yd"] = [q[f"yd{s}"] for s in range(self.ND)]
390
  q["yo"] = [q[f"yo{s}"] for s in range(self.NO)]
391
- pdir = os.path.join(d, "pfa3")
392
- q["pfa3_ctx"] = self._cx(f"pfa3{M}", os.path.join(pdir, "final.xclbin"))
393
- q["pfa3_ins"] = Pfa3Insts(pdir)
394
- q["pfa3"] = self._prog(q["pfa3_ctx"], q["pfa3_ins"].i0)
395
- q["pfa3_T0"] = 0
396
  c = q["pfa3_ins"].case
397
  q["aux"] = self._buf(c["NAUX"] * 4, 5, "params")
398
  q["aux_nrm"] = self._sub(q["aux"], c["NRM"] * 4, 8 * BW * 4) if D["attn"] in ("pfa3", "pfa3b") else None
@@ -414,11 +426,12 @@ class BigPrefill:
414
  return q
415
 
416
  def _set_T0(self, q, T0):
417
- if q["pfa3_T0"] != T0:
418
- ins = q["pfa3_ins"].get(T0).view(np.uint8)
419
- q["pfa3"][3][:ins.nbytes] = ins
420
- q["pfa3"][0].sync(q["pfa3"][1], True)
421
- q["pfa3_T0"] = T0
 
422
  if q["aux_T0"] != T0:
423
  a = pfa3_aux(q["pfa3_ins"].case, self.theta, T0, self.D["attn"])
424
  q["aux"][1][:a.nbytes] = a.view(np.uint8)
@@ -468,7 +481,7 @@ class BigPrefill:
468
  (fp32 [hid]), rows every token's ([n][hid]) when asked"""
469
  b, n, T0, H = self.b, len(toks), self.b.pos, self.H
470
  M = self.chunk_for(n)
471
- assert T0 % 32 == 0 and T0 + M + 32 <= b.tmax
472
  q = self._setup(M)
473
  t0 = time.perf_counter()
474
  self._set_T0(q, T0)
@@ -504,7 +517,8 @@ class BigPrefill:
504
  nrm = pfa3_norms(self.sm[f"qn{l}"] - sh, self.sm[f"kn{l}"] - sh)
505
  q["aux_nrm"][1][:nrm.nbytes] = nrm.view(np.uint8)
506
  self.dev.sync(q["aux_nrm"][0], True)
507
- run(q["pfa3"], "attention", S["Yq"], b.kv[l], q["aux"], S["Ao"])
 
508
  run(q["rotp"], "glue", S["Ao"], P[l], self.bX4)
509
  for s_ in range(self.NO):
510
  run(q["yo"][s_], "gemm", self.bX4, wv(dn, l, f"o{s_}" if self.NO > 1 else "out"), S["Yn"])
 
11
  (default, the 9B's: gemm.xclbin with in13312 / out / gu / d0..d2.bin, wq.xclbin + wq.bin,
12
  dnp.xclbin + dnl.bin, dnr.xclbin + dnr.bin, glue.xclbin + <op>.bin)
13
  m<M>/pfa3/ the attention (+ its glue): final.xclbin, insts_0 / insts_1024 / insts_d.bin, case.json
14
+ m<M>/pfa5r1/, pfa5r2/ [0.5] the same split in 2 (the K / V records | the attention, 16 keys a step): used if present
15
  small.npz per layer: in<l>, post<l> (the RMSNorm weights as the glue's 1 + w; padded to H),
16
  dn<l> (the gated norm), qn<l> / kn<l> (q / k norms), ab<l> (the DeltaNet a/b tiles)
17
  "dims" (default from the package): H (padded hidden), hreal, I (MLP), ND (down K-splits), NIN (attention in_proj
 
123
  core, rope 64), pfa3l (Llama: a pass 16, 2 a core, rope 128), pfa3b (Bonsai: a pass 16, 2 a core, rope 64)"""
124
  M, P = c["M"], c["passes"]
125
  tp, per, rot, nq = {"pfa3l": (16, 2, 128, 2), "pfa3b": (16, 2, 64, 4)}.get(kind, (32, 4, 64, 4))
126
+ kr = c.get("kround", 8) # (the cache blocks a pass reads: to a multiple of kr)
127
+ nkb = [((T0 + tp * p + tp + 3) // 4 + kr - 1) // kr * kr for p in range(P)]
128
  inv = 1.0 / (theta ** (np.arange(0, rot, 2) / rot))
129
  ang = (T0 + np.arange(M + 16, dtype=np.float64))[:, None] * inv[None]
130
  R = np.concatenate([np.cos(ang), np.sin(ang)], 1).astype(np.float32)
 
135
  h2 = a[c["H2"]:c["H2"] + P * 32 * BW].reshape(P, 8, 4, BW)
136
  f2 = f[c["H2"]:c["H2"] + P * 32 * BW].reshape(P, 8, 4, BW)
137
  h2[..., 0], h2[..., 5], h2[..., 9] = 2, nq, nq
138
+ h2[..., 6] = (np.array(nkb) // c.get("spb", 2))[:, None, None] # (steps: cache blocks a step)
139
  for p in range(P):
140
  for col in range(8):
141
  for r in range(4):
 
274
  self.MS = tuple(sorted(cfg.get("ms", self.MS)))
275
  caps = [] # (the attention templates' extent: a chunk ends by CAP tokens)
276
  for M in self.MS:
277
+ with open(os.path.join(self.attn_dirs(M)[-1], "case.json")) as f:
278
  caps.append(int(json.load(f).get("cap", 32768)))
279
  self.CAP = min(caps)
280
+ kr = max(int(json.load(open(os.path.join(self.attn_dirs(M)[-1], "case.json"))).get("kround", 8)) for M in self.MS)
281
+ self.ALIGN = self.RA = 4 * kr # (a chunk starts at a multiple of ALIGN; RA: the cache read past it)
282
  self.cost = cfg.get("cost", {"1024": 2.5, "2048": 4.3})
283
  self.old_tps = float(cfg.get("old_tps", 95.0))
284
  self.D = D = dims_of(b)
 
309
  self.part_of.setdefault(dn, {})[k] = i
310
  self.bh = self._buf(Mx * H * 9 // 8 * 4, 3, "activations")
311
  self.bX4 = self._buf(Mx * max(H, D["KO"]) * 9 // 8, 4, "activations")
312
+ self.cases = {M: json.load(open(os.path.join(self.attn_dirs(M)[-1], "case.json"))) for M in self.MS}
313
  self.nsc = max(max(o + n for o, n in self._regions(M).values()) for M in self.MS)
314
  self.scr = self._buf((self.nsc + KB64 - 1) // KB64 * KB64, 5, "activations")
315
  self.dq = {(dn, i): self._prog(self._cx(f"dqg_{k}", os.path.join(self.d, f"dqg_{k}{sf}", "final.xclbin")),
 
381
  "Yq": (0, c["NY"] * 4), "Ao": (al(c["NY"] * 4), c["NO"] * 4), "Yn": (0, self.NO * H // 2 * w),
382
  "Ygu": (0, I * w), "X12": (al(I * w), M * I * 9 // 8), "Yd": (0, ND * H // 2 * w)}
383
 
384
+ def attn_dirs(self, M):
385
+ """m<M>'s attention program dirs: pfa5r1 + pfa5r2 when present (ONWX_PFA5=0: pfa3), else pfa3"""
386
+ d = os.path.join(self.d, f"m{M}")
387
+ two = [os.path.join(d, "pfa5r1"), os.path.join(d, "pfa5r2")]
388
+ if all(os.path.isdir(x) for x in two) and os.environ.get("ONWX_PFA5", "1") != "0":
389
+ return two
390
+ return [os.path.join(d, "pfa3")]
391
+
392
  def _setup(self, M):
393
  if M in self.per:
394
  return self.per[M]
 
400
  q[name] = self._prog(self._cx(f"{xb}{M}", os.path.join(d, xb)), os.path.join(d, ins))
401
  q["yd"] = [q[f"yd{s}"] for s in range(self.ND)]
402
  q["yo"] = [q[f"yo{s}"] for s in range(self.NO)]
403
+ q["att"] = [] # (the attention programs in order: [pfa3] or [pfa5r1, pfa5r2])
404
+ for pdir in self.attn_dirs(M):
405
+ ins = Pfa3Insts(pdir)
406
+ q["att"].append([self._prog(self._cx(pdir, os.path.join(pdir, "final.xclbin")), ins.i0), ins, 0])
407
+ q["pfa3_ins"] = q["att"][-1][1]
408
  c = q["pfa3_ins"].case
409
  q["aux"] = self._buf(c["NAUX"] * 4, 5, "params")
410
  q["aux_nrm"] = self._sub(q["aux"], c["NRM"] * 4, 8 * BW * 4) if D["attn"] in ("pfa3", "pfa3b") else None
 
426
  return q
427
 
428
  def _set_T0(self, q, T0):
429
+ for at in q["att"]:
430
+ if at[2] != T0:
431
+ ins = at[1].get(T0).view(np.uint8)
432
+ at[0][3][:ins.nbytes] = ins
433
+ at[0][0].sync(at[0][1], True)
434
+ at[2] = T0
435
  if q["aux_T0"] != T0:
436
  a = pfa3_aux(q["pfa3_ins"].case, self.theta, T0, self.D["attn"])
437
  q["aux"][1][:a.nbytes] = a.view(np.uint8)
 
481
  (fp32 [hid]), rows every token's ([n][hid]) when asked"""
482
  b, n, T0, H = self.b, len(toks), self.b.pos, self.H
483
  M = self.chunk_for(n)
484
+ assert T0 % 32 == 0 and T0 + M + 32 <= b.tmax + b.kv_slack
485
  q = self._setup(M)
486
  t0 = time.perf_counter()
487
  self._set_T0(q, T0)
 
517
  nrm = pfa3_norms(self.sm[f"qn{l}"] - sh, self.sm[f"kn{l}"] - sh)
518
  q["aux_nrm"][1][:nrm.nbytes] = nrm.view(np.uint8)
519
  self.dev.sync(q["aux_nrm"][0], True)
520
+ for at in q["att"]:
521
+ run(at[0], "attention", S["Yq"], b.kv[l], q["aux"], S["Ao"])
522
  run(q["rotp"], "glue", S["Ao"], P[l], self.bX4)
523
  for s_ in range(self.NO):
524
  run(q["yo"][s_], "gemm", self.bX4, wv(dn, l, f"o{s_}" if self.NO > 1 else "out"), S["Yn"])
onwx/xdna.py CHANGED
@@ -115,6 +115,10 @@ def import_pyxrt():
115
  f"{', '.join(PYXRT_DIRS).format(XILINX_XRT=os.environ.get('XILINX_XRT', '/opt/xilinx/xrt'))}.")
116
 
117
 
 
 
 
 
118
  class PyxrtDev:
119
  def __init__(self, xclbin, base=None):
120
  pyxrt = import_pyxrt()
@@ -276,6 +280,8 @@ class Bonsai:
276
  mt = man.get("mtp") if os.environ.get("ONWX_MTP", "1") != "0" else None
277
  self.nslot, self.slot, self.stsub = (2 * mt["vt"] if mt else 1), 0, {}
278
  self.kv_margin = man.get("kv_margin", 1)
 
 
279
  for l in range(self.L):
280
  if self.types[l] == "linear_attention":
281
  self.st[l] = self.load(os.path.join(B, f"L{l}.st"), 5, self.nslot) # (bo, map, path)
@@ -284,7 +290,7 @@ class Bonsai:
284
  if self.nslot > 1:
285
  self.stsub[l] = [self.dev.sub(self.st[l][0], n, k * n) for k in range(self.nslot)]
286
  else:
287
- n = ((self.tmax + self.kq - 1) // self.kq + self.kv_margin) * PAIR if self.pair else 4 * self.hstr
288
  self.kv[l] = self.dev.buf(n * 4, 5)[0]
289
  self.actbo, am = self.dev.buf(man["act_words"] * 4, 4)
290
  self.am = am.view(np.int32)
@@ -391,9 +397,9 @@ class Bonsai:
391
  keep = (lambda r: res.append(np.asarray(r, np.float32).reshape(-1, self.hid))) if rows else (lambda r: None)
392
  bp = (self._big() if embeds is None and mpos is None and self.rdelta == 0 and not self._big_off else None)
393
  while bp is not None and len(toks) - i >= bp.MIN:
394
- a = (-self.pos) % 32 # (a chunk starts at a multiple of 32: the rest first, as before)
395
  m = bp.plan(len(toks) - i - a) # (the cheapest split; a short tail: a padded chunk or the old
396
- if m == 0 or self.pos + a + bp.chunk_for(m) + 32 > self.tmax: # programs, by the measured costs)
397
  break
398
  if self.pos + a + bp.chunk_for(m) > bp.CAP: # (past the chunk programs' cache extent: the old programs)
399
  break
@@ -414,6 +420,7 @@ class Bonsai:
414
  mp = lambda j: None if mpos is None else mpos[:, j]
415
  p128 = getattr(self, "pf128", None)
416
  cap128 = max(p128.man.get("tcaps") or [0]) if p128 is not None else 0 # (its attention plans' extents)
 
417
  while p128 is not None and len(toks) - i >= p128.NT and self.pos + p128.NT <= min(self.tmax, cap128):
418
  if self.pair and self.pos % self.kq: # (pair-major: a batch starts at an even position; q8: at a quad)
419
  self.step(toks[i], want_logits=False, emb=e(i), mpos=mp(i))
@@ -547,7 +554,7 @@ class Bonsai:
547
  return lg[:self.cfg["vocab_size"]].copy()
548
 
549
  def kv_bytes(self, l):
550
- return ((self.tmax + self.kq - 1) // self.kq + self.kv_margin) * PAIR * 4
551
 
552
 
553
  def read_h(self):
@@ -1083,7 +1090,7 @@ class XdnaModel:
1083
 
1084
  def mtp_ready(self):
1085
  """[MTP] drafts possible from here: the MTP rows valid for every position, the last one's waiting"""
1086
- return self.mtp is not None and self.mtp_ok and self.mtp_pend is not None and self.delta == 0
1087
 
1088
  def truncate(self, keep):
1089
  raise NotImplementedError("truncate: not on the AMD NPU build (no draft verification)")
 
115
  f"{', '.join(PYXRT_DIRS).format(XILINX_XRT=os.environ.get('XILINX_XRT', '/opt/xilinx/xrt'))}.")
116
 
117
 
118
+ PF128_CAP = int(os.environ.get("ONWX_PF128_CAP", "62208")) # [0.5] the 128-token prompt programs' last working cache extent
119
+ MTP_MAX_POS = int(os.environ.get("ONWX_MTP_MAX", "24576")) # [0.5] no MTP drafts past this context: the verify
120
+ # program's cost grows faster than a decode step's (HX 370: MTP 10.6 / plain 10.0 tok/s at 16K, 7.9 / 8.5 at 32K)
121
+
122
  class PyxrtDev:
123
  def __init__(self, xclbin, base=None):
124
  pyxrt = import_pyxrt()
 
280
  mt = man.get("mtp") if os.environ.get("ONWX_MTP", "1") != "0" else None
281
  self.nslot, self.slot, self.stsub = (2 * mt["vt"] if mt else 1), 0, {}
282
  self.kv_margin = man.get("kv_margin", 1)
283
+ pfx = man.get("pfx") # [0.5] room past tmax for the last prompt chunk's padding and the
284
+ self.kv_slack = (max(pfx.get("ms", [2048])) + 256) if pfx and self.pair else 0 # attention's read-ahead
285
  for l in range(self.L):
286
  if self.types[l] == "linear_attention":
287
  self.st[l] = self.load(os.path.join(B, f"L{l}.st"), 5, self.nslot) # (bo, map, path)
 
290
  if self.nslot > 1:
291
  self.stsub[l] = [self.dev.sub(self.st[l][0], n, k * n) for k in range(self.nslot)]
292
  else:
293
+ n = ((self.tmax + self.kv_slack + self.kq - 1) // self.kq + self.kv_margin) * PAIR if self.pair else 4 * self.hstr
294
  self.kv[l] = self.dev.buf(n * 4, 5)[0]
295
  self.actbo, am = self.dev.buf(man["act_words"] * 4, 4)
296
  self.am = am.view(np.int32)
 
397
  keep = (lambda r: res.append(np.asarray(r, np.float32).reshape(-1, self.hid))) if rows else (lambda r: None)
398
  bp = (self._big() if embeds is None and mpos is None and self.rdelta == 0 and not self._big_off else None)
399
  while bp is not None and len(toks) - i >= bp.MIN:
400
+ a = (-self.pos) % bp.ALIGN # (a chunk starts at a multiple of ALIGN (32 / 256): the rest first)
401
  m = bp.plan(len(toks) - i - a) # (the cheapest split; a short tail: a padded chunk or the old
402
+ if m == 0 or self.pos + a + bp.chunk_for(m) + max(32, bp.RA) > self.tmax + self.kv_slack: # programs, by the measured costs)
403
  break
404
  if self.pos + a + bp.chunk_for(m) > bp.CAP: # (past the chunk programs' cache extent: the old programs)
405
  break
 
420
  mp = lambda j: None if mpos is None else mpos[:, j]
421
  p128 = getattr(self, "pf128", None)
422
  cap128 = max(p128.man.get("tcaps") or [0]) if p128 is not None else 0 # (its attention plans' extents)
423
+ cap128 = min(cap128, PF128_CAP) # [0.5] (its plans past 62208 hang the NPU: the 16 / 32 ones there)
424
  while p128 is not None and len(toks) - i >= p128.NT and self.pos + p128.NT <= min(self.tmax, cap128):
425
  if self.pair and self.pos % self.kq: # (pair-major: a batch starts at an even position; q8: at a quad)
426
  self.step(toks[i], want_logits=False, emb=e(i), mpos=mp(i))
 
554
  return lg[:self.cfg["vocab_size"]].copy()
555
 
556
  def kv_bytes(self, l):
557
+ return ((self.tmax + self.kv_slack + self.kq - 1) // self.kq + self.kv_margin) * PAIR * 4
558
 
559
 
560
  def read_h(self):
 
1090
 
1091
  def mtp_ready(self):
1092
  """[MTP] drafts possible from here: the MTP rows valid for every position, the last one's waiting"""
1093
+ return self.mtp is not None and self.mtp_ok and self.mtp_pend is not None and self.delta == 0 and self.rt.pos < MTP_MAX_POS
1094
 
1095
  def truncate(self, keep):
1096
  raise NotImplementedError("truncate: not on the AMD NPU build (no draft verification)")
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "onwx"
7
- version = "0.4.0"
8
  description = "LLMs entirely on the AMD Ryzen AI NPU (XDNA2)"
9
  readme = "README.md"
10
  license = {text = "Apache-2.0"}
 
4
 
5
  [project]
6
  name = "onwx"
7
+ version = "0.5.0"
8
  description = "LLMs entirely on the AMD Ryzen AI NPU (XDNA2)"
9
  readme = "README.md"
10
  license = {text = "Apache-2.0"}