ryugyosoft commited on
Commit
267a962
·
verified ·
1 Parent(s): 4ce9555

onwx 1.1.0: the KV caches grow with the conversation (27B at 262144: ~16.7 -> ~8.3 GB at load)

Browse files
CHANGELOG.md CHANGED
@@ -5,6 +5,11 @@
5
  日付は日本時間です。各版は Hugging Face の `ryugyosoft/onwx` にタグ(`v0.2.0` 以降)付きで残っています。
6
  onwx ウィンドウは、新しい版があるとこのファイルから変更点を表示します(`## v…` の見出しで区切っています)。
7
 
 
 
 
 
 
8
  ## v1.0.1 (2026-10-23)
9
  - **セキュリティ修正(モデルの更新は不要)**:インドの認証局 eMudhra の中間証明書の問題で、emSign のルート証明書が信頼されなくなりました。Hugging Face からのダウンロードや更新に使う証明書リスト(certifi)を 2026.10.19 以降に、パッケージを入れる pip を 26.2.2 以降に上げます(pip は自分用の証明書リストを持っているため)。更新すると、パッケージの入れ直しが 1 回自動で走ります。
10
  - Python 本体(3.10 以降)も、python.org の最新の版(3.14.9 / 3.13.17 など)に更新しておくのがおすすめです。
 
5
  日付は日本時間です。各版は Hugging Face の `ryugyosoft/onwx` にタグ(`v0.2.0` 以降)付きで残っています。
6
  onwx ウィンドウは、新しい版があるとこのファイルから変更点を表示します(`## v…` の見出しで区切っています)。
7
 
8
+ ## v1.1.0 (2026-10-29)
9
+ - **長い文脈の設定でもメモリを最初に取りすぎないように**:アテンションのキャッシュ(キーと値)を、設定した文脈の長さぶん読み込み時にまとめて確保するのをやめ、会話が長くなるのに合わせて広げるようにしました(最初は 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 で確認)。モデルの更新は不要です。
10
+ - それに合わせて、「モデル」タブのメモリの目安を、読み込み直後の量で表示するようにしました。会話が長くなると、文脈 1k トークンあたり、モデルの表にある量ずつ増えます。
11
+ - 前の動き(最初に全部確保)に戻すには `ONWX_KV_GROW=0` を設定します。
12
+
13
  ## v1.0.1 (2026-10-23)
14
  - **セキュリティ修正(モデルの更新は不要)**:インドの認証局 eMudhra の中間証明書の問題で、emSign のルート証明書が信頼されなくなりました。Hugging Face からのダウンロードや更新に使う証明書リスト(certifi)を 2026.10.19 以降に、パッケージを入れる pip を 26.2.2 以降に上げます(pip は自分用の証明書リストを持っているため)。更新すると、パッケージの入れ直しが 1 回自動で走ります。
15
  - Python 本体(3.10 以降)も、python.org の最新の版(3.14.9 / 3.13.17 など)に更新しておくのがおすすめです。
CHANGELOG_en.md CHANGED
@@ -5,6 +5,11 @@
5
  Dates are Japan time. Every version is kept on Hugging Face `ryugyosoft/onwx` with a tag (from `v0.2.0` on).
6
  The onwx window shows what changed from this file when there is a newer version (sections start at `## v…`).
7
 
 
 
 
 
 
8
  ## v1.0.1 (2026-10-23)
9
  - **Security fix (no model update needed)**: after the eMudhra intermediate CA compromise the emSign root certificates are no longer trusted. The certificate list used for Hugging Face downloads and updates (certifi) goes to 2026.10.19 or later, and pip, which installs the packages, to 26.2.2 or later (pip carries a certificate list of its own). The update reinstalls the packages once, by itself.
10
  - Updating Python itself (3.10+) to the latest release from python.org (3.14.9 / 3.13.17 ...) is recommended too.
 
5
  Dates are Japan time. Every version is kept on Hugging Face `ryugyosoft/onwx` with a tag (from `v0.2.0` on).
6
  The onwx window shows what changed from this file when there is a newer version (sections start at `## v…`).
7
 
8
+ ## v1.1.0 (2026-10-29)
9
+ - **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.
10
+ - 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.
11
+ - `ONWX_KV_GROW=0` brings back the old behaviour (all of it at load).
12
+
13
  ## v1.0.1 (2026-10-23)
14
  - **Security fix (no model update needed)**: after the eMudhra intermediate CA compromise the emSign root certificates are no longer trusted. The certificate list used for Hugging Face downloads and updates (certifi) goes to 2026.10.19 or later, and pip, which installs the packages, to 26.2.2 or later (pip carries a certificate list of its own). The update reinstalls the packages once, by itself.
15
  - Updating Python itself (3.10+) to the latest release from python.org (3.14.9 / 3.13.17 ...) is recommended too.
README.md CHANGED
@@ -130,7 +130,7 @@ onwx chat ryugyosoft/Ternary-Bonsai-2-27B-onwx # 端末でチャット
130
  - プロンプトは NPU でまとめて読み込みます。256 トークン以上(llm-jp は 32 トークン以上)は 1,024 / 2,048 トークンずつ、NPU の 32 個の AI エンジン全部で 1 層ずつ計算します(行列計算は bfp16 の行列ユニット。重みはその層の直前に NPU 上で展開するので、使用メモリの増加は作業領域の約 0.5 GB だけです)。短いプロンプトは従来どおり 128 / 32 トークンずつの経路で読みます。
