ryugyosoft commited on
Commit
d6c6736
·
verified ·
1 Parent(s): 01f288d

0.2.0: context up to 262144 tokens, faster long prompts

Browse files
README.md CHANGED
@@ -81,15 +81,16 @@ onwx chat ryugyosoft/Ternary-Bonsai-2-27B-onwx # 端末でチャット
81
 
82
  | モデル | ダウンロード | メモリ | 生成速度 |
83
  |---|---|---|---|
84
- | [Ternary Bonsai 2 27B](https://huggingface.co/ryugyosoft/Ternary-Bonsai-2-27B-onwx)(三値・2 ビット、Qwen3.8-27B ベース) | 7.6 GB | 約 8.5 GB | 下表 |
85
 
86
  | | プロンプトの読み込み | 文章の生成 |
87
  |---|---|---|
88
- | Ryzen AI 9 HX 370(Windows) | 約 27〜30 tok/s | 約 3.5〜3.8 tok/s |
89
  | Ryzen AI Max+ 395(Linux) | 約 36〜39 tok/s | 約 6.0 tok/s |
90
 
91
  - プロンプトは 32 トークンずつまとめて NPU で読み込みます(行列計算は int8 の行列ユニット、DeltaNet は 8 トークンずつ)。
92
- - 文脈は最大 3840 トークンです。
 
93
  - 思考モード(考えてから答える)とツール呼び出しに対応しています。画像は読めません。
94
  - 電力モードは標準のままの値です。Windows の AI 機能(Copilot+ の機能)が NPU を使っていると遅くなることがあります。
95
 
 
81
 
82
  | モデル | ダウンロード | メモリ | 生成速度 |
83
  |---|---|---|---|
84
+ | [Ternary Bonsai 2 27B](https://huggingface.co/ryugyosoft/Ternary-Bonsai-2-27B-onwx)(三値・2 ビット、Qwen3.8-27B ベース) | 7.6 GB | 約 8.5 GB + 文脈 1k トークンあたり約 68 MB | 下表 |
85
 
86
  | | プロンプトの読み込み | 文章の生成 |
87
  |---|---|---|
88
+ | Ryzen AI 9 HX 370(Windows) | 約 29〜30 tok/s | 約 4.0〜4.3 tok/s |
89
  | Ryzen AI Max+ 395(Linux) | 約 36〜39 tok/s | 約 6.0 tok/s |
90
 
91
  - プロンプトは 32 トークンずつまとめて NPU で読み込みます(行列計算は int8 の行列ユニット、DeltaNet は 8 トークンずつ)。
92
+ - 文脈は最大 262144 トークン(モデルの上限)です。既定は 32768 トークンで、設定で変えられます。
93
+ - 文脈が長いほど遅くなります。HX 370 では、4,400 トークンのプロンプトの読み込みが約 24 tok/s、その後の生成が約 3.9 tok/s、7 万トークンの位置での生成が約 1.7 tok/s です。
94
  - 思考モード(考えてから答える)とツール呼び出しに対応しています。画像は読めません。
95
  - 電力モードは標準のままの値です。Windows の AI 機能(Copilot+ の機能)が NPU を使っていると遅くなることがあります。
96
 
README_en.md CHANGED
@@ -64,15 +64,16 @@ onwx chat ryugyosoft/Ternary-Bonsai-2-27B-onwx # chat in the terminal
64
 
65
  | Model | Download | Memory | 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.5 GB | below |
68
 
69
  | | Prompt processing | Generation |
70
  |---|---|---|
71
- | Ryzen AI 9 HX 370 (Windows) | ~27-30 tok/s | ~3.5-3.8 tok/s |
72
  | Ryzen AI Max+ 395 (Linux) | ~36-39 tok/s | ~6.0 tok/s |
73
 
74
  - Prompts are read 32 tokens at a time on the NPU (int8 matrix unit for the matmuls, DeltaNet 8 tokens at a time).
75
- - Context up to 3840 tokens.
 
76
  - Thinking mode and tool calls work; images do not.
77
  - Default power mode. Windows AI features (Copilot+) using the NPU can slow it down.
78
 
 
64
 
65
  | Model | Download | Memory | 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.5 GB + ~68 MB per 1k tokens of context | below |
68
 
69
  | | Prompt processing | Generation |
70
  |---|---|---|
71
+ | Ryzen AI 9 HX 370 (Windows) | ~29-30 tok/s | ~4.0-4.3 tok/s |
72
  | Ryzen AI Max+ 395 (Linux) | ~36-39 tok/s | ~6.0 tok/s |
73
 
74
  - Prompts are read 32 tokens at a time on the NPU (int8 matrix unit for the matmuls, DeltaNet 8 tokens at a time).
75
+ - Context up to 262144 tokens (the model's limit). The default is 32768; change it in the settings.
76
+ - Longer contexts are slower. On the HX 370 a 4,400-token prompt reads at ~24 tok/s and generation after it runs at ~3.9 tok/s; at position 70k, generation is ~1.7 tok/s.
77
  - Thinking mode and tool calls work; images do not.
78
  - Default power mode. Windows AI features (Copilot+) using the NPU can slow it down.
79
 
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.1.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.2.0"
6
  NAME = "onwx"
7
  TITLE = "onwx (AMD Ryzen AI NPU)"
onwx/app.py CHANGED
@@ -9,8 +9,8 @@ import json, os, re, shutil, subprocess, sys, threading, time, urllib.request, w
9
 
10
  # The models: each carries NPU programs built for it (plans/), so only models converted for onwx run here.
11
  CATALOG = [ # repo, title, takes images, download GB, decode speed (Ryzen AI 9 HX 370), note (shown through i18n.T)
12
- ("ryugyosoft/Ternary-Bonsai-2-27B-onwx", "Ternary Bonsai 2 27B (2-bit)", False, 7.6, "3.6 tok/s",
13
- "27B を三値(2 ビット)の重みで、全部 NPU で動かします(Qwen3.8-27B ベースの Ternary Bonsai 2。生成は Ryzen AI 9 HX 370 で約 3.6 tok/s、Ryzen AI Max+ 395 で約 6 tok/s、プロンプトの読み込みは約 27〜39 tok/s)。文脈は最大 3840 トークン"),
14
  ]
15
  CATALOG_REPOS = {c[0] for c in CATALOG}
16
 
@@ -20,10 +20,11 @@ def catalog():
20
  return list(CATALOG)
21
 
22
 
23
- # Memory the model needs, for the estimate shown per PC: (GB, unused, MB per 1k tokens of context). The weights, the
24
- # DeltaNet states and the KV cache (allocated whole) sit in buffers the NPU reads: measured 8.0 GB on a HX 370.
 
25
  MEMORY = {
26
- "ryugyosoft/Ternary-Bonsai-2-27B-onwx": (8.5, 0.0, 0),
27
  }
28
  STREAMABLE = {} # (no model streams weights from the SSD)
29
  DEFAULTS = {"model": "", "port": 8100, "lan": False, "api_key": "", "context": 3840,
@@ -31,7 +32,8 @@ DEFAULTS = {"model": "", "port": 8100, "lan": False, "api_key": "", "context": 3
31
  "think_default": False, "lang": "auto",
32
  "api_sampling": "greedy", "api_temperature": 0.7, "api_top_p": 0.95, "api_top_k": 20, "api_presence": 0.0,
33
  "model_prefs": {}}
34
- CONTEXTS = ["1024", "2048", "3840"] # (3840: the longest the NPU programs hold)
 
35
 
36
 
37
  # ------------------------------------------------------------------ config
 
9
 
10
  # The models: each carries NPU programs built for it (plans/), so only models converted for onwx run here.
11
  CATALOG = [ # repo, title, takes images, download GB, decode speed (Ryzen AI 9 HX 370), note (shown through i18n.T)
12
+ ("ryugyosoft/Ternary-Bonsai-2-27B-onwx", "Ternary Bonsai 2 27B (2-bit)", False, 7.6, "4 tok/s",
13
+ "27B を三値(2 ビット)の重みで、全部 NPU で動かします(Qwen3.8-27B ベースの Ternary Bonsai 2。生成は Ryzen AI 9 HX 370 で約 4 tok/s、Ryzen AI Max+ 395 で約 6 tok/s、プロンプトの読み込みは約 30〜39 tok/s)。文脈は最大 262144 トークン"),
14
  ]
15
  CATALOG_REPOS = {c[0] for c in CATALOG}
16
 
 
20
  return list(CATALOG)
21
 
22
 
23
+ # Memory the model needs, for the estimate shown per PC: (GB at a 1024 context, unused, MB per 1k tokens more). The
24
+ # weights, the DeltaNet states and the KV cache (allocated for the context set) sit in buffers the NPU reads: 8.0 GB
25
+ # measured on a HX 370 with 3840; the cache takes 16 layers x 4 heads x 272 words = 68 MB per 1k tokens.
26
  MEMORY = {
27
+ "ryugyosoft/Ternary-Bonsai-2-27B-onwx": (8.3, 0.0, 68),
28
  }
29
  STREAMABLE = {} # (no model streams weights from the SSD)
30
  DEFAULTS = {"model": "", "port": 8100, "lan": False, "api_key": "", "context": 3840,
 
32
  "think_default": False, "lang": "auto",
33
  "api_sampling": "greedy", "api_temperature": 0.7, "api_top_p": 0.95, "api_top_k": 20, "api_presence": 0.0,
34
  "model_prefs": {}}
35
+ CONTEXTS = ["1024", "2048", "3840", "8192", "16384", "32768", "65536", "131072", "262144"] # (models built before the
36
+ # pair-major cache take 3840 at most - engine.json's max_position_embeddings caps it)
37
 
38
 
39
  # ------------------------------------------------------------------ config
onwx/chat.py CHANGED
@@ -2,7 +2,7 @@
2
  (<think> blocks, harmony channels). stream_chat yields text deltas, then one stats dict (with split_reasoning=True,
3
  thinking comes as {"reasoning": delta} dicts instead of inline text)."""
4
  import re
5
- import json, os, time
6
  import numpy as np
7
  from transformers import AutoTokenizer
8
 
@@ -76,6 +76,11 @@ class ChatEngine:
76
  self._drop = sorted(specials - set(_tools.MARKERS), key=len, reverse=True) # ... when tool markup is kept
77
  self._tool_stop = {i for i in (self.tok.convert_tokens_to_ids(t) for t in _tools.STOP_AFTER)
78
  if isinstance(i, int) and i != self.tok.unk_token_id}
 
 
 
 
 
79
  # end-of-turn ids: text config, full config and generation_config (Gemma lists <eos>, <turn|>, ...)
80
  self.eos = {self.tok.eos_token_id}
81
  cands = [self.model.cfg.get("eos_token_id")]
@@ -225,14 +230,66 @@ class ChatEngine:
225
  self._think_open = self.think_style in ("switch", "forced") and text.rstrip().endswith("<think>")
226
  tail = text[len(base):] if text.startswith(base) else None # (the generation prompt: no images in it)
227
  ids = self.tok(text, add_special_tokens=False)["input_ids"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  suffix = len(self.tok(tail, add_special_tokens=False)["input_ids"]) if tail is not None else 0
229
  return ids, min(len(ids) - suffix, len(ids) - 1), images # at least one token left for the logits
230
 
231
- def _prefill(self, ids, start=0, stop=None, need_logits=True):
232
- """Feed ids[start:stop] in blocks of the model's prompt size (16 through the prefill program); the last
233
- logits."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  m, s, lg = self.model, start, None
235
  stop = len(ids) if stop is None else stop
 
 
 
 
 
 
 
 
 
236
  while s < stop:
237
  if self._cancel is not None and self._cancel():
238
  raise Cancelled() # (the client left: not the rest of a long prompt)
@@ -308,10 +365,20 @@ class ChatEngine:
308
  if n + 16 >= self.max_context:
309
  raise ValueError(f"the prompt is {n} tokens; the context holds {self.max_context} (raise the context length "
310
  "in the settings, or onwx serve --context)")
 
 
 
 
 
 
 
 
 
 
311
  # prefix reuse: state kept at the end of the previous conversation (before its generation prompt)
312
  ck, reuse = self.checkpoint, 0
313
- if ck is not None and len(ck[0]) <= B and ids[:len(ck[0])] == ck[0]:
314
- reuse = len(ck[0])
315
  self.model.restore(ck[1])
316
  else:
317
  self.model.reset()
@@ -319,14 +386,25 @@ class ChatEngine:
319
  # leave a checkpoint over another conversation's rows)
320
  t0 = time.time()
321
  t_vis = 0.0
 
 
 
 
 
 
 
 
 
 
322
  # the client may leave during a long prompt (minutes on a big one, every other request waiting): stopped between
323
  # blocks. The checkpoint stays right - its rows are below where this prompt writes (a fresh prompt dropped it)
324
  self._cancel = should_stop
325
  try:
326
  if B > reuse:
327
- self._prefill(ids, reuse, B, need_logits=False)
328
- self.checkpoint = (ids[:B], self.model.snapshot())
329
- lg = self._prefill(ids, B, n)
 
330
  except Cancelled:
331
  yield {"finish_reason": "stop", "prompt_tokens": n, "cached_tokens": reuse, "completion_tokens": 0,
332
  "reasoning_tokens": 0, "vision_ms": t_vis * 1000, "prefill_ms": (time.time() - t0 - t_vis) * 1000,
 
2
  (<think> blocks, harmony channels). stream_chat yields text deltas, then one stats dict (with split_reasoning=True,
3
  thinking comes as {"reasoning": delta} dicts instead of inline text)."""
4
  import re
5
+ import hashlib, json, os, time
6
  import numpy as np
7
  from transformers import AutoTokenizer
8
 
 
76
  self._drop = sorted(specials - set(_tools.MARKERS), key=len, reverse=True) # ... when tool markup is kept
77
  self._tool_stop = {i for i in (self.tok.convert_tokens_to_ids(t) for t in _tools.STOP_AFTER)
78
  if isinstance(i, int) and i != self.tok.unk_token_id}
79
+ # images (Qwen3.5 with its vision tower): the tower runs on the CPU, loaded at the first image (~1.6 GB) and
80
+ # kept while the model is (ONWX_KEEP_VISION=0 frees it after each image)
81
+ self.vision = self.model.meta.get("vision")
82
+ self._venc, self._grids = None, []
83
+ self.keep_vision = os.environ.get("ONWX_KEEP_VISION", "1") != "0"
84
  # end-of-turn ids: text config, full config and generation_config (Gemma lists <eos>, <turn|>, ...)
85
  self.eos = {self.tok.eos_token_id}
86
  cands = [self.model.cfg.get("eos_token_id")]
 
230
  self._think_open = self.think_style in ("switch", "forced") and text.rstrip().endswith("<think>")
231
  tail = text[len(base):] if text.startswith(base) else None # (the generation prompt: no images in it)
232
  ids = self.tok(text, add_special_tokens=False)["input_ids"]
233
+ if images: # an image's one placeholder -> one per 2 x 2 patches of its grid
234
+ from .qwen_vision import grid_of
235
+ v = self.vision
236
+ grids = [grid_of(im, v["patch"], v["merge"], v["max_pixels"]) for im in images]
237
+ it, out = iter(grids), []
238
+ for x in ids:
239
+ if x == v["image_token_id"]:
240
+ gh, gw = next(it)
241
+ out += [x] * ((gh // v["merge"]) * (gw // v["merge"]))
242
+ else:
243
+ out.append(x)
244
+ ids = out
245
+ if not count:
246
+ self._grids = grids
247
  suffix = len(self.tok(tail, add_special_tokens=False)["input_ids"]) if tail is not None else 0
248
  return ids, min(len(ids) - suffix, len(ids) - 1), images # at least one token left for the logits
249
 
250
+ def _positions(self, ids):
251
+ """MRoPE rows (t, h, w) for a prompt with images (self._grids, in order), and the delta for the positions
252
+ that follow (transformers' get_rope_index)"""
253
+ v = self.vision
254
+ tid, mg, grids = v["image_token_id"], v["merge"], iter(self._grids)
255
+ n, pos, st, i = len(ids), np.zeros((3, len(ids)), np.int64), 0, 0
256
+ while i < n:
257
+ if ids[i] == tid:
258
+ gh, gw = next(grids)
259
+ hh, ww = gh // mg, gw // mg
260
+ r = np.arange(hh * ww)
261
+ pos[0, i:i + hh * ww], pos[1, i:i + hh * ww], pos[2, i:i + hh * ww] = st, st + r // ww, st + r % ww
262
+ st += max(hh, ww)
263
+ i += hh * ww
264
+ else:
265
+ pos[:, i] = st
266
+ st += 1
267
+ i += 1
268
+ return pos, st - n
269
+
270
+ def _image_rows(self, img):
271
+ if self._venc is None:
272
+ from .qwen_vision import QwenVision
273
+ t0 = time.time()
274
+ self._venc = QwenVision(self.model.dir, self.model.meta["vision"]["config"])
275
+ print(f"[vision] encoder loaded in {time.time() - t0:.1f}s", flush=True)
276
+ rows, _ = self._venc.encode(img, self.vision["max_pixels"])
277
+ return rows
278
+
279
+ def _prefill(self, ids, start=0, stop=None, need_logits=True, embeds=None, pos=None):
280
+ """Feed ids[start:stop] in blocks of the model's prompt size (16 through the prefill program; with image rows /
281
+ explicit positions given, token by token); the last logits."""
282
  m, s, lg = self.model, start, None
283
  stop = len(ids) if stop is None else stop
284
+ if embeds is not None or pos is not None:
285
+ while s < stop: # (blocks of 32: the client may leave meanwhile)
286
+ if self._cancel is not None and self._cancel():
287
+ raise Cancelled()
288
+ k = min(32, stop - s)
289
+ lg = m.step(ids[s:s + k], None if embeds is None else embeds[s:s + k],
290
+ None if pos is None else pos[:, s:s + k], want_logits=(s + k >= stop and need_logits))
291
+ s += k
292
+ return lg[-1] if lg is not None else None
293
  while s < stop:
294
  if self._cancel is not None and self._cancel():
295
  raise Cancelled() # (the client left: not the rest of a long prompt)
 
365
  if n + 16 >= self.max_context:
366
  raise ValueError(f"the prompt is {n} tokens; the context holds {self.max_context} (raise the context length "
367
  "in the settings, or onwx serve --context)")
368
+ # images: the token spans they occupy, and a content hash so a different picture is never "reused"
369
+ spans, embeds, pos, delta = [], None, None, 0
370
+ if images:
371
+ tid = self.vision["image_token_id"]
372
+ starts = [i for i in range(n) if ids[i] == tid and (i == 0 or ids[i - 1] != tid)]
373
+ ends = [next((j for j in range(s0, n) if ids[j] != tid), n) for s0 in starts]
374
+ spans = [(s0, e0, hashlib.sha1(np.asarray(im.convert("RGB")).tobytes()).hexdigest())
375
+ for s0, e0, im in zip(starts, ends, images)]
376
+ pos, delta = self._positions(ids)
377
+ key = lambda upto: (ids[:upto], [h for s0, e0, h in spans if s0 < upto])
378
  # prefix reuse: state kept at the end of the previous conversation (before its generation prompt)
379
  ck, reuse = self.checkpoint, 0
380
+ if ck is not None and len(ck[0][0]) <= B and key(len(ck[0][0])) == ck[0]:
381
+ reuse = len(ck[0][0])
382
  self.model.restore(ck[1])
383
  else:
384
  self.model.reset()
 
386
  # leave a checkpoint over another conversation's rows)
387
  t0 = time.time()
388
  t_vis = 0.0
389
+ if images and any(e0 > reuse for s0, e0, _ in spans):
390
+ embeds = self.model.embed_rows(ids)
391
+ for (s0, e0, _), im in zip(spans, images):
392
+ if e0 > reuse:
393
+ tv = time.time()
394
+ embeds[s0:e0] = self._image_rows(im)
395
+ t_vis += time.time() - tv
396
+ if not self.keep_vision:
397
+ self._venc = None
398
+ self.model.delta = 0
399
  # the client may leave during a long prompt (minutes on a big one, every other request waiting): stopped between
400
  # blocks. The checkpoint stays right - its rows are below where this prompt writes (a fresh prompt dropped it)
401
  self._cancel = should_stop
402
  try:
403
  if B > reuse:
404
+ self._prefill(ids, reuse, B, need_logits=False, embeds=embeds, pos=pos)
405
+ self.checkpoint = (key(B), self.model.snapshot())
406
+ lg = self._prefill(ids, B, n, embeds=embeds, pos=pos)
407
+ self.model.delta = delta
408
  except Cancelled:
409
  yield {"finish_reason": "stop", "prompt_tokens": n, "cached_tokens": reuse, "completion_tokens": 0,
410
  "reasoning_tokens": 0, "vision_ms": t_vis * 1000, "prefill_ms": (time.time() - t0 - t_vis) * 1000,
onwx/i18n.json CHANGED
@@ -352,7 +352,7 @@
352
  "AMD Ryzen AI の NPU で LLM": "LLMs on the AMD Ryzen AI NPU",
353
  "AMD Ryzen AI の NPU が見つかりません": "No AMD Ryzen AI NPU found",
354
  "この PC には AMD Ryzen AI の NPU がありません": "This PC has no AMD Ryzen AI NPU",
355
- "27B を三値(2 ビット)の重みで、全部 NPU で動かします(Qwen3.8-27B ベースの Ternary Bonsai 2。生成は Ryzen AI 9 HX 370 で約 3.6 tok/s、Ryzen AI Max+ 395 で約 6 tok/s、プロンプトの読み込みは約 27〜39 tok/s)。文脈は最大 3840 トークン": "A 27B with ternary (2-bit) weights, run entirely on the NPU (Ternary Bonsai 2, from Qwen3.8-27B; generation about 3.6 tok/s on a Ryzen AI 9 HX 370, 6 tok/s on a Ryzen AI Max+ 395, prompts read at about 27-39 tok/s). Context up to 3840 tokens",
356
  "一度に 1 モデル。別のモデルを選んで「切り替え」を押すと、今のモデルをアンロードしてから読み込みます。": "One model at a time. Pick another and press \"Switch\": the current model is unloaded, then the new one loaded.",
357
  "会話で使える最大の長さ(NPU のプログラムが持てるのは 3840 トークンまで)。": "The longest conversation (the NPU programs hold up to 3840 tokens)."
358
  },
@@ -709,7 +709,7 @@
709
  "AMD Ryzen AI の NPU で LLM": "在 AMD Ryzen AI 的 NPU 上运行 LLM",
710
  "AMD Ryzen AI の NPU が見つかりません": "未找到 AMD Ryzen AI 的 NPU",
711
  "この PC には AMD Ryzen AI の NPU がありません": "此电脑没有 AMD Ryzen AI 的 NPU",
712
- "27B を三値(2 ビット)の重みで、全部 NPU で動かします(Qwen3.8-27B ベースの Ternary Bonsai 2。生成は Ryzen AI 9 HX 370 で約 3.6 tok/s、Ryzen AI Max+ 395 で約 6 tok/s、プロンプトの読み込みは約 27〜39 tok/s)。文脈は最大 3840 トークン": "三值(2 位)权重的 27B,全部在 NPU 上运行(基于 Qwen3.8-27B 的 Ternary Bonsai 2。生成:Ryzen AI 9 HX 370 约 3.6 tok/s,Ryzen AI Max+ 395 约 6 tok/s;提示词读取约 27~39 tok/s)。上下文最多 3840 个 token",
713
  "一度に 1 モデル。別のモデルを選んで「切り替え」を押すと、今のモデルをアンロードしてから読み込みます。": "一次一个模型。选择另一个模型并按“切换”,会先卸载当前模型再加载。",
714
  "会話で使える最大の長さ(NPU のプログラムが持てるのは 3840 トークンまで)。": "对话的最大长度(NPU 程序最多容纳 3840 个 token)。"
715
  }
 
352
  "AMD Ryzen AI の NPU で LLM": "LLMs on the AMD Ryzen AI NPU",
353
  "AMD Ryzen AI の NPU が見つかりません": "No AMD Ryzen AI NPU found",
354
  "この PC には AMD Ryzen AI の NPU がありません": "This PC has no AMD Ryzen AI NPU",
355
+ "27B を三値(2 ビット)の重みで、全部 NPU で動かします(Qwen3.8-27B ベースの Ternary Bonsai 2。生成は Ryzen AI 9 HX 370 で約 4 tok/s、Ryzen AI Max+ 395 で約 6 tok/s、プロンプトの読み込みは約 30〜39 tok/s)。文脈は最大 262144 トークン": "A 27B with ternary (2-bit) weights, run entirely on the NPU (Ternary Bonsai 2, from Qwen3.8-27B; generation about 4 tok/s on a Ryzen AI 9 HX 370, 6 tok/s on a Ryzen AI Max+ 395, prompts read at about 30-39 tok/s). Context up to 262144 tokens",
356
  "一度に 1 モデル。別のモデルを選んで「切り替え」を押すと、今のモデルをアンロードしてから読み込みます。": "One model at a time. Pick another and press \"Switch\": the current model is unloaded, then the new one loaded.",
357
  "会話で使える最大の長さ(NPU のプログラムが持てるのは 3840 トークンまで)。": "The longest conversation (the NPU programs hold up to 3840 tokens)."
358
  },
 
709
  "AMD Ryzen AI の NPU で LLM": "在 AMD Ryzen AI 的 NPU 上运行 LLM",
710
  "AMD Ryzen AI の NPU が見つかりません": "未找到 AMD Ryzen AI 的 NPU",
711
  "この PC には AMD Ryzen AI の NPU がありません": "此电脑没有 AMD Ryzen AI 的 NPU",
712
+ "27B を三値(2 ビット)の重みで、全部 NPU で動かします(Qwen3.8-27B ベースの Ternary Bonsai 2。生成は Ryzen AI 9 HX 370 で約 4 tok/s、Ryzen AI Max+ 395 で約 6 tok/s、プロンプトの読み込みは約 30〜39 tok/s)。文脈は最大 262144 トークン": "三值(2 位)权重的 27B,全部在 NPU 上运行(基于 Qwen3.8-27B 的 Ternary Bonsai 2。生成:Ryzen AI 9 HX 370 约 4 tok/s,Ryzen AI Max+ 395 约 6 tok/s;提示词读取约 30~39 tok/s)。上下文最多 262144 个 token",
713
  "一度に 1 モデル。別のモデルを選んで「切り替え」を押すと、今のモデルをアンロードしてから読み込みます。": "一次一个模型。选择另一个模型并按“切换”,会先卸载当前模型再加载。",
714
  "会話で使える最大の長さ(NPU のプログラムが持てるのは 3840 トークンまで)。": "对话的最大长度(NPU 程序最多容纳 3840 个 token)。"
715
  }
onwx/qwen_vision.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Qwen3.5's vision tower in numpy, on the CPU: an image -> its rows for the language model (one per 2 x 2 patches).
2
+
3
+ The model folder's vision.npz holds the tower's weights (bf16 as uint16, as the checkpoint has them; float32 here).
4
+ The image is resized to a multiple of 32 pixels (Qwen2-VL's smart_resize, its pixel count capped), patchified in the
5
+ processor's merge-window order; the learned 48 x 48 position table is resampled bilinearly (align_corners) and the
6
+ 2-D rotary tables (axial, theta 10000) are made for that grid - what transformers' Qwen3_5VisionModel does.
7
+ """
8
+ import math
9
+ import os
10
+ import numpy as np
11
+
12
+ VP = "model.visual."
13
+
14
+
15
+ def smart_resize(h, w, factor=32, min_pixels=128 * 128, max_pixels=512 * 512):
16
+ hb, wb = max(factor, round(h / factor) * factor), max(factor, round(w / factor) * factor)
17
+ if hb * wb > max_pixels:
18
+ beta = math.sqrt(h * w / max_pixels)
19
+ hb, wb = max(factor, math.floor(h / beta / factor) * factor), max(factor, math.floor(w / beta / factor) * factor)
20
+ elif hb * wb < min_pixels:
21
+ beta = math.sqrt(min_pixels / (h * w))
22
+ hb, wb = math.ceil(h * beta / factor) * factor, math.ceil(w * beta / factor) * factor
23
+ return hb, wb
24
+
25
+
26
+ def grid_of(img, ps=16, m=2, max_pixels=512 * 512):
27
+ """the patch grid (gh, gw) an image gets"""
28
+ w, h = img.size
29
+ hb, wb = smart_resize(h, w, ps * m, max_pixels=max_pixels)
30
+ return hb // ps, wb // ps
31
+
32
+
33
+ def patchify(img, grid, ps=16, tp=2, m=2, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)):
34
+ """PIL image -> pixel patches [gh * gw, 3 * tp * ps * ps] in the processor's merge-window order"""
35
+ from PIL import Image
36
+ gh, gw = grid
37
+ im = img.convert("RGB").resize((gw * ps, gh * ps), Image.BICUBIC)
38
+ a = (np.asarray(im, np.float32) / 255.0 - np.array(mean, np.float32)) / np.array(std, np.float32)
39
+ a = np.repeat(a.transpose(2, 0, 1)[None], tp, 0) # [tp, C, H, W]
40
+ C = a.shape[1]
41
+ a = a.reshape(1, tp, C, gh // m, m, ps, gw // m, m, ps).transpose(0, 3, 6, 4, 7, 2, 1, 5, 8)
42
+ return np.ascontiguousarray(a.reshape(gh * gw, C * tp * ps * ps))
43
+
44
+
45
+ def _erf(x): # Abramowitz-Stegun 7.1.26 (|error| < 1.5e-7)
46
+ s = np.sign(x)
47
+ a = np.abs(x)
48
+ t = 1.0 / (1.0 + 0.3275911 * a)
49
+ y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * np.exp(-a * a)
50
+ return (s * y).astype(np.float32)
51
+
52
+
53
+ def _gelu_tanh(x):
54
+ return (0.5 * x * (1.0 + np.tanh(np.float32(math.sqrt(2 / math.pi)) * (x + np.float32(0.044715) * x * x * x)))).astype(np.float32)
55
+
56
+
57
+ def _layernorm(x, w, b, eps=1e-6):
58
+ mu = x.mean(-1, keepdims=True)
59
+ xc = x - mu
60
+ return xc / np.sqrt((xc * xc).mean(-1, keepdims=True) + np.float32(eps)) * w + b
61
+
62
+
63
+ def _rot_half(x):
64
+ h = x.shape[-1] // 2
65
+ return np.concatenate([-x[..., h:], x[..., :h]], -1)
66
+
67
+
68
+ class QwenVision:
69
+ def __init__(self, d, cfg):
70
+ """d: the model folder (vision.npz); cfg: config.json's vision_config"""
71
+ self.cfg = cfg
72
+ z = np.load(os.path.join(d, "vision.npz"))
73
+ self.W = {k: ((z[k].astype(np.uint32) << 16).view(np.float32) if z[k].dtype == np.uint16 else z[k].astype(np.float32))
74
+ for k in z.files}
75
+ self.D, self.nh = cfg["hidden_size"], cfg["num_heads"]
76
+ self.hd = self.D // self.nh
77
+ self.side = int(cfg["num_position_embeddings"] ** 0.5)
78
+ self.m = cfg["spatial_merge_size"]
79
+
80
+ def _w(self, n):
81
+ return self.W[VP + n]
82
+
83
+ def _tables(self, grid):
84
+ """position embeddings [N, D] and rotary cos / sin [N, hd] of the patches (merge-window order)"""
85
+ gh, gw, m, side = grid[0], grid[1], self.m, self.side
86
+ br, bc, ir, ic = np.meshgrid(np.arange(gh // m), np.arange(gw // m), np.arange(m), np.arange(m), indexing="ij")
87
+ row, col = (br * m + ir).reshape(-1), (bc * m + ic).reshape(-1)
88
+
89
+ def taps(idx, size):
90
+ src = idx * (side - 1) / max(size - 1, 1)
91
+ f = np.floor(src)
92
+ t = np.stack([f, f + 1], 1)
93
+ return np.clip(t, 0, side - 1).astype(np.int64), np.clip(1 - np.abs(src[:, None] - t), 0, None)
94
+ th, wh = taps(row, gh)
95
+ tw, ww = taps(col, gw)
96
+ tab = self._w("pos_embed.weight")
97
+ pos = np.zeros((len(row), self.D), np.float32)
98
+ for a in range(2):
99
+ for b in range(2):
100
+ pos += (wh[:, a] * ww[:, b])[:, None].astype(np.float32) * tab[th[:, a] * side + tw[:, b]]
101
+ sd = self.hd // 2
102
+ inv = 1.0 / (10000.0 ** (np.arange(0, sd, 2) / sd))
103
+ emb = np.concatenate([row[:, None] * inv, col[:, None] * inv], 1)
104
+ emb = np.concatenate([emb, emb], 1)
105
+ return pos, np.cos(emb).astype(np.float32), np.sin(emb).astype(np.float32)
106
+
107
+ def encode(self, img, max_pixels=512 * 512):
108
+ """PIL image -> (rows [n, out_hidden] float32, (gh, gw) patch grid)"""
109
+ c = self.cfg
110
+ grid = grid_of(img, c["patch_size"], self.m, max_pixels)
111
+ px = patchify(img, grid, c["patch_size"], c["temporal_patch_size"], self.m)
112
+ pos, cos, sin = self._tables(grid)
113
+ N, D, nh, hd = px.shape[0], self.D, self.nh, self.hd
114
+ pw = self._w("patch_embed.proj.weight")
115
+ x = px @ pw.reshape(pw.shape[0], -1).T + self._w("patch_embed.proj.bias") + pos
116
+ cs, sn = cos[:, None, :], sin[:, None, :]
117
+ sc = np.float32(1.0 / math.sqrt(hd))
118
+ for b in range(c["depth"]):
119
+ p = f"blocks.{b}."
120
+ h = _layernorm(x, self._w(p + "norm1.weight"), self._w(p + "norm1.bias"))
121
+ qkv = (h @ self._w(p + "attn.qkv.weight").T + self._w(p + "attn.qkv.bias")).reshape(N, 3, nh, hd)
122
+ q, k, v = qkv[:, 0], qkv[:, 1], qkv[:, 2]
123
+ q = q * cs + _rot_half(q) * sn
124
+ k = k * cs + _rot_half(k) * sn
125
+ s = (q.transpose(1, 0, 2) * sc) @ k.transpose(1, 2, 0) # [nh, N, N] (BLAS)
126
+ s = np.exp(s - s.max(-1, keepdims=True))
127
+ s /= s.sum(-1, keepdims=True)
128
+ o = (s @ v.transpose(1, 0, 2)).transpose(1, 0, 2).reshape(N, D)
129
+ x = x + o @ self._w(p + "attn.proj.weight").T + self._w(p + "attn.proj.bias")
130
+ h = _layernorm(x, self._w(p + "norm2.weight"), self._w(p + "norm2.bias"))
131
+ h = _gelu_tanh(h @ self._w(p + "mlp.linear_fc1.weight").T + self._w(p + "mlp.linear_fc1.bias"))
132
+ x = x + h @ self._w(p + "mlp.linear_fc2.weight").T + self._w(p + "mlp.linear_fc2.bias")
133
+ x = _layernorm(x, self._w("merger.norm.weight"), self._w("merger.norm.bias")).reshape(N // (self.m ** 2), -1)
134
+ h = x @ self._w("merger.linear_fc1.weight").T + self._w("merger.linear_fc1.bias")
135
+ h = (0.5 * h * (1.0 + _erf(h / np.float32(math.sqrt(2))))).astype(np.float32)
136
+ return h @ self._w("merger.linear_fc2.weight").T + self._w("merger.linear_fc2.bias"), grid
onwx/web/manage.html CHANGED
@@ -239,7 +239,7 @@
239
  <div class="card set sub" data-sub="server">
240
  <div class="opt"><span class="k">ポート</span><input type="number" id="f-port" style="width:90px"></div>
241
  <div class="opt"><span class="k">API キー(任意)</span><input type="password" id="f-api_key" placeholder="未設定なら何を入れても通ります" style="width:260px"></div>
242
- <div class="opt"><span class="k">コンテキスト長</span><select id="f-context" style="width:110px"><option>1024</option><option>2048</option><option>3840</option></select> <span id="ctxnote" class="small muted"></span>
243
  <span class="desc">会話で使える最大の長さ(NPU のプログラムが持てるのは 3840 トークンまで)。</span></div>
244
  <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>
245
  </div>
 
239
  <div class="card set sub" data-sub="server">
240
  <div class="opt"><span class="k">ポート</span><input type="number" id="f-port" style="width:90px"></div>
241
  <div class="opt"><span class="k">API キー(任意)</span><input type="password" id="f-api_key" placeholder="未設定なら何を入れても通ります" style="width:260px"></div>
242
+ <div class="opt"><span class="k">コンテキスト長</span><select id="f-context" style="width:110px"><option>1024</option><option>2048</option><option>3840</option><option>8192</option><option>16384</option><option>32768</option><option>65536</option><option>131072</option><option>262144</option></select> <span id="ctxnote" class="small muted"></span>
243
  <span class="desc">会話で使える最大の長さ(NPU のプログラムが持てるのは 3840 トークンまで)。</span></div>
244
  <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>
245
  </div>
onwx/xdna.py CHANGED
@@ -17,6 +17,7 @@ import numpy as np
17
 
18
  BLK_W = 544
19
  REC = 256 # words per attention cache record (k 256 bf16 | v 256 bf16)
 
20
  HERE = os.path.dirname(os.path.abspath(__file__))
21
 
22
 
@@ -155,15 +156,25 @@ while H32.shape[0] < 32:
155
 
156
 
157
  class Bonsai:
158
- """d: the model folder (xdna.json, plans/, blobs/, embed.npz). One token per step()."""
159
- def __init__(self, d):
 
160
  self.d = d
161
  man = self.man = json.load(open(os.path.join(d, "xdna.json")))
162
  c = self.cfg = man["config"]
163
  self.L, self.types = c["num_hidden_layers"], c["layer_types"]
164
  self.rot = man["rope"]["dim"]
165
  self.inv_freq = 1.0 / (man["rope"]["theta"] ** (np.arange(0, self.rot, 2) / self.rot))
166
- self.tmax, self.hstr = man["tmax"], man["hstr"]
 
 
 
 
 
 
 
 
 
167
  self.act = man["act"] # region offsets (words) in the activation buffer
168
  P = os.path.join(d, "plans")
169
  self.dev = open_device(os.path.join(P, man["xclbin"]))
@@ -183,7 +194,8 @@ class Bonsai:
183
  if self.types[l] == "linear_attention":
184
  self.st[l] = self.load(os.path.join(B, f"L{l}.st"), 5) # (bo, map, path)
185
  else:
186
- self.kv[l] = self.dev.buf(4 * self.hstr * 4, 5)[0]
 
187
  self.actbo, am = self.dev.buf(man["act_words"] * 4, 4)
188
  self.am = am.view(np.int32)
189
  init = np.fromfile(os.path.join(B, "act.init"), dtype=np.int32)
@@ -191,8 +203,13 @@ class Bonsai:
191
  self.dev.sync(self.actbo, True)
192
  self.dummy = self.dev.buf(64, 6)[0]
193
  self.load_s = time.time() - t
194
- e = np.load(os.path.join(d, "embed.npz"))
195
- self.emb_codes, self.emb_scales, self.emb_signs = e["codes"], e["scales"], e["signs"]
 
 
 
 
 
196
  self.pos = 0
197
  self.t_npu = 0.0
198
  self.pf = Prefill(self) if "pf" in man and os.environ.get("ONWX_PREFILL", "1") != "0" else None
@@ -213,6 +230,7 @@ class Bonsai:
213
  f.readinto(memoryview(m[:os.path.getsize(path)]))
214
  self.dev.sync(bo, True)
215
  self.pos = 0
 
216
 
217
  def snapshot(self):
218
  """the position and the DeltaNet states (the KV rows below the position are never rewritten)"""
@@ -230,6 +248,8 @@ class Bonsai:
230
  self.pos = pos
231
 
232
  def embed(self, tok):
 
 
233
  c = ((self.emb_codes[tok][:, None] >> (2 * np.arange(16, dtype=np.uint32))) & 3).reshape(-1).astype(np.float32) - 1
234
  row = (c.reshape(-1, 128) * self.emb_scales[tok].astype(np.float32)[:, None]).reshape(-1)
235
  y = (H32 @ row.reshape(-1, 32, 32) @ H32).reshape(-1) / 32
@@ -241,6 +261,10 @@ class Bonsai:
241
  toks = list(toks)
242
  i, h = 0, None
243
  while self.pf is not None and len(toks) - i >= 2 and self.pos + self.pf.NT <= self.tmax:
 
 
 
 
244
  k = min(self.pf.NT, len(toks) - i)
245
  h = self.pf.run(toks[i:i + k])
246
  i += k
@@ -256,7 +280,8 @@ class Bonsai:
256
  def head(self, h):
257
  """the logits of residual h (fp32 [5120]): the decode program's head op"""
258
  a, am = self.act, self.am
259
- am[a["H"]:a["H"] + 16 * BLK_W].view(np.float32).reshape(16, BLK_W)[:, :320] = h.reshape(16, 320)
 
260
  self.dev.sync(self.actbo, True)
261
  hi = self.ins["head"]
262
  self.dev.run(hi[0], hi[1], self.hbo, self.actbo, self.dummy, self.dummy)
@@ -267,22 +292,43 @@ class Bonsai:
267
  return lg[:self.cfg["vocab_size"]].copy()
268
 
269
  def bucket(self, T):
 
 
 
270
  return min(256 * ((T + 256) // 256), self.man["tcap_max"])
271
 
272
- def step(self, tok, want_logits=True):
273
- """feed one token at position self.pos; returns the logits (float32 [vocab]) or None."""
 
 
 
 
 
 
 
 
 
 
 
 
274
  T = self.pos
275
  if T >= self.tmax:
276
  raise RuntimeError(f"context full ({self.tmax} tokens)")
277
  a, am = self.act, self.am
278
- am[a["H"]:a["H"] + 16 * BLK_W].view(np.float32).reshape(16, BLK_W)[:, :320] = self.embed(tok).reshape(16, 320)
 
 
279
  tcap = self.bucket(T)
280
  hd = np.zeros(BLK_W, np.int32)
281
- hd[0], hd[5], hd[9] = 3, 10 + tcap // 2, 3 # attention header: op, B count, F count
 
 
 
282
  am[a["AH"]:a["AH"] + 4 * BLK_W] = np.tile(hd, 4)
283
  pb = np.zeros(BLK_W, np.int32)
284
  pb[0] = T
285
- ang = T * self.inv_freq
 
286
  pb.view(np.float32)[16:48], pb.view(np.float32)[48:80] = np.cos(ang), np.sin(ang)
287
  am[a["POS"]:a["POS"] + 4 * BLK_W] = np.tile(pb, 4)
288
  self.dev.sync(self.actbo, True)
@@ -292,7 +338,7 @@ class Bonsai:
292
  if self.types[l] == "linear_attention":
293
  self.dev.run(dn[0], dn[1], self.wbo[l], self.actbo, self.st[l][0], self.dummy)
294
  else:
295
- sub = self.dev.sub(self.kv[l], 4 * self.hstr * 4 - T * REC * 4, T * REC * 4)
296
  self.dev.run(ins_at[0], ins_at[1], self.wbo[l], self.actbo, self.kv[l], sub)
297
  self.dev.free(sub)
298
  self.pos += 1
@@ -350,16 +396,22 @@ class Prefill:
350
  tcaps = self.man.get("tcaps") # (the plans' cache extents; older programs: the decode buckets)
351
  n_at = self.NT if n > 16 else 16 # (32-token programs: attention plans of 16 and 32 tokens)
352
  tcap = min(c for c in tcaps if c >= T + n_at) if tcaps else b.bucket(T + self.NT - 1)
 
353
  hd = np.zeros(BLK_W, np.int32)
354
- hd[0], hd[5], hd[9] = 3, 10 + tcap // 2, 3
355
- am[a["AH"]:a["AH"] + self.NT * 4 * BLK_W] = np.tile(hd, self.NT * 4)
356
- pv = am[a["POS"]:a["POS"] + self.NT * 4 * BLK_W].reshape(self.NT, 4, BLK_W)
357
  for t in range(self.NT):
358
- pb = np.zeros(BLK_W, np.int32)
359
- pb[0] = T + t
360
- ang = (T + t) * b.inv_freq
361
- pb.view(np.float32)[16:48], pb.view(np.float32)[48:80] = np.cos(ang), np.sin(ang)
362
- pv[t] = pb
 
 
 
 
 
 
 
363
  self.dev.sync(self.abo, True)
364
  ins_at = self.ins[f"at{tcap}_{n_at}" if self.NT > 16 else f"at{tcap}"]
365
  for l in range(b.L):
@@ -367,7 +419,7 @@ class Prefill:
367
  ins = self.ins[f"dn{'0' if l == 0 else ''}_{n}"]
368
  self.dev.run(ins[0], ins[1], b.wbo[l], self.abo, b.st[l][0], self.pf[l])
369
  else:
370
- sub = b.dev.sub(b.kv[l], 4 * b.hstr * 4 - T * REC * 4, T * REC * 4)
371
  self.dev.run(ins_at[0], ins_at[1], b.wbo[l], self.abo, b.kv[l], sub)
372
  b.dev.free(sub)
373
  b.pos += n
@@ -383,11 +435,11 @@ class XdnaModel:
383
  swapping = False
384
  block_gb = None
385
  mtp = None
386
- embed_rows = None
387
  exact_truncate = False
388
 
389
  def __init__(self, d, context=None):
390
- self.rt = Bonsai(d)
 
391
  self.meta = json.load(open(os.path.join(d, "engine.json")))
392
  self.cfg = self.meta["config"]
393
  self.T = min(int(context), self.rt.tmax) if context else self.rt.tmax
@@ -402,12 +454,22 @@ class XdnaModel:
402
  def cur(self):
403
  return self.rt.pos
404
 
 
 
 
405
  def step(self, ids, embeds=None, pos=None, want_logits=True):
406
- if embeds is not None:
407
- raise NotImplementedError("images: not on the AMD NPU build")
408
  if isinstance(pos, int) and pos != self.rt.pos: # (text positions arrays are always the running ones)
409
  raise RuntimeError(f"step at {pos}: the AMD NPU build continues at {self.rt.pos} only")
410
- if len(ids) > 1:
 
 
 
 
 
 
 
411
  lg = self.rt.prefill([int(t) for t in ids], want_logits=want_logits)
412
  else:
413
  lg = self.rt.step(int(ids[0]), want_logits=want_logits)
 
17
 
18
  BLK_W = 544
19
  REC = 256 # words per attention cache record (k 256 bf16 | v 256 bf16)
20
+ PAIR = 4 * BLK_W # pair-major cache ("kv": "pair"): [pair P][head 4][pos 2P, 2P+1 | 32 spare]
21
  HERE = os.path.dirname(os.path.abspath(__file__))
22
 
23
 
 
156
 
157
 
158
  class Bonsai:
159
+ """d: the model folder (xdna.json, plans/, blobs/, embed.npz). One token per step(). context: the positions the
160
+ attention caches are allocated for (pair-major programs: up to xdna.json "tmax"; older ones: their fixed 3840)."""
161
+ def __init__(self, d, context=None):
162
  self.d = d
163
  man = self.man = json.load(open(os.path.join(d, "xdna.json")))
164
  c = self.cfg = man["config"]
165
  self.L, self.types = c["num_hidden_layers"], c["layer_types"]
166
  self.rot = man["rope"]["dim"]
167
  self.inv_freq = 1.0 / (man["rope"]["theta"] ** (np.arange(0, self.rot, 2) / self.rot))
168
+ # MRoPE (images): which of (t, h, w) each rotary frequency follows - Qwen3.5's interleaved sections
169
+ rp = c.get("rope_parameters", {})
170
+ sec = rp.get("mrope_section", [self.rot // 2, 0, 0])
171
+ j = np.arange(self.rot // 2)
172
+ self.axis = np.where((j % 3 == 1) & (j < 3 * sec[1]), 1, np.where((j % 3 == 2) & (j < 3 * sec[2]), 2, 0)) if rp.get("mrope_interleaved") else np.zeros(self.rot // 2, np.int64)
173
+ self.rdelta = 0 # (rotary position = cache slot + rdelta after images)
174
+ self.pair = man.get("kv") == "pair"
175
+ # (no context given: 32768, the server's default - the whole 262144 would allocate ~18 GB of cache)
176
+ self.tmax = min(int(context or 32768), man["tmax"]) if self.pair else man["tmax"]
177
+ self.hstr = man.get("hstr", 0)
178
  self.act = man["act"] # region offsets (words) in the activation buffer
179
  P = os.path.join(d, "plans")
180
  self.dev = open_device(os.path.join(P, man["xclbin"]))
 
194
  if self.types[l] == "linear_attention":
195
  self.st[l] = self.load(os.path.join(B, f"L{l}.st"), 5) # (bo, map, path)
196
  else:
197
+ n = ((self.tmax + 1) // 2 + 1) * PAIR if self.pair else 4 * self.hstr
198
+ self.kv[l] = self.dev.buf(n * 4, 5)[0]
199
  self.actbo, am = self.dev.buf(man["act_words"] * 4, 4)
200
  self.am = am.view(np.int32)
201
  init = np.fromfile(os.path.join(B, "act.init"), dtype=np.int32)
 
203
  self.dev.sync(self.actbo, True)
204
  self.dummy = self.dev.buf(64, 6)[0]
205
  self.load_s = time.time() - t
206
+ self.hid = man.get("hid", 5120) # (hidden size: H holds 16 slots of hid / 16)
207
+ if man.get("embed") == "bf16": # (the embedding table as bf16 [vocab][hid])
208
+ self.emb_bf16 = np.memmap(os.path.join(d, "embed.bf16"), np.uint16, "r").reshape(-1, self.hid)
209
+ else:
210
+ e = np.load(os.path.join(d, "embed.npz"))
211
+ self.emb_bf16 = None
212
+ self.emb_codes, self.emb_scales, self.emb_signs = e["codes"], e["scales"], e["signs"]
213
  self.pos = 0
214
  self.t_npu = 0.0
215
  self.pf = Prefill(self) if "pf" in man and os.environ.get("ONWX_PREFILL", "1") != "0" else None
 
230
  f.readinto(memoryview(m[:os.path.getsize(path)]))
231
  self.dev.sync(bo, True)
232
  self.pos = 0
233
+ self.rdelta = 0
234
 
235
  def snapshot(self):
236
  """the position and the DeltaNet states (the KV rows below the position are never rewritten)"""
 
248
  self.pos = pos
249
 
250
  def embed(self, tok):
251
+ if self.emb_bf16 is not None:
252
+ return (np.asarray(self.emb_bf16[tok]).astype(np.uint32) << 16).view(np.float32)
253
  c = ((self.emb_codes[tok][:, None] >> (2 * np.arange(16, dtype=np.uint32))) & 3).reshape(-1).astype(np.float32) - 1
254
  row = (c.reshape(-1, 128) * self.emb_scales[tok].astype(np.float32)[:, None]).reshape(-1)
255
  y = (H32 @ row.reshape(-1, 32, 32) @ H32).reshape(-1) / 32
 
261
  toks = list(toks)
262
  i, h = 0, None
263
  while self.pf is not None and len(toks) - i >= 2 and self.pos + self.pf.NT <= self.tmax:
264
+ if self.pair and self.pos % 2: # (pair-major: a batch starts at an even position)
265
+ self.step(toks[i], want_logits=False)
266
+ i += 1
267
+ continue
268
  k = min(self.pf.NT, len(toks) - i)
269
  h = self.pf.run(toks[i:i + k])
270
  i += k
 
280
  def head(self, h):
281
  """the logits of residual h (fp32 [5120]): the decode program's head op"""
282
  a, am = self.act, self.am
283
+ w = self.hid // 16
284
+ am[a["H"]:a["H"] + 16 * BLK_W].view(np.float32).reshape(16, BLK_W)[:, :w] = h.reshape(16, w)
285
  self.dev.sync(self.actbo, True)
286
  hi = self.ins["head"]
287
  self.dev.run(hi[0], hi[1], self.hbo, self.actbo, self.dummy, self.dummy)
 
292
  return lg[:self.cfg["vocab_size"]].copy()
293
 
294
  def bucket(self, T):
295
+ """the attention plan's cache extent for a token at position T (positions 0..T)"""
296
+ if self.pair:
297
+ return min(c for c in self.man["tcaps"] if c > T)
298
  return min(256 * ((T + 256) // 256), self.man["tcap_max"])
299
 
300
+ def kv_at(self, l, T):
301
+ """the cache sub-buffer a plan writes the record(s) of position T on into"""
302
+ if self.pair:
303
+ off = T // 2 * PAIR * 4
304
+ return self.dev.sub(self.kv[l], self.kv_bytes(l) - off, off)
305
+ return self.dev.sub(self.kv[l], 4 * self.hstr * 4 - T * REC * 4, T * REC * 4)
306
+
307
+ def kv_bytes(self, l):
308
+ return ((self.tmax + 1) // 2 + 1) * PAIR * 4
309
+
310
+ def step(self, tok, want_logits=True, emb=None, mpos=None):
311
+ """feed one token at cache slot self.pos; returns the logits (float32 [vocab]) or None. emb: its input row
312
+ instead of the token's embedding (an image row); mpos: its (t, h, w) rotary position (default: slot + rdelta
313
+ on all three)."""
314
  T = self.pos
315
  if T >= self.tmax:
316
  raise RuntimeError(f"context full ({self.tmax} tokens)")
317
  a, am = self.act, self.am
318
+ w = self.hid // 16
319
+ row = self.embed(tok) if emb is None else np.asarray(emb, np.float32)
320
+ am[a["H"]:a["H"] + 16 * BLK_W].view(np.float32).reshape(16, BLK_W)[:, :w] = row.reshape(16, w)
321
  tcap = self.bucket(T)
322
  hd = np.zeros(BLK_W, np.int32)
323
+ if self.man.get("at_split"): # attention header: op, B / C (cache) / F counts
324
+ hd[0], hd[5], hd[6], hd[9] = 3, 10, tcap // 4, 3
325
+ else:
326
+ hd[0], hd[5], hd[9] = 3, 10 + tcap // 2, 3
327
  am[a["AH"]:a["AH"] + 4 * BLK_W] = np.tile(hd, 4)
328
  pb = np.zeros(BLK_W, np.int32)
329
  pb[0] = T
330
+ p = np.full(3, T + self.rdelta) if mpos is None else np.asarray(mpos)
331
+ ang = p[self.axis] * self.inv_freq
332
  pb.view(np.float32)[16:48], pb.view(np.float32)[48:80] = np.cos(ang), np.sin(ang)
333
  am[a["POS"]:a["POS"] + 4 * BLK_W] = np.tile(pb, 4)
334
  self.dev.sync(self.actbo, True)
 
338
  if self.types[l] == "linear_attention":
339
  self.dev.run(dn[0], dn[1], self.wbo[l], self.actbo, self.st[l][0], self.dummy)
340
  else:
341
+ sub = self.kv_at(l, T)
342
  self.dev.run(ins_at[0], ins_at[1], self.wbo[l], self.actbo, self.kv[l], sub)
343
  self.dev.free(sub)
344
  self.pos += 1
 
396
  tcaps = self.man.get("tcaps") # (the plans' cache extents; older programs: the decode buckets)
397
  n_at = self.NT if n > 16 else 16 # (32-token programs: attention plans of 16 and 32 tokens)
398
  tcap = min(c for c in tcaps if c >= T + n_at) if tcaps else b.bucket(T + self.NT - 1)
399
+ assert not b.pair or T % 2 == 0
400
  hd = np.zeros(BLK_W, np.int32)
401
+ pv = np.zeros((self.NT, BLK_W), np.int32) # (the tokens' position blocks)
 
 
402
  for t in range(self.NT):
403
+ pv[t, 0] = T + t
404
+ ang = (T + t + b.rdelta) * b.inv_freq # (rotary position: slot + delta after images)
405
+ pv[t].view(np.float32)[16:48], pv[t].view(np.float32)[48:80] = np.cos(ang), np.sin(ang)
406
+ if self.man.get("at_split"): # (ops of 2 tokens: [header, POS t, POS t + 1] x 4 cores each)
407
+ hd[0], hd[5], hd[6], hd[9] = 3, 17, tcap // 4, 5
408
+ ap = am[a["AP"]:a["AP"] + self.NT // 2 * 12 * BLK_W].reshape(self.NT // 2, 3, 4, BLK_W)
409
+ ap[:, 0] = hd
410
+ ap[:, 1:] = pv.reshape(self.NT // 2, 2, 1, BLK_W)
411
+ else:
412
+ hd[0], hd[5], hd[9] = (3, 19 + tcap // 2, 5) if self.man.get("at2") else (3, 10 + tcap // 2, 3)
413
+ am[a["AH"]:a["AH"] + self.NT * 4 * BLK_W] = np.tile(hd, self.NT * 4)
414
+ am[a["POS"]:a["POS"] + self.NT * 4 * BLK_W].reshape(self.NT, 4, BLK_W)[:] = pv[:, None]
415
  self.dev.sync(self.abo, True)
416
  ins_at = self.ins[f"at{tcap}_{n_at}" if self.NT > 16 else f"at{tcap}"]
417
  for l in range(b.L):
 
419
  ins = self.ins[f"dn{'0' if l == 0 else ''}_{n}"]
420
  self.dev.run(ins[0], ins[1], b.wbo[l], self.abo, b.st[l][0], self.pf[l])
421
  else:
422
+ sub = b.kv_at(l, T)
423
  self.dev.run(ins_at[0], ins_at[1], b.wbo[l], self.abo, b.kv[l], sub)
424
  b.dev.free(sub)
425
  b.pos += n
 
435
  swapping = False
436
  block_gb = None
437
  mtp = None
 
438
  exact_truncate = False
439
 
440
  def __init__(self, d, context=None):
441
+ self.dir = d
442
+ self.rt = Bonsai(d, context)
443
  self.meta = json.load(open(os.path.join(d, "engine.json")))
444
  self.cfg = self.meta["config"]
445
  self.T = min(int(context), self.rt.tmax) if context else self.rt.tmax
 
454
  def cur(self):
455
  return self.rt.pos
456
 
457
+ def embed_rows(self, ids):
458
+ return np.stack([self.rt.embed(int(t)) for t in ids])
459
+
460
  def step(self, ids, embeds=None, pos=None, want_logits=True):
461
+ """ids at the running slot; embeds: their input rows (images); pos: their MRoPE rows [3, k] (a prompt with
462
+ images) - those go token by token; later tokens run at slot + delta (chat sets it after such a prompt)"""
463
  if isinstance(pos, int) and pos != self.rt.pos: # (text positions arrays are always the running ones)
464
  raise RuntimeError(f"step at {pos}: the AMD NPU build continues at {self.rt.pos} only")
465
+ self.rt.rdelta = self.delta
466
+ if embeds is not None or (pos is not None and not isinstance(pos, int)):
467
+ lg = None
468
+ for i, t in enumerate(ids):
469
+ lg = self.rt.step(int(t), want_logits=want_logits and i == len(ids) - 1,
470
+ emb=None if embeds is None else embeds[i],
471
+ mpos=None if pos is None or isinstance(pos, int) else pos[:, i])
472
+ elif len(ids) > 1:
473
  lg = self.rt.prefill([int(t) for t in ids], want_logits=want_logits)
474
  else:
475
  lg = self.rt.step(int(ids[0]), want_logits=want_logits)
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "onwx"
7
- version = "0.1.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.2.0"
8
  description = "LLMs entirely on the AMD Ryzen AI NPU (XDNA2)"
9
  readme = "README.md"
10
  license = {text = "Apache-2.0"}