131
  - 設定の「CPU も使ってプロンプトの読み込みを速くする(消費電力が増えます)」をオンにすると、NPU の計算の合間の小さな処理を CPU(省電力側のコア)で行い、1K トークン以上のプロンプトの読み込みが 1〜2 割速くなります(Qwen3.5 9B、4K トークンで 7.7 → 6.6 秒)。読み込み中の消費電力は数 W 増えます。長いプロンプトほど効きます。既定はオフです。
132
  - **LFM2.5 24B-A2B は onwx が重みを配布しません**:モデル一覧から選ぶと、変換用のキット(約 9 MB)と Liquid AI の元のモデル(約 48 GB)を Hugging Face から取ってきて、この PC で int4 に変換します(ダウンロードと変換で約 20〜30 分。途中で約 65 GB のディスクを使い、終わると元のファイルは消え、約 17 GB が残ります。ボタンは「ダウンロードして変換」で、始める前にこれらを確認します)。利用には LFM Open License v1.0 が適用されます。プロンプトは行列の計算を NPU、注意機構などを CPU でまとめて読みます。
133
- - アテンションのキャッシュ(キーと値)は int8 で持つので、文脈 1k トークンあたりのメモリは 0.3.0 の半分です。
134
  - Qwen3.5 9B と Qwen3.6 35B-A3B は温度 0(API の既定)のとき、モデルの MTP 層で次のトークンを先読みして速く生成します。出力は 1 トークンずつ生成したときと同じです(Qwen3.6 はエキスパートの足し算の順序が違うため、ほぼ同点の候補のところで分かれることがあります。チャット画面の既定のサンプリングでは使いません。`ONWX_MTP=0` で止められます)。文脈が 24K トークン(Qwen3.6 は 8K)を超えると、先読みの検証のほうが重くなるので自動で使わなくなります(`ONWX_MTP_MAX` で変更)。Qwen3.6 は連続する 2 トークンのエキスパートがほとんど重ならないため検証が重く、効果は平均で約 1 割(コードの生成で約 15%)です。先読みが当たりにくい応答では、途中から自動で 1 トークンずつの生成に戻ります。
135
  - 文脈は最大 262144 トークン(モデルの上限。llm-jp は 65536)です。Qwen3.5 9B / 4B は 32K を超える長いプロンプトも NPU の新しい経路で読みます(9B、64K トークンで約 340 tok/s)。既定は 3840 トークンで、設定で変えられます。文脈が長いほど遅くなります。
136
  - 思考モード(考えてから答える)とツール呼び出しに対応しています。画像は Qwen3.6 35B-A3B・Qwen3.5 9B / 4B・Ternary Bonsai 2 9B / 4B で読めます(画像のエンコーダーは CPU で動きます)。
 
130
  - プロンプトは NPU でまとめて読み込みます。256 トークン以上(llm-jp は 32 トークン以上)は 1,024 / 2,048 トークンずつ、NPU の 32 個の AI エンジン全部で 1 層ずつ計算します(行列計算は bfp16 の行列ユニット。重みはその層の直前に NPU 上で展開するので、使用メモリの増加は作業領域の約 0.5 GB だけです)。短いプロンプトは従来どおり 128 / 32 トークンずつの経路で読みます。
131
  - 設定の「CPU も使ってプロンプトの読み込みを速くする(消費電力が増えます)」をオンにすると、NPU の計算の合間の小さな処理を CPU(省電力側のコア)で行い、1K トークン以上のプロンプトの読み込みが 1〜2 割速くなります(Qwen3.5 9B、4K トークンで 7.7 → 6.6 秒)。読み込み中の消費電力は数 W 増えます。長いプロンプトほど効きます。既定はオフです。
132
  - **LFM2.5 24B-A2B は onwx が重みを配布しません**:モデル一覧から選ぶと、変換用のキット(約 9 MB)と Liquid AI の元のモデル(約 48 GB)を Hugging Face から取ってきて、この PC で int4 に変換します(ダウンロードと変換で約 20〜30 分。途中で約 65 GB のディスクを使い、終わると元のファイルは消え、約 17 GB が残ります。ボタンは「ダウンロードして変換」で、始める前にこれらを確認します)。利用には LFM Open License v1.0 が適用されます。プロンプトは行列の計算を NPU、注意機構などを CPU でまとめて読みます。
133
+ - アテンションのキャッシュ(キーと値)は int8 で持つので、文脈 1k トークンあたりのメモリは 0.3.0 の半分です。1.1.0 からは、設定した文脈の長さぶんを最初に確保せず、会話が長くなるのに合わせて広げます(最初は 4,096 トークン分。表のメモリの「+文脈 1k トークンあたり」は、実際に使った長さの分です。`ONWX_KV_GROW=0` で前の動き)。
134
  - Qwen3.5 9B と Qwen3.6 35B-A3B は温度 0(API の既定)のとき、モデルの MTP 層で次のトークンを先読みして速く生成します。出力は 1 トークンずつ生成したときと同じです(Qwen3.6 はエキスパートの足し算の順序が違うため、ほぼ同点の候補のところで分かれることがあります。チャット画面の既定のサンプリングでは使いません。`ONWX_MTP=0` で止められます)。文脈が 24K トークン(Qwen3.6 は 8K)を超えると、先読みの検証のほうが重くなるので自動で使わなくなります(`ONWX_MTP_MAX` で変更)。Qwen3.6 は連続する 2 トークンのエキスパートがほとんど重ならないため検証が重く、効果は平均で約 1 割(コードの生成で約 15%)です。先読みが当たりにくい応答では、途中から自動で 1 トークンずつの生成に戻ります。
135
  - 文脈は最大 262144 トークン(モデルの上限。llm-jp は 65536)です。Qwen3.5 9B / 4B は 32K を超える長いプロンプトも NPU の新しい経路で読みます(9B、64K トークンで約 340 tok/s)。既定は 3840 トークンで、設定で変えられます。文脈が長いほど遅くなります。
136
  - 思考モード(考えてから答える)とツール呼び出しに対応しています。画像は Qwen3.6 35B-A3B・Qwen3.5 9B / 4B・Ternary Bonsai 2 9B / 4B で読めます(画像のエンコーダーは CPU で動きます)。
README_en.md CHANGED
@@ -113,7 +113,7 @@ onwx chat ryugyosoft/Ternary-Bonsai-2-27B-onwx # chat in the terminal
113
  - 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.
114
  - The setting "Use the CPU too, to read prompts faster (uses more power)" moves the small steps between the NPU's computations to the CPU (its efficiency cores): prompts of 1K tokens and more read 10-20% faster (Qwen3.5 9B, 4K tokens: 7.7 -> 6.6 s), for a few watts more while reading. The longer the prompt, the more it helps. Off by default.
115
  - **onwx does not distribute LFM2.5 24B-A2B's weights**: picked from the model list, onwx fetches the conversion kit (~9 MB) and Liquid AI's original model (~48 GB) from Hugging Face and converts it to int4 on your PC (download and conversion ~20-30 minutes; ~65 GB of disk on the way, the original files deleted at the end, ~17 GB stays; the button reads "Download and convert" and asks first). The LFM Open License v1.0 applies. Its prompts are read in chunks: the matrix products on the NPU, the attention and the rest on the CPU.
116
- - The attention cache (keys and values) is kept as int8: half the memory per 1k tokens of context of 0.3.0.
117
  - At temperature 0 (the API default) Qwen3.5 9B and Qwen3.6 35B-A3B draft the next token with the model's MTP layer and generate faster; the output is the same as one token at a time (Qwen3.6 adds the experts up in another order, so it can part ways where two candidates are all but tied; not used with the chat window's default sampling; `ONWX_MTP=0` turns it off). Past 24K tokens of context (Qwen3.6: 8K) the drafts' check costs more than it saves, so it turns itself off (`ONWX_MTP_MAX` changes that). For Qwen3.6 the check is heavy - two tokens in a row hardly share experts - so it gains about 10% on average (about 15% for code); when the drafts are rarely right, the rest of the answer goes back to one token at a time by itself.
118
  - 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.
119
  - Thinking mode and tool calls are supported. Images work with Qwen3.6 35B-A3B, Qwen3.5 9B / 4B and Ternary Bonsai 2 9B / 4B (the image encoder runs on the CPU).
 
113
  - 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.
114
  - The setting "Use the CPU too, to read prompts faster (uses more power)" moves the small steps between the NPU's computations to the CPU (its efficiency cores): prompts of 1K tokens and more read 10-20% faster (Qwen3.5 9B, 4K tokens: 7.7 -> 6.6 s), for a few watts more while reading. The longer the prompt, the more it helps. Off by default.
115
  - **onwx does not distribute LFM2.5 24B-A2B's weights**: picked from the model list, onwx fetches the conversion kit (~9 MB) and Liquid AI's original model (~48 GB) from Hugging Face and converts it to int4 on your PC (download and conversion ~20-30 minutes; ~65 GB of disk on the way, the original files deleted at the end, ~17 GB stays; the button reads "Download and convert" and asks first). The LFM Open License v1.0 applies. Its prompts are read in chunks: the matrix products on the NPU, the attention and the rest on the CPU.
116
+ - The attention cache (keys and values) is kept as int8: half the memory per 1k tokens of context of 0.3.0. Since 1.1.0 it is not allocated for the whole context setting up front but grows with the conversation (4,096 tokens at first; the table's "+ per 1k tokens of context" counts the length actually used; `ONWX_KV_GROW=0`: the old behaviour).
117
  - At temperature 0 (the API default) Qwen3.5 9B and Qwen3.6 35B-A3B draft the next token with the model's MTP layer and generate faster; the output is the same as one token at a time (Qwen3.6 adds the experts up in another order, so it can part ways where two candidates are all but tied; not used with the chat window's default sampling; `ONWX_MTP=0` turns it off). Past 24K tokens of context (Qwen3.6: 8K) the drafts' check costs more than it saves, so it turns itself off (`ONWX_MTP_MAX` changes that). For Qwen3.6 the check is heavy - two tokens in a row hardly share experts - so it gains about 10% on average (about 15% for code); when the drafts are rarely right, the rest of the answer goes back to one token at a time by itself.
118
  - 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.
119
  - Thinking mode and tool calls are supported. Images work with Qwen3.6 35B-A3B, Qwen3.5 9B / 4B and Ternary Bonsai 2 9B / 4B (the image encoder runs on the CPU).
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__ = "1.0.1"
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__ = "1.1.0"
6
  NAME = "onwx"
7
  TITLE = "onwx (AMD Ryzen AI NPU)"
onwx/app.py CHANGED
@@ -262,6 +262,8 @@ def usable_ram(ram):
262
  return None if ram is None else ram * 0.85
263
 
264
 
 
 
265
  MAX_CONTEXT = {} # model key -> its longest context (engine.json), noted by note_max_contexts
266
 
267
 
@@ -294,7 +296,9 @@ def memory_full(repo, cfg, ram):
294
  if repo not in MEMORY:
295
  return None
296
  base, s64, kv = MEMORY[repo]
297
- return base + (s64 if big_blocks_on(cfg, ram) else 0.0) + kv * max(context_of(repo, cfg) - 1024, 0) / 1024 / 1024
 
 
298
 
299
 
300
  def expert_budget(repo, cfg, ram):
 
262
  return None if ram is None else ram * 0.85
263
 
264
 
265
+ KV_FIRST = (int(os.environ.get("ONWX_KV_FIRST", "4096")) if os.environ.get("ONWX_KV_GROW", "1") != "0"
266
+ else 1 << 30) # [1.1] (as xdna.KV_FIRST: the positions the KV caches start with)
267
  MAX_CONTEXT = {} # model key -> its longest context (engine.json), noted by note_max_contexts
268
 
269
 
 
296
  if repo not in MEMORY:
297
  return None
298
  base, s64, kv = MEMORY[repo]
299
+ # [1.1] the KV caches grow with the conversation (xdna.KV_FIRST positions at load): the memory at the start
300
+ ctx = min(context_of(repo, cfg), KV_FIRST)
301
+ return base + (s64 if big_blocks_on(cfg, ram) else 0.0) + kv * max(ctx - 1024, 0) / 1024 / 1024
302
 
303
 
304
  def expert_budget(repo, cfg, ram):
onwx/npu_lfx.py CHANGED
@@ -453,6 +453,7 @@ class LfxPrefill:
453
  def run(self, toks, rows=False):
454
  b = self.b
455
  T0, M = b.pos, len(toks)
 
456
  t0 = time.perf_counter()
457
  h = np.stack([b.embed(int(t)) for t in toks]).astype(np.float32)
458
  for l in range(self.L):
 
453
  def run(self, toks, rows=False):
454
  b = self.b
455
  T0, M = b.pos, len(toks)
456
+ b.kv_ensure(T0 + M) # [1.1] (the caches grow first)
457
  t0 = time.perf_counter()
458
  h = np.stack([b.embed(int(t)) for t in toks]).astype(np.float32)
459
  for l in range(self.L):
onwx/npu_pfx.py CHANGED
@@ -600,6 +600,7 @@ class BigPrefill:
600
  b, n, T0, H = self.b, len(toks), self.b.pos, self.H
601
  M = self.chunk_for(n)
602
  assert T0 % 32 == 0 and T0 + M + 32 <= b.tmax + b.kv_slack
 
603
  q = self._setup(M)
604
  t0 = time.perf_counter()
605
  self._set_T0(q, T0)
 
600
  b, n, T0, H = self.b, len(toks), self.b.pos, self.H
601
  M = self.chunk_for(n)
602
  assert T0 % 32 == 0 and T0 + M + 32 <= b.tmax + b.kv_slack
603
+ b.kv_ensure(T0 + M) # [1.1] (the caches grow first; the read-ahead: kv_slack)
604
  q = self._setup(M)
605
  t0 = time.perf_counter()
606
  self._set_T0(q, T0)
onwx/npu_pfx_moe.py CHANGED
@@ -147,6 +147,7 @@ class MoePrefill(BigPrefill):
147
  b, n, T0, H = self.b, len(toks), self.b.pos, self.H
148
  M = self.chunk_for(n)
149
  assert T0 % 32 == 0 and T0 + M + 32 <= b.tmax + b.kv_slack
 
150
  q = self._setup(M)
151
  t0 = time.perf_counter()
152
  self._set_T0(q, T0)
 
147
  b, n, T0, H = self.b, len(toks), self.b.pos, self.H
148
  M = self.chunk_for(n)
149
  assert T0 % 32 == 0 and T0 + M + 32 <= b.tmax + b.kv_slack
150
+ b.kv_ensure(T0 + M) # [1.1] (the caches grow first; the read-ahead: kv_slack)
151
  q = self._setup(M)
152
  t0 = time.perf_counter()
153
  self._set_T0(q, T0)
onwx/xdna.py CHANGED
@@ -12,7 +12,7 @@ Devices: Windows - xdna_shim.dll (bin/, a C face over XRT's C++ API, built again
12
  NPU driver); Linux - pyxrt (XRT's Python bindings).
13
  """
14
  import ctypes as C
15
- import json, os, threading, time
16
  import numpy as np
17
 
18
  BLK_W = 544
@@ -151,6 +151,10 @@ def import_pyxrt():
151
  PF128_CAP = int(os.environ.get("ONWX_PF128_CAP", "62208")) # [0.5] the 128-token prompt programs' last working cache extent
152
  MTP_MAX_POS = int(os.environ.get("ONWX_MTP_MAX", "24576")) # [0.5] no MTP drafts past this context: the verify
153
  # 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)
 
 
 
 
154
 
155
  # [0.5] busy-wait while the chunked prefill runs (its ~11 xclbin switches a layer: a sleeping host thread lets the CPU
156
  # idle deeply and many switches take ~4 ms instead of ~2.4; rmax 4B 1K chunk 2.45 -> 2.07 s, the energy the same).
@@ -405,6 +409,12 @@ class Bonsai:
405
  self.kv_margin = man.get("kv_margin", 1)
406
  pfx = man.get("pfx") # [0.5] room past tmax for the last prompt chunk's padding and the
407
  self.kv_slack = (max(pfx.get("ms", [2048])) + 256) if pfx and self.pair else 0 # attention's read-ahead
 
 
 
 
 
 
408
  for l in range(self.L):
409
  if self.types[l] in STATEFUL:
410
  self.st[l] = self.load(os.path.join(B, f"L{l}.st"), 5, self.nslot) # (bo, map, path)
@@ -413,8 +423,8 @@ class Bonsai:
413
  if self.nslot > 1:
414
  self.stsub[l] = [self.dev.sub(self.st[l][0], n, k * n) for k in range(self.nslot)]
415
  else:
416
- n = ((self.tmax + self.kv_slack + self.kq - 1) // self.kq + self.kv_margin) * PAIR if self.pair else 4 * self.hstr
417
- self.kv[l], self.kvm[l] = self.dev.buf(n * 4, 5) # ([1.0] the map: LFM2.5's prefill writes it)
418
  self.actbo, am = self.dev.buf(man["act_words"] * 4, 4)
419
  self.am = am.view(np.int32)
420
  init = np.fromfile(os.path.join(B, "act.init"), dtype=np.int32)
@@ -680,6 +690,7 @@ class Bonsai:
680
  def kv_at(self, l, T):
681
  """the cache sub-buffer a plan writes the record(s) of position T on into"""
682
  if self.pair:
 
683
  off = T // self.kq * PAIR * 4
684
  return self.dev.sub(self.kv[l], self.kv_bytes(l) - off, off)
685
  return self.dev.sub(self.kv[l], 4 * self.hstr * 4 - T * REC * 4, T * REC * 4)
@@ -694,6 +705,7 @@ class Bonsai:
694
  T = self.pos
695
  if T >= self.tmax:
696
  raise RuntimeError(f"context full ({self.tmax} tokens)")
 
697
  a, am = self.act, self.am
698
  w = self.hid // 16
699
  row = self.embed(tok) if emb is None else self.fit(emb)
@@ -742,7 +754,43 @@ class Bonsai:
742
  return lg[:self.cfg["vocab_size"]].copy()
743
 
744
  def kv_bytes(self, l):
745
- return ((self.tmax + self.kv_slack + self.kq - 1) // self.kq + self.kv_margin) * PAIR * 4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
746
 
747
 
748
  def read_h(self):
@@ -805,7 +853,8 @@ class Mtp:
805
  self.fbo = b.load(os.path.join(B, bl["fc"]), 3)[0]
806
  self.dbo = b.load(os.path.join(B, bl["head"]), 3)[0]
807
  self.kvb = b.kv_bytes(None)
808
- self.kv = b.dev.buf(self.kvb, 5)[0] # (the MTP layer's KV cache)
 
809
  init = np.fromfile(os.path.join(B, "act.init"), dtype=np.int32)
810
  self.bufs = [(b.actbo, b.am)] # (VT activation buffers: VT rows a runlist)
811
  for _ in range(self.VT - 1):
@@ -848,6 +897,7 @@ class Mtp:
848
  return bf16_bits(x).view(np.int32)
849
 
850
  def kv_at(self, T):
 
851
  off = T // self.b.kq * PAIR * 4
852
  return self.b.dev.sub(self.kv, self.kvb - off, off)
853
 
@@ -857,6 +907,7 @@ class Mtp:
857
  draft (the token after the last row's) from the draft head"""
858
  b, a = self.b, self.b.act
859
  t0 = time.perf_counter()
 
860
  items, subs = [], []
861
  bufs = self.bufs
862
  for r, (hn, tok, pos) in enumerate(rows):
@@ -915,6 +966,7 @@ class Mtp:
915
  b, av, vm, VT = self.b, self.av, self.vm, self.VT
916
  t0 = time.perf_counter()
917
  P = b.pos
 
918
  tcap = b.bucket(P + VT - 1)
919
  w, HS = b.hid // 16, 16 * BLK_W
920
  for t, tok in enumerate(toks):
@@ -1047,7 +1099,7 @@ def adaptive(ms, ids, n, stop=frozenset(), c=None):
1047
  m0 = ms[vts[-1]]
1048
  b = m0.b
1049
  for m in ms.values(): # (one MTP cache and set of row buffers for all)
1050
- m.bufs, m.kv, m.kvb = m0.bufs, m0.kv, m0.kvb
1051
  p = [0.8] * (vts[-1] - 1) # (EMA acceptance of draft j | drafts < j kept)
1052
  cost = dict(c or {2: 127.0, 3: 164.0})
1053
  lg, hn = m0.prompt(ids)
@@ -1126,6 +1178,7 @@ class Prefill:
1126
  b, a, am, n = self.b, self.act, self.am, len(toks)
1127
  T = b.pos
1128
  assert 1 <= n <= self.NT and T + self.NT <= b.tmax
 
1129
  hs, hid = self.man.get("hstr", 5440), self.man.get("hid", 5120) # (an H row's stride, its used words)
1130
  hv = am[a["H"]:a["H"] + (self.NT + 1) * hs].view(np.float32).reshape(self.NT + 1, hs)
1131
  hv[:, :hid] = 0.0
 
12
  NPU driver); Linux - pyxrt (XRT's Python bindings).
13
  """
14
  import ctypes as C
15
+ import json, os, sys, threading, time
16
  import numpy as np
17
 
18
  BLK_W = 544
 
151
  PF128_CAP = int(os.environ.get("ONWX_PF128_CAP", "62208")) # [0.5] the 128-token prompt programs' last working cache extent
152
  MTP_MAX_POS = int(os.environ.get("ONWX_MTP_MAX", "24576")) # [0.5] no MTP drafts past this context: the verify
153
  # 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)
154
+ # [1.1] the KV caches grow with the conversation: positions allocated at load (then at least doubled, to a plan extent,
155
+ # when a step or a prompt chunk needs more); ONWX_KV_GROW=0: the whole context at load as before
156
+ KV_FIRST = int(os.environ.get("ONWX_KV_FIRST", "4096"))
157
+ KV_GROW = os.environ.get("ONWX_KV_GROW", "1") != "0"
158
 
159
  # [0.5] busy-wait while the chunked prefill runs (its ~11 xclbin switches a layer: a sleeping host thread lets the CPU
160
  # idle deeply and many switches take ~4 ms instead of ~2.4; rmax 4B 1K chunk 2.45 -> 2.07 s, the energy the same).
 
409
  self.kv_margin = man.get("kv_margin", 1)
410
  pfx = man.get("pfx") # [0.5] room past tmax for the last prompt chunk's padding and the
411
  self.kv_slack = (max(pfx.get("ms", [2048])) + 256) if pfx and self.pair else 0 # attention's read-ahead
412
+ # [1.1] kv_cap: the positions the caches hold now - a plan extent (tcaps) or tmax, so that every attention plan
413
+ # used below it reads inside the buffers; kv_owners: the MTP layers' caches (objects with kv, kvm, kvb)
414
+ self.kv_cap = self.tmax
415
+ if self.pair and KV_GROW:
416
+ self.kv_cap = min(self.tmax, min((c for c in man["tcaps"] if c >= KV_FIRST), default=self.tmax))
417
+ self.kv_owners, self.kv_grows = [], 0
418
  for l in range(self.L):
419
  if self.types[l] in STATEFUL:
420
  self.st[l] = self.load(os.path.join(B, f"L{l}.st"), 5, self.nslot) # (bo, map, path)
 
423
  if self.nslot > 1:
424
  self.stsub[l] = [self.dev.sub(self.st[l][0], n, k * n) for k in range(self.nslot)]
425
  else:
426
+ n = self.kv_bytes(l) if self.pair else 4 * self.hstr * 4
427
+ self.kv[l], self.kvm[l] = self.dev.buf(n, 5) # ([1.0] the map: LFM2.5's prefill writes it)
428
  self.actbo, am = self.dev.buf(man["act_words"] * 4, 4)
429
  self.am = am.view(np.int32)
430
  init = np.fromfile(os.path.join(B, "act.init"), dtype=np.int32)
 
690
  def kv_at(self, l, T):
691
  """the cache sub-buffer a plan writes the record(s) of position T on into"""
692
  if self.pair:
693
+ self.kv_ensure(T + 1)
694
  off = T // self.kq * PAIR * 4
695
  return self.dev.sub(self.kv[l], self.kv_bytes(l) - off, off)
696
  return self.dev.sub(self.kv[l], 4 * self.hstr * 4 - T * REC * 4, T * REC * 4)
 
705
  T = self.pos
706
  if T >= self.tmax:
707
  raise RuntimeError(f"context full ({self.tmax} tokens)")
708
+ self.kv_ensure(T + 1) # [1.1] (the caches grow first)
709
  a, am = self.act, self.am
710
  w = self.hid // 16
711
  row = self.embed(tok) if emb is None else self.fit(emb)
 
754
  return lg[:self.cfg["vocab_size"]].copy()
755
 
756
  def kv_bytes(self, l):
757
+ return ((self.kv_cap + self.kv_slack + self.kq - 1) // self.kq + self.kv_margin) * PAIR * 4
758
+
759
+ def kv_ensure(self, end):
760
+ """[1.1] grow the caches (the layers' and the MTP layers') so they hold positions < end: to the plan extent at
761
+ or above max(end, 2 x now), at most tmax; the records written so far are copied over"""
762
+ if end <= self.kv_cap or self.kv_cap >= self.tmax:
763
+ return
764
+ want = max(end, 2 * self.kv_cap)
765
+ cap = min(self.tmax, min((c for c in self.man["tcaps"] if c >= want), default=self.tmax))
766
+ old, was, t = self.kv_bytes(None), self.kv_cap, time.perf_counter()
767
+ self.kv_cap = cap
768
+ new = self.kv_bytes(None)
769
+ try:
770
+ for l in list(self.kv):
771
+ self.kv[l], self.kvm[l] = self._kv_copy(self.kv[l], self.kvm[l], old, new)
772
+ done = {}
773
+ for o in self.kv_owners: # (Mtp objects may share one cache: copied once)
774
+ k = id(o.kv)
775
+ if k not in done:
776
+ done[k] = (o, self._kv_copy(o.kv, o.kvm, old, new))
777
+ o.kv, o.kvm = done[k][1]
778
+ o.kvb = new
779
+ except RuntimeError as e:
780
+ self.kv_cap = was # (the caches copied already are just bigger)
781
+ raise RuntimeError(f"not enough memory for a longer conversation ({cap} tokens): {e}") from e
782
+ self.kv_grows += 1
783
+ n = len(self.kv) + len({id(o.kv) for o in self.kv_owners})
784
+ print(f"[onwx] KV cache {was} -> {cap} positions ({new * n / 2**20:.0f} MB, {time.perf_counter() - t:.2f} s)",
785
+ file=sys.stderr, flush=True)
786
+
787
+ def _kv_copy(self, bo, m, old, new):
788
+ nb, nm = self.dev.buf(new, 5)
789
+ self.dev.sync(bo, False)
790
+ nm[:old] = m[:old]
791
+ self.dev.sync(nb, True)
792
+ self.dev.free(bo)
793
+ return nb, nm
794
 
795
 
796
  def read_h(self):
 
853
  self.fbo = b.load(os.path.join(B, bl["fc"]), 3)[0]
854
  self.dbo = b.load(os.path.join(B, bl["head"]), 3)[0]
855
  self.kvb = b.kv_bytes(None)
856
+ self.kv, self.kvm = b.dev.buf(self.kvb, 5) # (the MTP layer's KV cache: grows with the layers')
857
+ b.kv_owners.append(self)
858
  init = np.fromfile(os.path.join(B, "act.init"), dtype=np.int32)
859
  self.bufs = [(b.actbo, b.am)] # (VT activation buffers: VT rows a runlist)
860
  for _ in range(self.VT - 1):
 
897
  return bf16_bits(x).view(np.int32)
898
 
899
  def kv_at(self, T):
900
+ self.b.kv_ensure(T + 1)
901
  off = T // self.b.kq * PAIR * 4
902
  return self.b.dev.sub(self.kv, self.kvb - off, off)
903
 
 
907
  draft (the token after the last row's) from the draft head"""
908
  b, a = self.b, self.b.act
909
  t0 = time.perf_counter()
910
+ b.kv_ensure(max(r[2] for r in rows) + 1) # [1.1] (the caches grow first: the items keep self.kv)
911
  items, subs = [], []
912
  bufs = self.bufs
913
  for r, (hn, tok, pos) in enumerate(rows):
 
966
  b, av, vm, VT = self.b, self.av, self.vm, self.VT
967
  t0 = time.perf_counter()
968
  P = b.pos
969
+ b.kv_ensure(P + VT) # [1.1] (the caches grow first)
970
  tcap = b.bucket(P + VT - 1)
971
  w, HS = b.hid // 16, 16 * BLK_W
972
  for t, tok in enumerate(toks):
 
1099
  m0 = ms[vts[-1]]
1100
  b = m0.b
1101
  for m in ms.values(): # (one MTP cache and set of row buffers for all)
1102
+ m.bufs, m.kv, m.kvm, m.kvb = m0.bufs, m0.kv, m0.kvm, m0.kvb
1103
  p = [0.8] * (vts[-1] - 1) # (EMA acceptance of draft j | drafts < j kept)
1104
  cost = dict(c or {2: 127.0, 3: 164.0})
1105
  lg, hn = m0.prompt(ids)
 
1178
  b, a, am, n = self.b, self.act, self.am, len(toks)
1179
  T = b.pos
1180
  assert 1 <= n <= self.NT and T + self.NT <= b.tmax
1181
+ b.kv_ensure(T + self.NT) # [1.1] (the caches grow first)
1182
  hs, hid = self.man.get("hstr", 5440), self.man.get("hid", 5120) # (an H row's stride, its used words)
1183
  hv = am[a["H"]:a["H"] + (self.NT + 1) * hs].view(np.float32).reshape(self.NT + 1, hs)
1184
  hv[:, :hid] = 0.0
onwx/xdna_moe.py CHANGED
@@ -159,6 +159,7 @@ class Moe:
159
  self.trace = [] if os.environ.get("ONWX_MOE_TRACE") else None # (h after each mixer, the experts)
160
  self.prof = {"read": 0.0, "route": 0.0, "set": 0.0}
161
  self.pr = {} # [0.8] prepared runs (ShimDev): key -> handle
 
162
  self.use_prep = bool(getattr(b.dev, "has_prep", False))
163
 
164
  def read_h(self):
@@ -199,6 +200,7 @@ class Moe:
199
  T = b.pos
200
  if T >= b.tmax:
201
  raise RuntimeError(f"context full ({b.tmax} tokens)")
 
202
  a, am = b.act, b.am
203
  w = b.hid // 16
204
  row = b.embed(tok) if emb is None else b.fit(emb)
@@ -251,7 +253,11 @@ class Moe:
251
  if r is None:
252
  r = self.pr[key] = b.dev.prep(*it)
253
  elif key[0] == "at":
 
 
254
  b.dev.setarg(r, 3, it[5])
 
 
255
  elif key[0] == "dn" and b.nslot > 1: # ([MTP] the state slot the step reads moves)
256
  b.dev.setarg(r, 2, it[4])
257
  return r
@@ -410,7 +416,8 @@ class MoeMtp:
410
  z = np.load(os.path.join(B, bl["host"]))
411
  self.mhost = (z["router"], z["sgate"], z["gpost"])
412
  self.kvb = b.kv_bytes(None)
413
- self.kv = b.dev.buf(self.kvb, 5)[0] # (the MTP layer's KV cache)
 
414
  self.HS = 16 * BLK_W
415
  self.XS = man.get("xs", 4096) # (X words a token: XV_W / VT)
416
  self.h_sub = self.dev.sub(self.vbo, VT * self.HS * 4, av["H2"] * 4)
@@ -455,6 +462,7 @@ class MoeMtp:
455
  return bf16_bits(x).view(np.int32)
456
 
457
  def kv_at(self, T):
 
458
  off = T // self.b.kq * PAIR_W * 4
459
  return self.b.dev.sub(self.kv, self.kvb - off, off)
460
 
@@ -576,6 +584,7 @@ class MoeMtp:
576
  b, av, vm, VT = self.b, self.av, self.vm, self.VT
577
  t0 = time.perf_counter()
578
  P = b.pos
 
579
  tcap = b.bucket(P + VT - 1)
580
  w, HS = b.hid // 16, self.HS
581
  for t, tok in enumerate(toks):
@@ -639,6 +648,7 @@ class MoeMtp:
639
  t0 = time.perf_counter()
640
  P = rows[0][2]
641
  assert len(rows) <= VT and all(r[2] == P + j for j, r in enumerate(rows))
 
642
  for t, (hn, tok, pos) in enumerate(rows):
643
  x = self.fc_in(hn, tok)
644
  o = av["XFC2"] + t * self.XS
 
159
  self.trace = [] if os.environ.get("ONWX_MOE_TRACE") else None # (h after each mixer, the experts)
160
  self.prof = {"read": 0.0, "route": 0.0, "set": 0.0}
161
  self.pr = {} # [0.8] prepared runs (ShimDev): key -> handle
162
+ self.pr_kv = {} # [1.1] (an attention run's cache: kv_grows when set)
163
  self.use_prep = bool(getattr(b.dev, "has_prep", False))
164
 
165
  def read_h(self):
 
200
  T = b.pos
201
  if T >= b.tmax:
202
  raise RuntimeError(f"context full ({b.tmax} tokens)")
203
+ b.kv_ensure(T + 1) # [1.1] (the caches grow first)
204
  a, am = b.act, b.am
205
  w = b.hid // 16
206
  row = b.embed(tok) if emb is None else b.fit(emb)
 
253
  if r is None:
254
  r = self.pr[key] = b.dev.prep(*it)
255
  elif key[0] == "at":
256
+ if self.pr_kv.get(key) != b.kv_grows: # [1.1] (the cache grew: a new buffer)
257
+ b.dev.setarg(r, 2, it[4])
258
  b.dev.setarg(r, 3, it[5])
259
+ if key[0] == "at":
260
+ self.pr_kv[key] = b.kv_grows
261
  elif key[0] == "dn" and b.nslot > 1: # ([MTP] the state slot the step reads moves)
262
  b.dev.setarg(r, 2, it[4])
263
  return r
 
416
  z = np.load(os.path.join(B, bl["host"]))
417
  self.mhost = (z["router"], z["sgate"], z["gpost"])
418
  self.kvb = b.kv_bytes(None)
419
+ self.kv, self.kvm = b.dev.buf(self.kvb, 5) # (the MTP layer's KV cache: grows with the layers')
420
+ b.kv_owners.append(self)
421
  self.HS = 16 * BLK_W
422
  self.XS = man.get("xs", 4096) # (X words a token: XV_W / VT)
423
  self.h_sub = self.dev.sub(self.vbo, VT * self.HS * 4, av["H2"] * 4)
 
462
  return bf16_bits(x).view(np.int32)
463
 
464
  def kv_at(self, T):
465
+ self.b.kv_ensure(T + 1)
466
  off = T // self.b.kq * PAIR_W * 4
467
  return self.b.dev.sub(self.kv, self.kvb - off, off)
468
 
 
584
  b, av, vm, VT = self.b, self.av, self.vm, self.VT
585
  t0 = time.perf_counter()
586
  P = b.pos
587
+ b.kv_ensure(P + VT) # [1.1] (the caches grow first)
588
  tcap = b.bucket(P + VT - 1)
589
  w, HS = b.hid // 16, self.HS
590
  for t, tok in enumerate(toks):
 
648
  t0 = time.perf_counter()
649
  P = rows[0][2]
650
  assert len(rows) <= VT and all(r[2] == P + j for j, r in enumerate(rows))
651
+ b.kv_ensure(P + VT) # [1.1] (the caches grow first)
652
  for t, (hn, tok, pos) in enumerate(rows):
653
  x = self.fc_in(hn, tok)
654
  o = av["XFC2"] + t * self.XS
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "onwx"
7
- version = "1.0.1"
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 = "1.1.0"
8
  description = "LLMs entirely on the AMD Ryzen AI NPU (XDNA2)"
9
  readme = "README.md"
10
  license = {text = "Apache-2.0"}