adriandj3 commited on
Commit
5c251fb
·
verified ·
1 Parent(s): f582158

TernaryPilot v2: card and training kit (weights after training)

Browse files
README.md ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: prism-ml/Ternary-Bonsai-2-9B-gguf
4
+ base_model_relation: adapter
5
+ library_name: gguf
6
+ pipeline_tag: image-text-to-text
7
+ language:
8
+ - en
9
+ datasets:
10
+ - vyokky/GUI-360
11
+ - xlangai/AgentNet
12
+ - osunlp/Multimodal-Mind2Web
13
+ tags:
14
+ - computer-use
15
+ - browser-use
16
+ - gui-agent
17
+ - web-agent
18
+ - gui-grounding
19
+ - screen-understanding
20
+ - visual-grounding
21
+ - agent
22
+ - lora
23
+ - gguf
24
+ - llama.cpp
25
+ - ternary
26
+ - 1.58-bit
27
+ - bonsai
28
+ - qwen3.5
29
+ - screenspot
30
+ - screenspot-pro
31
+ - gui-360
32
+ - windows
33
+ - macos
34
+ - local-ai
35
+ ---
36
+
37
+ <div align="center">
38
+
39
+ # TernaryPilot v2 · computer & browser use for Ternary-Bonsai-2-9B
40
+
41
+ **A LoRA that teaches the 9B ternary Bonsai (2.7 GB) to click, act and read on Windows, macOS and the web.**
42
+ Screenshot in, a point or the next action out. Trained from scratch on 60,516 examples from GUI-360, AgentNet and Mind2Web.
43
+
44
+ [![latest](https://img.shields.io/badge/version-v2_latest-brightgreen)](#)
45
+ [![llama.cpp](https://img.shields.io/badge/llama.cpp-GGUF_F16_LoRA-2b6cb0)](#how-to-use-it)
46
+ [![data](https://img.shields.io/badge/data-60.5k_examples_·_32k_screenshots-6b46c1)](#how-i-trained-it)
47
+ [![trained on](https://img.shields.io/badge/trained_on-RTX_PRO_6000_Blackwell-76b900)](#how-i-trained-it)
48
+ [![GitHub](https://img.shields.io/badge/GitHub-ArtyomITA-181717?logo=github)](https://github.com/ArtyomITA)
49
+
50
+ By **Adrian Ciprian Iancu** · [GitHub](https://github.com/ArtyomITA) · [Hugging Face](https://huggingface.co/adriandj3) · [LinkedIn](https://www.linkedin.com/in/adrian-ciprian-iancu-a2a477391)
51
+
52
+ </div>
53
+
54
+ > **Updated October 2026: this is the current version.** Not a standalone model: it is an adapter for
55
+ > [prism-ml/Ternary-Bonsai-2-9B-gguf](https://huggingface.co/prism-ml/Ternary-Bonsai-2-9B-gguf), loaded at scale 0 and
56
+ > switched on per request, so normal chat stays exactly the base model.
57
+
58
+ ## Pick a file
59
+
60
+ | file | for | size | what it is |
61
+ |---|---|---:|---|
62
+ | `TernaryPilot-v2-Ternary-Bonsai-2-9B-LoRA-F16.gguf` | llama.cpp (PrismML fork) `--lora` | uploading after training | rank 64, alpha 128, F16 |
63
+ | `eval/` | checking my numbers | small | summaries and every answer of the base model and v2 on each benchmark |
64
+ | `training/` | rebuilding it | small | data builder, trainer (Blackwell dense mode), benchmark runner |
65
+
66
+ ## At a glance
67
+
68
+ Every case is asked to the base model (adapter at scale 0) and to v2 on the same llama.cpp server. Greedy decoding,
69
+ images at 1024 tokens, `Ternary-Bonsai-2-9B-PQ2_0-MTP-Q8_0.gguf` with the Q8_0 vision projector.
70
+
71
+ **Benchmarks are running now** (full ScreenSpot-v2, full ScreenSpot-Pro, GUI-360 test grounding and actions, base model against v2 on the same server). This section is filled in as soon as they finish.
72
+
73
+ ## Results
74
+
75
+ **Benchmarks are running now** (full ScreenSpot-v2, full ScreenSpot-Pro, GUI-360 test grounding and actions, base model against v2 on the same server). This section is filled in as soon as they finish.
76
+
77
+ ## How to use it
78
+
79
+ You need the [PrismML fork of llama.cpp](https://github.com/PrismML-Eng/llama.cpp) (ternary kernels), the base model and
80
+ the vision projector from [prism-ml/Ternary-Bonsai-2-9B-gguf](https://huggingface.co/prism-ml/Ternary-Bonsai-2-9B-gguf),
81
+ and the adapter from this repo. I tested `Ternary-Bonsai-2-9B-PQ2_0-MTP-Q8_0.gguf` with
82
+ `Ternary-Bonsai-2-9B-mmproj-Q8_0.gguf`.
83
+
84
+ ```bash
85
+ llama-server -m Ternary-Bonsai-2-9B-PQ2_0-MTP-Q8_0.gguf \
86
+ --mmproj Ternary-Bonsai-2-9B-mmproj-Q8_0.gguf \
87
+ --lora-scaled TernaryPilot-v2-Ternary-Bonsai-2-9B-LoRA-F16.gguf:0 \
88
+ --image-max-tokens 1024 -ngl 999 -fa on --jinja -c 16384 --parallel 2
89
+ ```
90
+
91
+ Turn it on for GUI requests only, with `"lora": [{"id": 0, "scale": 1}]` in the request body, `"temperature": 0` and
92
+ `"chat_template_kwargs": {"enable_thinking": false}`. The scale set by a request stays on its slot, so give GUI requests
93
+ their own slot (`"id_slot": 1`) or send `"scale": 0` on every chat request. On Windows `--lora-scaled` splits on `:`:
94
+ start the server from the adapter's folder and pass the file name only.
95
+
96
+ **Click** (image first, then this text, the target at the end):
97
+
98
+ ```text
99
+ Localize an element on the GUI image according to the provided target and output a click position.
100
+ * You must output a valid JSON following the format: {"x": int, "y": int}, with x and y normalized to 0-1000
101
+ Your target is:
102
+ save the document
103
+ ```
104
+
105
+ **Next action:**
106
+
107
+ ```text
108
+ You are operating a Windows computer.
109
+ Task: Open Notepad and write a shopping list with milk and bread
110
+ Previous actions:
111
+ 1. Click on the Start button
112
+ 2. Type "notepad" in the search box
113
+ Look at the current screen and give the next action. Coordinates are integers normalized to 0-1000.
114
+ Available actions: click(x, y), double_click(x, y), right_click(x, y), move(x, y), drag(x, y), write(text), press(key), hotkey(keys), scroll(amount), wait(), done()
115
+ Reply as:
116
+ Thought: <short reasoning>
117
+ Action: <one action>
118
+ ```
119
+
120
+ Use `You are operating a Mac computer.` or `You are operating a web browser.` as the first line where it fits.
121
+ **Screen reading:** `Describe the current screen: the application or website, its state, and the important visible text.`
122
+ Coordinates are on a 0-1000 grid over the image you send.
123
+
124
+ ## How I trained it
125
+
126
+ - **Model:** Ternary-Bonsai-2-9B rebuilt exactly in PyTorch from the PQ2_0 GGUF (2-bit codes plus the Hadamard rotation of
127
+ the PrismML format), weights frozen, LoRA on the attention, GatedDeltaNet and MLP projections of all 32 layers. Exported
128
+ in the GGUF LoRA format the fork reads with `--lora`.
129
+ - **Run:** rank 64, alpha 128, AdamW lr 1e-4, warmup, constant, final decay over the last 15%, gradient accumulation 8,
130
+ 2.5 hours of training, about a third of the dataset seen once. Fresh start from random LoRA weights.
131
+ - **Speed on one RTX PRO 6000 Blackwell:** frozen ternary weights unpacked once to BF16 (the 1080 kit unpacks them at
132
+ every use), vision encoded on the fly and shared by all examples of the same screenshot, gradient checkpointing only
133
+ above 3,072 tokens. About 0.4 s per example, against 6 to 9 s with the same kit on a GTX 1080.
134
+ - **Data (60,516 examples on 32,001 screenshots, English prompts):**
135
+
136
+ | part | examples | source | license |
137
+ |---|---:|---|---|
138
+ | Office actions with history (Word, Excel, PowerPoint) | 15,000 | [GUI-360](https://huggingface.co/datasets/vyokky/GUI-360), action prediction joined to grounding by screenshot | MIT |
139
+ | Office clicks from the agent's own thought | 15,000 | GUI-360 grounding | MIT |
140
+ | Windows and macOS actions with history | 10,000 | [AgentNet](https://huggingface.co/datasets/xlangai/AgentNet), completed tasks with alignment score 8 or more | MIT |
141
+ | Windows and macOS clicks from the same steps | 4,921 | AgentNet | MIT |
142
+ | Screen reading | 2,426 | AgentNet observations | MIT |
143
+ | Web actions with history | 7,227 | [Multimodal-Mind2Web](https://huggingface.co/datasets/osunlp/Multimodal-Mind2Web) train, page cropped to 1280x800 around the target | OpenRAIL |
144
+ | Web clicks from the same steps | 5,942 | Multimodal-Mind2Web | OpenRAIL |
145
+
146
+ Every training screenshot was compared by perceptual hash (16x16 dHash, Hamming distance 12 or less) with the 2,308
147
+ ScreenSpot-v2 and ScreenSpot-Pro images, and near copies were dropped. GUI-360 test is a separate official split.
148
+
149
+ ## How much to trust this
150
+
151
+ Filled in with the results: sample sizes, what each benchmark measures and where the numbers can mislead.
152
+
153
+ ## Limitations
154
+
155
+ - **No safety layer.** It predicts actions, it does not judge them. Keep a human in the loop for anything that deletes,
156
+ buys or sends.
157
+ - **English prompts.** Screens in other languages work but were not tuned for.
158
+ - **Professional apps are still hard** (ScreenSpot-Pro: high-resolution screens with tiny targets).
159
+ - **Speed:** with the adapter active, decoding is slower than the bare base model; measure it on your card.
160
+ - **Responsible use:** part of the data comes from Multimodal-Mind2Web under an OpenRAIL license; please use the adapter
161
+ in line with its terms.
162
+
163
+ ## License and credits
164
+
165
+ Adapter weights: Apache-2.0. Base model: [prism-ml/Ternary-Bonsai-2-9B-gguf](https://huggingface.co/prism-ml/Ternary-Bonsai-2-9B-gguf)
166
+ (Apache-2.0), from Qwen3.5-9B. Data: GUI-360 (MIT), AgentNet (MIT), Multimodal-Mind2Web (OpenRAIL). Benchmarks:
167
+ ScreenSpot-v2 (OS-Copilot), ScreenSpot-Pro, GUI-360 test. Not affiliated with PrismML or Qwen.
168
+
169
+ ## Citation
170
+
171
+ ```bibtex
172
+ @misc{iancu2026ternarypilot2,
173
+ author = {Iancu, Adrian Ciprian},
174
+ title = {TernaryPilot v2: a computer use and browser use LoRA for Ternary-Bonsai-2-9B},
175
+ year = {2026},
176
+ publisher = {Hugging Face},
177
+ howpublished = {\url{https://huggingface.co/adriandj3/TernaryPilot-v2-Computer-Browser-Use-LoRA}}
178
+ }
179
+ ```
180
+
181
+ Its sibling for decisions: [TernaryDecider v1](https://huggingface.co/adriandj3/TernaryDecider-v1-Decision-LoRA),
182
+ one-token calibrated choices for the same base model. If you try it, open a discussion here or find me on
183
+ [GitHub](https://github.com/ArtyomITA).
184
+
185
+ Keywords: computer use, browser use, GUI agent, web agent, GUI grounding, screen understanding, LoRA, GGUF, llama.cpp,
186
+ ternary, 1.58-bit, Bonsai, Qwen3.5, ScreenSpot, ScreenSpot-Pro, GUI-360, AgentNet, Mind2Web, Windows, macOS, local AI
training/README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training and evaluation kit for TernaryPilot v2
2
+
3
+ By Adrian Ciprian Iancu. These are the exact scripts used for the adapter in this repo.
4
+
5
+ | file | what it does |
6
+ |---|---|
7
+ | `bonsai_hf.py` | rebuilds Ternary-Bonsai-2-9B exactly in PyTorch from the PQ2_0 GGUF (2-bit codes + Hadamard rotation), LoRA on top, GGUF LoRA export |
8
+ | `tern_unpack.py` | unpacks the ternary codes |
9
+ | `bonsai_bw.py` | large-GPU mode: unpack every ternary weight once (BF16 with `BF16=1`), checked against the packed path |
10
+ | `vision_cache.py` | the vision tower and image processor (live encoding, or a cache) |
11
+ | `make_data.py` | v1 data builder (AgentNet, Multimodal-Mind2Web), perceptual-hash exclusion of benchmark images |
12
+ | `make_data_v2.py` | v2 data builder: GUI-360 + AgentNet Windows and macOS + the v1 file, parallel exclusion filter |
13
+ | `train.py` | the trainer: time budget (`HOURS`), WSD schedule, shared image prefix for examples of the same screenshot |
14
+ | `banco_pubblico.py` | ScreenSpot-v2, ScreenSpot-Pro, GUI-360 grounding and actions; base and any number of adapters on one llama.cpp server |
15
+
16
+ Environment: `BONSAI_GGUF` (the PQ2_0 GGUF), `MMPROJ` (BF16 vision projector), `QWEN_SRC` (folder with the Qwen3.5-9B
17
+ config and tokenizer), `GGUF_PY` (the `gguf-py` folder of the PrismML llama.cpp fork).
18
+
19
+ ```bash
20
+ # data
21
+ python make_data.py --mind2web "mind2web/data/train-*.parquet" --images m2w-img --exclude "bench/**/*.png" --out data/m2w.jsonl
22
+ python make_data_v2.py --gui360 GUI-360 --agentnet-jsonl agentnet_win_mac_18k.jsonl --agentnet-images agentnet/imgs \
23
+ --v1-jsonl data/m2w.jsonl --exclude "bench/**/*.png" --out data/train_v2.jsonl --max-gui360 15000 --max-agentnet 10000
24
+ # training (one 96 GB GPU)
25
+ DATA=data/train_v2.jsonl RUN_DIR=run/pilot-v2 HOURS=2.5 RANK=64 ALPHA=128 LR=1e-4 ACCUM=8 \
26
+ DENSE=1 BF16=1 VISION_LIVE=1 EMPTY_CACHE=0 python train.py
27
+ # benchmarks: base, v2 and v1 on one server
28
+ python banco_pubblico.py --server llama-server --model Ternary-Bonsai-2-9B-PQ2_0-MTP-Q8_0.gguf \
29
+ --mmproj Ternary-Bonsai-2-9B-mmproj-Q8_0.gguf --lora v2.gguf v1.gguf --names v2 v1 \
30
+ --bench ss2 --data ScreenSpot-v2 --out banco-ss2.jsonl --parallel 4
31
+ ```
32
+
33
+ The same kit trains on a GTX 1080 (8 GB) without `DENSE`; the 1080 version and its CUDA kernel are in
34
+ [bonsai2-ternary-pascal](https://github.com/ArtyomITA/bonsai2-ternary-pascal).
training/banco_pubblico.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public benchmarks, base model vs one or more LoRAs on the same server: every case is asked once per arm (base = all
2
+ adapters at scale 0, then each adapter alone at scale 1), same image payload, greedy.
3
+ ss2 ScreenSpot-v2 (OS-Copilot/ScreenSpot-v2), 1,272 instructions, hit = point inside the box
4
+ sspro ScreenSpot-Pro (likaixin/ScreenSpot-Pro), 1,581 instructions on professional apps, hit = point inside the box
5
+ g360g GUI-360-Bench grounding (vyokky/GUI-360 test): the agent's thought -> point inside the control rectangle
6
+ g360a GUI-360-Bench action prediction: task + history -> action type right and, for click/type, point inside the rectangle
7
+ Usage:
8
+ python banco_pubblico.py --server llama-server --model M.gguf --mmproj P.gguf --lora v2.gguf v1.gguf --names v2 v1 \
9
+ --bench ss2 --data DIR --out res.jsonl [--limit N] [--parallel 4]
10
+ """
11
+ import argparse
12
+ import base64
13
+ import concurrent.futures as cf
14
+ import glob
15
+ import io
16
+ import json
17
+ import os
18
+ import random
19
+ import re
20
+ import subprocess
21
+ import sys
22
+ import time
23
+ import urllib.request
24
+
25
+ from PIL import Image
26
+
27
+ import make_data as md
28
+
29
+
30
+ def png(im):
31
+ b = io.BytesIO()
32
+ im.save(b, "PNG")
33
+ return {"type": "image_url", "image_url": {"url": "data:image/png;base64," + base64.b64encode(b.getvalue()).decode()}}
34
+
35
+
36
+ def post(port, body, timeout=600):
37
+ r = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", json.dumps(body).encode(),
38
+ {"Content-Type": "application/json"})
39
+ return json.loads(urllib.request.urlopen(r, timeout=timeout).read())
40
+
41
+
42
+ def chiedi(port, img, testo, scale, max_tok): # img: the png() payload, built once per case
43
+ body = {"messages": [{"role": "user", "content": [img, {"type": "text", "text": testo}]}], "temperature": 0,
44
+ "max_tokens": max_tok, "chat_template_kwargs": {"enable_thinking": False},
45
+ "lora": [{"id": i, "scale": s} for i, s in enumerate(scale)]}
46
+ return post(port, body)["choices"][0]["message"].get("content") or ""
47
+
48
+
49
+ def punto(testo): # first x/y pair on the 0-1000 grid
50
+ m = re.search(r'"x"\s*:\s*(-?\d+).*?"y"\s*:\s*(-?\d+)', testo, re.S) or re.search(r"x\s*=\s*(-?\d+)\s*,\s*y\s*=\s*(-?\d+)", testo)
51
+ return (int(m.group(1)), int(m.group(2))) if m else None
52
+
53
+
54
+ def dentro(p, im, box): # p on the 0-1000 grid, box (x1, y1, x2, y2) in pixels of im
55
+ if not p:
56
+ return False
57
+ x, y = p[0] * im.size[0] / 1000, p[1] * im.size[1] / 1000
58
+ return box[0] <= x <= box[2] and box[1] <= y <= box[3]
59
+
60
+
61
+ def casi_ss2(d):
62
+ for f in sorted(glob.glob(f"{d}/screenspot_*_v2.json")):
63
+ for r in json.load(open(f, encoding="utf-8")):
64
+ x, y, w, h = r["bbox"]
65
+ yield {"img": f"{d}/screenspotv2_image/{r['img_filename']}", "testo": md.P_CLIC + r["instruction"], "box": (x, y, x + w, y + h),
66
+ "gruppo": f"{os.path.basename(f).split('_')[1]}-{r['data_type']}", "tipo": "click"}
67
+
68
+
69
+ def casi_sspro(d):
70
+ for f in sorted(glob.glob(f"{d}/annotations/*.json")):
71
+ for r in json.load(open(f, encoding="utf-8")):
72
+ yield {"img": f"{d}/images/{r['img_filename']}", "testo": md.P_CLIC + r["instruction"], "box": tuple(r["bbox"]),
73
+ "gruppo": f"{r['group']}-{r['ui_type']}", "tipo": "click"}
74
+
75
+
76
+ def casi_g360(d, azioni):
77
+ for f in sorted(glob.glob(f"{d}/test/data/*/*/success/*.jsonl")):
78
+ app, cat = f.replace("\\", "/").split("/")[-4:-2]
79
+ storia = []
80
+ for riga in open(f, encoding="utf-8"):
81
+ r = json.loads(riga)
82
+ s, a = r["step"], r["step"]["action"]
83
+ img = f"{d}/test/image/{app}/{cat}/{s['screenshot_clean']}"
84
+ rect = a.get("rectangle") or {}
85
+ box = (rect.get("left"), rect.get("top"), rect.get("right"), rect.get("bottom")) if rect else None
86
+ f_ = a.get("function")
87
+ if a.get("action_type") == "GUI" and box and None not in box and os.path.exists(img):
88
+ if azioni and f_ in ("click", "type", "drag", "wheel_mouse_input"):
89
+ yield {"img": img, "testo": md.p_azione("Windows computer", r["request"], storia), "box": box, "gruppo": f"{app}-{f_}",
90
+ "tipo": "azione", "vero": {"click": "click", "type": "type", "drag": "drag", "wheel_mouse_input": "scroll"}[f_]}
91
+ elif not azioni and "grounding" in (s.get("tags") or []) and s.get("thought"):
92
+ yield {"img": img, "testo": md.P_CLIC + md.frase(s["thought"], 300), "box": box, "gruppo": app, "tipo": "click"}
93
+ storia.append(md.frase(s.get("thought") or "", 160))
94
+
95
+
96
+ def categoria(testo):
97
+ m = re.search(r"Action:\s*(.+)", testo, re.S)
98
+ corpo = m.group(1) if m else testo
99
+ if "write(" in corpo:
100
+ return "type"
101
+ t = re.match(r"\s*(\w+)\(", corpo)
102
+ if not t:
103
+ return None
104
+ n = t.group(1)
105
+ return {"click": "click", "double_click": "click", "right_click": "click", "drag": "drag", "scroll": "scroll",
106
+ "move": "drag" if "drag(" in corpo else "scroll" if "scroll(" in corpo else "move"}.get(n, n)
107
+
108
+
109
+ def valuta(c, testo, im):
110
+ if c["tipo"] == "click":
111
+ return dentro(punto(testo), im, c["box"])
112
+ cat = categoria(testo)
113
+ if cat != c["vero"]:
114
+ return False
115
+ return dentro(punto(testo), im, c["box"]) if cat in ("click", "type") else True
116
+
117
+
118
+ class Server:
119
+ def __init__(self, a):
120
+ self.a, self.p = a, None
121
+
122
+ def __enter__(self):
123
+ a = self.a
124
+ cmd = [a.server, "-m", a.model, "--mmproj", a.mmproj, "--lora-scaled", *[f"{x}:0" for x in a.lora],
125
+ "--image-max-tokens", "1024", "-ngl", "999", "-fa", "on", "--jinja", "-c", str(16384 * a.parallel),
126
+ "--parallel", str(a.parallel), "--port", str(a.port)]
127
+ self.log = open(a.out + ".server.log", "w")
128
+ self.p = subprocess.Popen(cmd, stdout=self.log, stderr=subprocess.STDOUT)
129
+ for _ in range(900):
130
+ try:
131
+ with urllib.request.urlopen(f"http://127.0.0.1:{a.port}/health", timeout=2) as r:
132
+ if r.status == 200:
133
+ return self
134
+ except Exception:
135
+ time.sleep(1)
136
+ if self.p.poll() is not None:
137
+ sys.exit("server exited, see " + self.log.name)
138
+ sys.exit("server not ready")
139
+
140
+ def __exit__(self, *e):
141
+ self.p.terminate()
142
+ self.p.wait(timeout=60)
143
+
144
+
145
+ def main():
146
+ ap = argparse.ArgumentParser()
147
+ for k in ("server", "model", "mmproj", "bench", "data", "out"):
148
+ ap.add_argument("--" + k, required=True)
149
+ ap.add_argument("--lora", nargs="+", required=True), ap.add_argument("--names", nargs="+")
150
+ ap.add_argument("--limit", type=int, default=0), ap.add_argument("--parallel", type=int, default=4)
151
+ ap.add_argument("--port", type=int, default=8791), ap.add_argument("--seed", type=int, default=0)
152
+ a = ap.parse_args()
153
+ casi = list({"ss2": lambda: casi_ss2(a.data), "sspro": lambda: casi_sspro(a.data), "g360g": lambda: casi_g360(a.data, False),
154
+ "g360a": lambda: casi_g360(a.data, True)}[a.bench]())
155
+ if a.limit and len(casi) > a.limit:
156
+ casi = random.Random(a.seed).sample(casi, a.limit)
157
+ max_tok = 64 if a.bench in ("ss2", "sspro", "g360g") else 256
158
+ nomi = a.names or [f"lora{i}" for i in range(len(a.lora))]
159
+ assert len(nomi) == len(a.lora)
160
+ bracci = [("base", [0.0] * len(a.lora))] + [(n, [float(i == j) for j in range(len(a.lora))]) for i, n in enumerate(nomi)]
161
+
162
+ def uno(c):
163
+ im = Image.open(c["img"]).convert("RGB")
164
+ img = png(im)
165
+ r = {"gruppo": c["gruppo"], "img": os.path.basename(c["img"])}
166
+ for nome, scale in bracci:
167
+ t0 = time.time()
168
+ testo = chiedi(a.port, img, c["testo"], scale, max_tok)
169
+ r[nome] = {"ok": valuta(c, testo, im), "s": round(time.time() - t0, 2), "out": testo[-200:]}
170
+ return r
171
+
172
+ tot = {k: 0 for k, _ in bracci}
173
+ per = {}
174
+ with Server(a), cf.ThreadPoolExecutor(a.parallel) as ex, open(a.out, "w", encoding="utf-8") as fo:
175
+ for i, r in enumerate(ex.map(uno, casi)):
176
+ fo.write(json.dumps(r, ensure_ascii=False) + "\n")
177
+ g = per.setdefault(r["gruppo"], {"n": 0, **{k: 0 for k in tot}})
178
+ g["n"] += 1
179
+ for k in tot:
180
+ tot[k] += r[k]["ok"]
181
+ g[k] += r[k]["ok"]
182
+ if (i + 1) % 100 == 0:
183
+ print(f"{i + 1}/{len(casi)} " + " ".join(f"{k} {v}" for k, v in tot.items()), flush=True)
184
+ n = len(casi)
185
+ riass = {"bench": a.bench, "n": n, **tot, **{k + "_pct": round(100 * v / n, 1) for k, v in tot.items()}, "per_gruppo": per}
186
+ print(json.dumps(riass), flush=True)
187
+ json.dump(riass, open(a.out + ".summary.json", "w"), indent=1)
188
+
189
+
190
+ if __name__ == "__main__":
191
+ main()
training/bonsai_bw.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Blackwell mode for bonsai_hf: unpack every ternary weight ONCE (fp32, ~36 GB on a 96 GB card) instead of at each use,
2
+ and let matmuls run in TF32, or with BF16=1 keep the frozen weights in bf16 (LoRA, rotation and loss stay fp32). Same rotation, same LoRA placement, same adapter format as the 1080 kit.
3
+
4
+ import bonsai_hf as B, bonsai_bw
5
+ m, testa, cfg = B.carica(rank=R, alpha=A)
6
+ bonsai_bw.densifica(m, testa)
7
+ """
8
+ import os
9
+
10
+ import torch
11
+
12
+ import bonsai_hf as B
13
+
14
+ torch.backends.cuda.matmul.allow_tf32 = True
15
+ torch.backends.cudnn.allow_tf32 = True
16
+
17
+
18
+ BF16 = os.environ.get("BF16") == "1" # frozen base matmuls in bf16 (386 TFLOPS measured on this card, TF32 201)
19
+
20
+
21
+ def _fwd_lineare(self, x):
22
+ xr = self.ruota(x.float())
23
+ y = (xr.to(self.W.dtype) @ self.W.T).float()
24
+ if self.rank:
25
+ y = y + (x.float() @ self.lora_a.T) @ self.lora_b.T * self.s
26
+ return y
27
+
28
+
29
+ def _fwd_embed(self, ids):
30
+ return self.W[ids].float()
31
+
32
+
33
+ @torch.no_grad()
34
+ def densifica(*moduli):
35
+ n = 0
36
+ for root in moduli:
37
+ for mod in root.modules():
38
+ if isinstance(mod, B.LinearTernario) and not hasattr(mod, "W"):
39
+ W = B.spacchetta(mod.codici, mod.scale)
40
+ mod.register_buffer("W", W.bfloat16() if BF16 else W, persistent=False)
41
+ del W
42
+ mod.forward = _fwd_lineare.__get__(mod)
43
+ del mod.codici, mod.scale
44
+ n += 1
45
+ elif isinstance(mod, B.EmbedTernario) and not hasattr(mod, "W"):
46
+ W = torch.empty(mod.codici.shape[0], mod.codici.shape[1] * 4, device=mod.codici.device)
47
+ for i in range(0, W.shape[0], 16384): # rows already rotated and signed, like EmbedTernario.forward
48
+ z = B.spacchetta(mod.codici[i:i + 16384], mod.scale[i:i + 16384])
49
+ W[i:i + 16384] = B.kron2(z, mod.H) * mod.segni
50
+ mod.register_buffer("W", W, persistent=False)
51
+ mod.forward = _fwd_embed.__get__(mod)
52
+ del mod.codici, mod.scale
53
+ n += 1
54
+ torch.cuda.empty_cache()
55
+ print(f"densified {n} ternary modules, {torch.cuda.memory_allocated() / 2**30:.1f} GiB allocated", flush=True)
56
+
57
+
58
+ if __name__ == "__main__": # self-check: dense output == packed output on a few rows
59
+ m, testa, _ = B.carica(rank=0)
60
+ lin = next(x for x in m.modules() if isinstance(x, B.LinearTernario))
61
+ x = torch.randn(3, lin.in_f, device="cuda")
62
+ torch.backends.cuda.matmul.allow_tf32 = False
63
+ ref = lin(x)
64
+ densifica(lin)
65
+ out = lin(x)
66
+ print("max abs diff fp32 dense vs packed:", float((out - ref).abs().max()))
67
+ assert torch.allclose(out, ref, atol=1e-4, rtol=1e-4)
training/bonsai_hf.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ternary-Bonsai-2-9B (PQ2_0 + Hadamard) rebuilt exactly in PyTorch on top of transformers' Qwen3_5TextModel, to train
2
+ LoRA adapters on a GTX 1080. Ternary weights stay packed on the GPU (2 bit codes + one fp16 scale per 128 weights) and are
3
+ unpacked to fp32 at each use. The input is rotated as in llama.cpp (build_lora_mm): x' = H(s * x), y = W' x'. The LoRA reads
4
+ the input BEFORE the rotation, so the adapter is the same GGUF LoRA the PrismML fork applies with --lora.
5
+ Everything is computed in fp32 (fp16 runs at 1/64 speed on Pascal).
6
+ HF ordering: V rows of qkv/z/a/b, conv1d channels, dt and A are grouped in HF and interleaved in the GGUF (the converter
7
+ interleaves them); ssm_out already has grouped columns in the GGUF, so it needs no permutation.
8
+
9
+ Paths (environment variables):
10
+ BONSAI_GGUF Ternary-Bonsai-2-9B-PQ2_0-MTP-Q8_0.gguf (or PQ2_0) from prism-ml/Ternary-Bonsai-2-9B-gguf
11
+ QWEN_SRC folder with config.json from Qwen/Qwen3.5-9B (same architecture, no weights needed)
12
+ GGUF_PY gguf-py folder of the PrismML llama.cpp fork (it knows the PQ2_0 type)
13
+ """
14
+ import json
15
+ import math
16
+ import os
17
+ import sys
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ sys.path.insert(0, os.environ.get("GGUF_PY", "llama.cpp/gguf-py"))
25
+ import gguf # noqa: E402
26
+ from transformers.models.qwen3_5 import modeling_qwen3_5 as mq # noqa: E402
27
+ from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5Config # noqa: E402
28
+
29
+ GGUF = os.environ.get("BONSAI_GGUF", "Ternary-Bonsai-2-9B-PQ2_0-MTP-Q8_0.gguf")
30
+ CONFIG = os.path.join(os.environ.get("QWEN_SRC", "qwen35-9b"), "config.json")
31
+ MAPPA = {"linear_attn.in_proj_qkv": "attn_qkv", "linear_attn.in_proj_z": "attn_gate", "linear_attn.out_proj": "ssm_out",
32
+ "self_attn.q_proj": "attn_q", "self_attn.k_proj": "attn_k", "self_attn.v_proj": "attn_v", "self_attn.o_proj": "attn_output",
33
+ "mlp.gate_proj": "ffn_gate", "mlp.up_proj": "ffn_up", "mlp.down_proj": "ffn_down"}
34
+
35
+
36
+ def hadamard(n, device):
37
+ i = torch.arange(n, device=device)
38
+ par = torch.zeros(n, n, dtype=torch.int64, device=device)
39
+ x = i[:, None] & i[None, :]
40
+ while bool(x.any()):
41
+ par ^= x & 1
42
+ x = x >> 1
43
+ return (1 - 2 * par).float() / math.sqrt(n)
44
+
45
+
46
+ try: # own CUDA kernel (tern_unpack.py, compiled once): writes W*scale in one pass; without it, plain torch fallback
47
+ import tern_unpack
48
+ _KERNEL = tern_unpack._carica()
49
+ except Exception:
50
+ _KERNEL = None
51
+
52
+
53
+ def spacchetta(codici, scale): # codes (out, in/4) uint8, scales (out, in/128) fp16 -> (out, in) fp32
54
+ if _KERNEL is not None and codici.is_cuda and codici.is_contiguous() and scale.is_contiguous():
55
+ return _KERNEL.unpack(codici, scale, torch.empty(codici.shape[0], codici.shape[1] * 4, device=codici.device))
56
+ # broadcast shift and (q-1)*scale in place on an (out, in/128, 128) view: same values, half the memory traffic
57
+ s = torch.tensor([0, 2, 4, 6], dtype=torch.uint8, device=codici.device)
58
+ w = ((codici.unsqueeze(-1) >> s) & 3).float().view(codici.shape[0], -1, 128)
59
+ return w.sub_(1.0).mul_(scale.float().unsqueeze(-1)).view(codici.shape[0], -1)
60
+
61
+
62
+ def kron2(z, Hs): # z (..., a*a) @ kron(Hs, Hs): Sylvester H4096 = H64 x H64, two 64-wide matmuls instead of one dense 4096
63
+ a = Hs.shape[0]
64
+ t = z.reshape(-1, a) @ Hs # low index
65
+ return torch.matmul(Hs, t.view(-1, a, a)).reshape(z.shape) # high index
66
+
67
+
68
+ class _MatTernaria(torch.autograd.Function): # y = x W^T without saving W: unpacked again in backward
69
+ @staticmethod
70
+ def forward(ctx, x, codici, scale):
71
+ ctx.save_for_backward(codici, scale)
72
+ return x @ spacchetta(codici, scale).T
73
+
74
+ @staticmethod
75
+ def backward(ctx, gy):
76
+ codici, scale = ctx.saved_tensors
77
+ return gy @ spacchetta(codici, scale), None, None
78
+
79
+
80
+ class Ruota(nn.Module):
81
+ def __init__(self, segni, H):
82
+ super().__init__()
83
+ self.register_buffer("segni", segni, persistent=False)
84
+ self.H = H # shared, not registered
85
+
86
+ def forward(self, x):
87
+ # q/k/v, gate/up and qkv/z get the same tensor: rotate once (like the fork's memo)
88
+ if getattr(self, "_x", None) is x and self._g == torch.is_grad_enabled():
89
+ return self._y
90
+ self._x, self._g, self._y = x, torch.is_grad_enabled(), kron2(x * self.segni, self.H)
91
+ return self._y
92
+
93
+
94
+ class LinearTernario(nn.Module):
95
+ def __init__(self, codici, scale, ruota, rank=0, alpha=None):
96
+ super().__init__()
97
+ self.register_buffer("codici", codici, persistent=False)
98
+ self.register_buffer("scale", scale, persistent=False)
99
+ self.ruota = ruota
100
+ self.out_f, self.in_f = codici.shape[0], codici.shape[1] * 4
101
+ self.rank = rank
102
+ if rank:
103
+ self.lora_a = nn.Parameter(torch.randn(rank, self.in_f, device=codici.device) / math.sqrt(self.in_f))
104
+ self.lora_b = nn.Parameter(torch.zeros(self.out_f, rank, device=codici.device))
105
+ self.s = (alpha or rank) / rank
106
+
107
+ def forward(self, x):
108
+ if self.out_f > 65536: # 248k x 4096 output head: unpacked in slices to fit in VRAM
109
+ xr = self.ruota(x.float())
110
+ return torch.cat([_MatTernaria.apply(xr, self.codici[i:i + 16384], self.scale[i:i + 16384])
111
+ for i in range(0, self.out_f, 16384)], -1)
112
+ y = _MatTernaria.apply(self.ruota(x.float()), self.codici, self.scale)
113
+ if self.rank:
114
+ y = y + (x.float() @ self.lora_a.T) @ self.lora_b.T * self.s
115
+ return y
116
+
117
+
118
+ class EmbedTernario(nn.Module): # rotated row: h = s * (H z), like build_embd_rows
119
+ def __init__(self, codici, scale, segni, H):
120
+ super().__init__()
121
+ self.register_buffer("codici", codici, persistent=False)
122
+ self.register_buffer("scale", scale, persistent=False)
123
+ self.register_buffer("segni", segni, persistent=False)
124
+ self.H = H
125
+
126
+ def forward(self, ids):
127
+ z = spacchetta(self.codici[ids.reshape(-1)], self.scale[ids.reshape(-1)])
128
+ h = kron2(z, self.H) * self.segni
129
+ return h.reshape(*ids.shape, -1)
130
+
131
+
132
+ def _gruppi(t, dim, nk, nvpk, hd): # inverse of _reorder_v_heads: interleaved -> grouped
133
+ s = list(t.shape)
134
+ t = t.reshape(*s[:dim], nvpk, nk, hd, *s[dim + 1:])
135
+ p = list(range(t.ndim))
136
+ p[dim], p[dim + 1] = p[dim + 1], p[dim]
137
+ return t.permute(*p).contiguous().reshape(*s)
138
+
139
+
140
+ def carica(device="cuda", rank=0, alpha=None, moduli=tuple(MAPPA), gguf_path=GGUF):
141
+ """Returns (model, output_head, config). Only the LoRA tensors require grad."""
142
+ cfg = Qwen3_5Config(**{k: v for k, v in json.load(open(CONFIG)).items()}).text_config
143
+ cfg._attn_implementation = "sdpa"
144
+ r = gguf.GGUFReader(gguf_path)
145
+ T = {t.name: t for t in r.tensors}
146
+ sv = r.fields["prism.hadamard.sign_values"].contents()
147
+ sw = r.fields["prism.hadamard.sign_widths"].contents()
148
+ segni, o = {}, 0
149
+ for w in sw:
150
+ segni[w] = torch.tensor(sv[o:o + w], dtype=torch.float32, device=device)
151
+ o += w
152
+ H = hadamard(math.isqrt(int(r.fields["prism.hadamard.block_size"].contents())), device) # a x a factor, block_size = a*a
153
+ ruote = {w: Ruota(s, H) for w, s in segni.items()}
154
+ nk, nv, hd = cfg.linear_num_key_heads, cfg.linear_num_value_heads, cfg.linear_value_head_dim
155
+
156
+ def f32(nome):
157
+ t = T[nome]
158
+ return torch.from_numpy(np.array(t.data, dtype=np.float32).reshape([int(x) for x in reversed(t.shape)]))
159
+
160
+ def tern(nome, gruppi_righe=False):
161
+ t = T[nome]
162
+ assert t.tensor_type.name == "PQ2_0", nome
163
+ out, inn = int(t.shape[1]), int(t.shape[0])
164
+ b = np.frombuffer(t.data.tobytes(), dtype=np.uint8).reshape(out, inn // 128, 34)
165
+ sc = torch.from_numpy(b[:, :, :2].copy().view(np.float16).reshape(out, inn // 128))
166
+ cod = torch.from_numpy(b[:, :, 2:].copy().reshape(out, inn // 4))
167
+ if gruppi_righe == "qkv":
168
+ q = 2 * cfg.linear_key_head_dim * nk
169
+ cod = torch.cat([cod[:q], _gruppi(cod[q:], 0, nk, nv // nk, hd)])
170
+ sc = torch.cat([sc[:q], _gruppi(sc[q:], 0, nk, nv // nk, hd)])
171
+ elif gruppi_righe == "z":
172
+ cod, sc = _gruppi(cod, 0, nk, nv // nk, hd), _gruppi(sc, 0, nk, nv // nk, hd)
173
+ return cod.to(device), sc.to(device), inn
174
+
175
+ with torch.device("meta"):
176
+ m = mq.Qwen3_5TextModel(cfg)
177
+ for i, L in enumerate(m.layers):
178
+ for hf, gg in MAPPA.items():
179
+ parent, attr = hf.split(".")
180
+ mod = getattr(L, parent, None)
181
+ if mod is None or not hasattr(mod, attr):
182
+ continue
183
+ cod, sc, inn = tern(f"blk.{i}.{gg}.weight", "qkv" if gg == "attn_qkv" else "z" if gg == "attn_gate" else False)
184
+ setattr(mod, attr, LinearTernario(cod, sc, ruote[inn], rank if hf in moduli else 0, alpha))
185
+ p = f"blk.{i}."
186
+ L.input_layernorm.weight = nn.Parameter(f32(p + "attn_norm.weight").to(device) - 1, requires_grad=False)
187
+ L.post_attention_layernorm.weight = nn.Parameter(f32(p + "post_attention_norm.weight").to(device) - 1, requires_grad=False)
188
+ if hasattr(L, "linear_attn"):
189
+ g = L.linear_attn
190
+ g.A_log = nn.Parameter(torch.log(-_gruppi(f32(p + "ssm_a").reshape(-1, 1), 0, nk, nv // nk, 1).reshape(-1)).to(device), requires_grad=False)
191
+ g.dt_bias = nn.Parameter(_gruppi(f32(p + "ssm_dt.bias").reshape(-1, 1), 0, nk, nv // nk, 1).reshape(-1).to(device), requires_grad=False)
192
+ c = f32(p + "ssm_conv1d.weight") # (channels, 4)
193
+ qk = 2 * cfg.linear_key_head_dim * nk
194
+ c = torch.cat([c[:qk], _gruppi(c[qk:], 0, nk, nv // nk, hd)])
195
+ g.conv1d.weight = nn.Parameter(c.unsqueeze(1).to(device), requires_grad=False)
196
+ for hf, gg in (("in_proj_a", "ssm_alpha"), ("in_proj_b", "ssm_beta")):
197
+ w = _gruppi(f32(p + gg + ".weight"), 0, nk, nv // nk, 1)
198
+ lin = nn.Linear(w.shape[1], w.shape[0], bias=False, device=device)
199
+ lin.weight = nn.Parameter(w.to(device), requires_grad=False)
200
+ setattr(g, hf, lin)
201
+ g.norm.weight = nn.Parameter(f32(p + "ssm_norm.weight").to(device), requires_grad=False)
202
+ else:
203
+ a = L.self_attn
204
+ a.q_norm.weight = nn.Parameter(f32(p + "attn_q_norm.weight").to(device) - 1, requires_grad=False)
205
+ a.k_norm.weight = nn.Parameter(f32(p + "attn_k_norm.weight").to(device) - 1, requires_grad=False)
206
+ m.norm.weight = nn.Parameter(f32("output_norm.weight").to(device) - 1, requires_grad=False)
207
+ cod, sc, inn = tern("token_embd.weight")
208
+ m.embed_tokens = EmbedTernario(cod, sc, segni[inn], H)
209
+ cod, sc, inn = tern("output.weight")
210
+ testa = LinearTernario(cod, sc, ruote[inn])
211
+ m.rotary_emb = mq.Qwen3_5TextRotaryEmbedding(config=cfg, device=device)
212
+ for n, b in list(m.named_buffers()):
213
+ assert b.device.type != "meta", n
214
+ for n, p in m.named_parameters():
215
+ assert p.device.type != "meta", n
216
+ p.requires_grad = "lora_" in n
217
+ return m, testa, cfg
218
+
219
+
220
+ def salva_lora_gguf(m, path, rank, alpha=None): # same format the fork reads with --lora
221
+ w = gguf.GGUFWriter(path, "qwen35")
222
+ w.add_type(gguf.GGUFType.ADAPTER)
223
+ w.add_string(gguf.Keys.Adapter.TYPE, "lora")
224
+ w.add_float32(gguf.Keys.Adapter.LORA_ALPHA, float(alpha or rank))
225
+ for i, L in enumerate(m.layers):
226
+ for hf, gg in MAPPA.items():
227
+ parent, attr = hf.split(".")
228
+ mod = getattr(getattr(L, parent, None), attr, None)
229
+ if not isinstance(mod, LinearTernario) or not mod.rank:
230
+ continue
231
+ a, b = mod.lora_a.detach().float().cpu(), mod.lora_b.detach().float().cpu()
232
+ if gg == "attn_qkv": # V rows interleaved again as in the base GGUF
233
+ q = 2 * 128 * 16
234
+ b = torch.cat([b[:q], _affianca(b[q:])])
235
+ elif gg == "attn_gate":
236
+ b = _affianca(b)
237
+ w.add_tensor(f"blk.{i}.{gg}.weight.lora_a", a.to(torch.float16).numpy())
238
+ w.add_tensor(f"blk.{i}.{gg}.weight.lora_b", b.to(torch.float16).numpy())
239
+ w.write_header_to_file()
240
+ w.write_kv_data_to_file()
241
+ w.write_tensors_to_file()
242
+ w.close()
243
+
244
+
245
+ def _affianca(t, nk=16, nvpk=2, hd=128):
246
+ s = list(t.shape)
247
+ t = t.reshape(nk, nvpk, hd, *s[1:])
248
+ return t.permute(1, 0, 2, *range(3, t.ndim)).contiguous().reshape(s)
249
+
250
+
251
+ # ---- Shared prefix. K targets on the same screenshot = one sequence X = [prefix | suffix 1 | ... | suffix K] (lens = lengths).
252
+ # Projections, norms and MLP run on all tokens together (one weight unpack); causal conv, GDN recurrence and attention run per
253
+ # segment: the prefix alone, every branch with the prefix's state / keys. Same math as Qwen3_5DecoderLayer on each full
254
+ # sequence (different summation order: within tolerance, not bit-exact).
255
+ def _gdn(g, x, lens):
256
+ n, k = x.shape[1], g.conv_kernel_size
257
+ mixed = g.in_proj_qkv(x).transpose(1, 2) # (1, C, T)
258
+ z = g.in_proj_z(x).reshape(1, n, -1, g.head_v_dim)
259
+ beta, a = g.in_proj_b(x).sigmoid(), g.in_proj_a(x)
260
+ seg = mixed.split(lens, -1)
261
+ w, ctx = g.conv1d.weight, seg[0][..., -(k - 1):] # branches see the last k-1 REAL inputs of the prefix, not zeros
262
+ conv = lambda s: F.conv1d(s, w, None, groups=w.shape[0]) # noqa: E731
263
+ mixed = torch.cat([conv(F.pad(seg[0], (k - 1, 0)))] + [conv(torch.cat([ctx, s], -1)) for s in seg[1:]], -1)
264
+ mixed = mq.ACT2FN[g.activation](mixed).transpose(1, 2)
265
+ q, kk, v = torch.split(mixed, [g.key_dim, g.key_dim, g.value_dim], -1)
266
+ q, kk, v = (t.reshape(1, n, -1, d) for t, d in ((q, g.head_k_dim), (kk, g.head_k_dim), (v, g.head_v_dim)))
267
+ rip = g.num_v_heads // g.num_k_heads
268
+ if rip > 1:
269
+ q, kk = q.repeat_interleave(rip, 2), kk.repeat_interleave(rip, 2)
270
+ dec = -g.A_log.float().exp() * F.softplus(a.float() + g.dt_bias)
271
+ out, stato = [], None
272
+ for i, (qi, ki, vi, di, bi) in enumerate(zip(*(t.split(lens, 1) for t in (q, kk, v, dec, beta)))):
273
+ o, s = mq.torch_chunk_gated_delta_rule(qi, ki, vi, g=di, beta=bi, initial_state=stato, output_final_state=i == 0,
274
+ use_qk_l2norm_in_kernel=True)
275
+ out.append(o)
276
+ stato = s if i == 0 else stato # state after the prefix (padding to 64 uses k=v=beta=0, g=0, so it stays unchanged)
277
+ o = g.norm(torch.cat(out, 1).reshape(-1, g.head_v_dim), z.reshape(-1, g.head_v_dim)).reshape(1, n, -1)
278
+ return g.out_proj(o)
279
+
280
+
281
+ def _attn(at, x, cos, sin, lens):
282
+ n = x.shape[1]
283
+ sh = (1, n, -1, at.head_dim)
284
+ q, gate = torch.chunk(at.q_proj(x).view(1, n, -1, at.head_dim * 2), 2, -1)
285
+ q, k = mq.apply_rotary_pos_emb(at.q_norm(q.reshape(sh)).transpose(1, 2), at.k_norm(at.k_proj(x).view(sh)).transpose(1, 2), cos, sin)
286
+ v = at.v_proj(x).view(sh).transpose(1, 2)
287
+ qs, ks, vs = q.split(lens, 2), k.split(lens, 2), v.split(lens, 2)
288
+ f = mq.ALL_ATTENTION_FUNCTIONS.get_interface(at.config._attn_implementation, mq.eager_attention_forward)
289
+ out = [f(at, qs[0], ks[0], vs[0], None, dropout=0.0, scaling=at.scaling)[0]] # prefix: causal
290
+ for qi, ki, vi in zip(qs[1:], ks[1:], vs[1:]): # branch: keys = prefix + own suffix, each query sees the prefix and its past
291
+ kk, vv = torch.cat([ks[0], ki], 2), torch.cat([vs[0], vi], 2)
292
+ mask = torch.ones(qi.shape[2], kk.shape[2], dtype=torch.bool, device=x.device).tril(lens[0])[None, None]
293
+ out.append(f(at, qi, kk, vv, mask, dropout=0.0, scaling=at.scaling)[0])
294
+ return at.o_proj(torch.cat(out, 1).reshape(1, n, -1) * torch.sigmoid(gate.reshape(1, n, -1)))
295
+
296
+
297
+ def strato_ramificato(L, X, cos, sin, lens):
298
+ h = L.input_layernorm(X)
299
+ X = X + (_gdn(L.linear_attn, h, lens) if L.block_type == "linear_attention" else _attn(L.self_attn, h, cos, sin, lens))
300
+ return X + L.mlp(L.post_attention_layernorm(X))
training/make_data.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """make_data.py: builds a train.jsonl for train.py from AgentNet (Windows steps) and Multimodal-Mind2Web (web steps),
2
+ in the format TernaryPilot v1 was trained on. Coordinates are integers on a 0-1000 grid over the image.
3
+
4
+ python make_data.py --agentnet agentnet_win_mac_18k.jsonl --agentnet-images DIR \
5
+ --mind2web "train-*.parquet" --out data/train.jsonl --images out_images/ [--exclude "bench/*.png"]
6
+
7
+ AgentNet (MIT): completed tasks with alignment_score >= 8, Windows only (no macOS words in the first observations), one
8
+ example per step with the history of previous actions as text; plus, on part of the steps, a screen reading example
9
+ (the step's observation) and a click example (the step's target). --agentnet-images is a folder with the extracted PNGs.
10
+ Mind2Web (OpenRAIL): the full-page screenshot is cropped to a 1280x800 window around the target; one action example per
11
+ step plus a click example on the element name. --exclude: images whose perceptual hash is close to any of these files
12
+ are skipped (use it to keep your evaluation screenshots out of training)."""
13
+ import argparse
14
+ import ast
15
+ import glob
16
+ import hashlib
17
+ import io
18
+ import json
19
+ import os
20
+ import random
21
+ import re
22
+
23
+ from PIL import Image
24
+
25
+ P_CLIC = ('Localize an element on the GUI image according to the provided target and output a click position.\n'
26
+ ' * You must output a valid JSON following the format: {"x": int, "y": int}, with x and y normalized to 0-1000\n'
27
+ ' Your target is:\n')
28
+ AZIONI = ("click(x, y), double_click(x, y), right_click(x, y), move(x, y), drag(x, y), write(text), press(key), "
29
+ "hotkey(keys), scroll(amount), wait(), done()")
30
+ P_LETTURA = "Describe the current screen: the application or website, its state, and the important visible text."
31
+
32
+
33
+ def p_azione(dove, compito, storia):
34
+ st = "\n".join(f"{i + 1}. {a}" for i, a in enumerate(storia[-8:])) or "none"
35
+ return (f"You are operating a {dove}.\nTask: {compito}\nPrevious actions:\n{st}\n"
36
+ f"Look at the current screen and give the next action. Coordinates are integers normalized to 0-1000.\n"
37
+ f"Available actions: {AZIONI}\nReply as:\nThought: <short reasoning>\nAction: <one action>")
38
+
39
+
40
+ def md5(path):
41
+ return hashlib.md5(open(path, "rb").read()).hexdigest()[:16]
42
+
43
+
44
+ def dhash(im, n=16):
45
+ g = im.convert("L").resize((n + 1, n))
46
+ px = list(g.getdata())
47
+ return sum(1 << i for i in range(n * n) if px[(i // n) * (n + 1) + i % n] > px[(i // n) * (n + 1) + i % n + 1])
48
+
49
+
50
+ def frase(t, n): # cut at a sentence end within n characters
51
+ t = re.sub(r"\s+", " ", t).strip()
52
+ if len(t) <= n:
53
+ return t
54
+ c = t[:n]
55
+ k = max(c.rfind(". "), c.rfind(".\n"))
56
+ return c[:k + 1] if k > n // 2 else c.rstrip() + "..."
57
+
58
+
59
+ def converti(code):
60
+ """pyautogui / computer.* code with 0-1 coordinates -> actions on the 0-1000 grid; None if not recognised"""
61
+ out = []
62
+ for riga in code.strip().splitlines():
63
+ riga = riga.strip()
64
+ if not riga:
65
+ continue
66
+ try:
67
+ nodo = ast.parse(riga).body[0].value
68
+ nome = nodo.func.attr
69
+ kw = {k.arg: ast.literal_eval(k.value) for k in nodo.keywords}
70
+ args = [ast.literal_eval(a) for a in nodo.args]
71
+ except Exception:
72
+ return None
73
+
74
+ def xy():
75
+ x = kw.get("x", args[0] if args else 0)
76
+ y = kw.get("y", args[1] if len(args) > 1 else 0)
77
+ return "x=%d, y=%d" % (round(x * 1000), round(y * 1000))
78
+
79
+ if nome == "click":
80
+ n, b = kw.get("clicks", 1), kw.get("button", "left")
81
+ out.append(("right_click" if b == "right" else "double_click" if n == 2 else "click") + f"({xy()})")
82
+ elif nome in ("doubleClick", "rightClick", "moveTo", "dragTo", "tripleClick"):
83
+ out.append({"doubleClick": "double_click", "rightClick": "right_click", "moveTo": "move", "dragTo": "drag",
84
+ "tripleClick": "triple_click"}[nome] + f"({xy()})")
85
+ elif nome in ("write", "typewrite"):
86
+ out.append("write(%s)" % json.dumps(kw.get("message", args[0] if args else ""), ensure_ascii=False))
87
+ elif nome == "press":
88
+ k = kw.get("keys", args[0] if args else "")
89
+ out.append("press(%s)" % json.dumps("+".join(k) if isinstance(k, list) else k))
90
+ elif nome == "hotkey":
91
+ k = args[0] if len(args) == 1 else args if args else kw.get("keys", [])
92
+ k = k if isinstance(k, list) else [k]
93
+ if not all(isinstance(x, str) for x in k):
94
+ return None
95
+ out.append("hotkey(%s)" % json.dumps("+".join(k)))
96
+ elif nome in ("scroll", "hscroll"):
97
+ out.append("scroll(%d)" % int(kw.get("clicks", args[0] if args else 0)))
98
+ elif nome == "terminate":
99
+ out.append("done()")
100
+ elif nome == "wait":
101
+ out.append("wait()")
102
+ else:
103
+ return None
104
+ return "\n".join(out) if out else None
105
+
106
+
107
+ def main():
108
+ ap = argparse.ArgumentParser()
109
+ ap.add_argument("--agentnet"), ap.add_argument("--agentnet-images"), ap.add_argument("--mind2web")
110
+ ap.add_argument("--out", required=True), ap.add_argument("--images", required=True), ap.add_argument("--exclude")
111
+ ap.add_argument("--max-agentnet", type=int, default=900), ap.add_argument("--seed", type=int, default=0)
112
+ a = ap.parse_args()
113
+ rnd = random.Random(a.seed)
114
+ os.makedirs(a.images, exist_ok=True)
115
+ vietate = [dhash(Image.open(f)) for f in glob.glob(a.exclude, recursive=True)] if a.exclude else []
116
+ def vietata(im): # one hash per image, compared with every excluded one
117
+ h = dhash(im)
118
+ return any(bin(h ^ v).count("1") <= 12 for v in vietate)
119
+ blocchi = []
120
+
121
+ if a.agentnet:
122
+ mac = re.compile(r"\bmac ?os\b|\bfinder\b|\bdock\b|\bmenu bar\b|\bcommand key|\bcmd\b|safari|spotlight", re.I)
123
+ win = re.compile(r"\bwindows\b|taskbar|start menu|file explorer|\bwps\b|ctrl\+", re.I)
124
+ passi = []
125
+ for riga in open(a.agentnet, encoding="utf-8"):
126
+ d = json.loads(riga)
127
+ if not d.get("task_completed") or (d.get("alignment_score") or 0) < 8:
128
+ continue
129
+ oss = " ".join(s["value"].get("observation", "") for s in d["traj"][:3])
130
+ if mac.search(oss) or not win.search(oss):
131
+ continue
132
+ compito, storia = d.get("natural_language_task") or d["instruction"], []
133
+ for s in d["traj"]:
134
+ v, img = s["value"], os.path.join(a.agentnet_images, s["image"])
135
+ act = converti(v.get("code") or "")
136
+ if act and os.path.exists(img) and v.get("last_step_correct", True) is not False:
137
+ passi.append((img, compito, list(storia), v, act))
138
+ storia.append(frase(v.get("action", ""), 160))
139
+ rnd.shuffle(passi)
140
+ for img, compito, storia, v, act in passi[:a.max_agentnet]:
141
+ if vietata(Image.open(img)):
142
+ continue
143
+ k = md5(img)
144
+ b = [{"cache": k, "img": img, "user": p_azione("Windows computer", compito, storia),
145
+ "risposta": f"Thought: {frase(v.get('action', ''), 220)}\nAction: {act}", "tipo": "action_pc"}]
146
+ if rnd.random() < 0.35 and v.get("observation"):
147
+ b.append({"cache": k, "img": img, "user": P_LETTURA, "risposta": frase(v["observation"], 900), "tipo": "reading"})
148
+ mm = re.fullmatch(r"(?:double_|right_)?click\((x=\d+, y=\d+)\)", act)
149
+ t = re.sub(r"^(double[- ]|right[- ])?click (on |the )*", "", frase(v.get("action", ""), 120), flags=re.I).rstrip(".")
150
+ if mm and 3 <= len(t) <= 100:
151
+ x, y = re.findall(r"\d+", mm.group(1))
152
+ b.append({"cache": k, "img": img, "user": P_CLIC + t, "risposta": '{"x": %s, "y": %s}' % (x, y), "tipo": "click_pc"})
153
+ blocchi.append(b)
154
+
155
+ if a.mind2web:
156
+ import pyarrow.parquet as pq
157
+ for f in sorted(glob.glob(a.mind2web)):
158
+ for batch in pq.ParquetFile(f).iter_batches(batch_size=32):
159
+ for r in batch.to_pylist():
160
+ try:
161
+ pos = json.loads(r["pos_candidates"][0])
162
+ x0, y0, w, h = [float(v) for v in json.loads(pos["attributes"])["bounding_box_rect"].split(",")]
163
+ im = Image.open(io.BytesIO(r["screenshot"]["bytes"])).convert("RGB")
164
+ except Exception:
165
+ continue
166
+ W, H = im.size
167
+ if w <= 0 or h <= 0 or W < 800:
168
+ continue
169
+ top = int(min(max(0, y0 + h / 2 - 400), max(0, H - 800)))
170
+ cr = im.crop((0, top, W, min(H, top + 800)))
171
+ cx, cy = (x0 + w / 2) / W, (y0 + h / 2 - top) / cr.size[1]
172
+ if not (0 < cx < 1 and 0 < cy < 1) or vietata(cr):
173
+ continue
174
+ out = os.path.join(a.images, f"{r['action_uid']}.png")
175
+ cr.save(out)
176
+ k = md5(out)
177
+ px, py = round(cx * 1000), round(cy * 1000)
178
+ opr = json.loads(r["operation"]) if isinstance(r["operation"], str) else r["operation"]
179
+ op, val = opr["op"], opr.get("value", "")
180
+ act = f"click(x={px}, y={py})" + (f"\nwrite({json.dumps(val, ensure_ascii=False)})" if op == "TYPE" else
181
+ f"\nselect({json.dumps(val, ensure_ascii=False)})" if op == "SELECT" else "")
182
+ elem = re.sub(r"^\[\w+\]\s*", "", r["target_action_reprs"].split(" -> ")[0]).strip()
183
+ pensiero = f"The next step is to {op.lower()} the {elem or 'target element'}" + (f" with \"{val}\"" if val else "") + "."
184
+ storia = [s.replace(" -> ", ": ") for s in r["action_reprs"][:int(r["target_action_index"])]]
185
+ b = [{"cache": k, "img": out, "user": p_azione("web browser", r["confirmed_task"], storia),
186
+ "risposta": f"Thought: {pensiero}\nAction: {act}", "tipo": "action_web"}]
187
+ if 5 <= len(elem) <= 80:
188
+ b.append({"cache": k, "img": out, "user": P_CLIC + elem, "risposta": '{"x": %d, "y": %d}' % (px, py), "tipo": "click_web"})
189
+ blocchi.append(b)
190
+
191
+ # order: blocks of the same screenshot stay inside one window of 4 (shared prefix), types are mixed
192
+ rnd.shuffle(blocchi)
193
+ finestre, aperte = [], []
194
+ for b in blocchi:
195
+ for f in aperte:
196
+ if sum(map(len, f)) + len(b) <= 4:
197
+ f.append(b)
198
+ break
199
+ else:
200
+ aperte.append([b])
201
+ for f in [f for f in aperte if sum(map(len, f)) == 4]:
202
+ finestre.append(f)
203
+ aperte.remove(f)
204
+ finestre += aperte
205
+ rnd.shuffle(finestre)
206
+ os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
207
+ with open(a.out, "w", encoding="utf-8") as fo:
208
+ for f in finestre:
209
+ for b in f:
210
+ for e in b:
211
+ fo.write(json.dumps(e, ensure_ascii=False) + "\n")
212
+ print("examples", sum(len(b) for b in blocchi), "screenshots", len(blocchi))
213
+
214
+
215
+ if __name__ == "__main__":
216
+ main()
training/make_data_v2.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """make_data_v2.py: TernaryPilot v2 training data, same format and prompts as v1 (make_data.py), more and different sources:
2
+ - GUI-360 (vyokky/GUI-360, MIT): Word/Excel/PowerPoint on Windows. Grounding (agent thought -> point) and action
3
+ prediction (task + history + screen -> thought + action), joined by screenshot. API actions (19%) are skipped.
4
+ - AgentNet (xlangai/AgentNet, MIT): every completed task with alignment >= 8, Windows AND macOS (v1: Windows, part 1 only).
5
+ - Multimodal-Mind2Web (OpenRAIL) and v1's click pool: through make_data.py (--v1-jsonl merges an existing v1 file).
6
+ Coordinates are integers on a 0-1000 grid over the image, as in v1.
7
+
8
+ python make_data_v2.py --gui360 DIR --agentnet-jsonl F --agentnet-images DIR [--v1-jsonl data/train.jsonl] \
9
+ --out data/train_v2.jsonl --max-gui360 40000 --max-agentnet 20000 [--exclude "bench/**/*.png"]
10
+ """
11
+ import argparse
12
+ import glob
13
+ import json
14
+ import multiprocessing
15
+ import os
16
+ import random
17
+ import re
18
+
19
+ from PIL import Image
20
+
21
+ import make_data as md
22
+
23
+
24
+ _V = [] # dhash of the benchmark images, set before the filtering pool forks
25
+
26
+
27
+ def _hash(path):
28
+ return md.dhash(Image.open(path))
29
+
30
+
31
+ def _libera(path): # the image is not a near copy of any benchmark image
32
+ h = _hash(path)
33
+ return not any(bin(h ^ v).count("1") <= 12 for v in _V)
34
+
35
+
36
+ def filtra(cands, path, max_n, pool):
37
+ """cands already shuffled: the first max_n whose image is free, checked in parallel a slice at a time"""
38
+ out = []
39
+ for i in range(0, len(cands), 2048):
40
+ parte = cands[i:i + 2048]
41
+ out += [c for c, ok in zip(parte, pool.map(_libera, [path(c) for c in parte], chunksize=16)) if ok]
42
+ if len(out) >= max_n:
43
+ break
44
+ return out[:max_n]
45
+
46
+
47
+ def norm(x, y, w, h):
48
+ return round(min(max(x / w, 0), 0.999) * 1000), round(min(max(y / h, 0), 0.999) * 1000)
49
+
50
+
51
+ def gui360_azione(js, w, h):
52
+ """GUI-360 <tool_call>{function, args} -> our action text, or None (API actions and unknown ones are skipped)"""
53
+ f, a = js.get("function"), js.get("args") or {}
54
+ for k in ("coordinate", "start_coordinate", "end_coordinate"): # some steps carry null coordinates: skip them
55
+ c = a.get(k)
56
+ if c is not None and not (isinstance(c, (list, tuple)) and len(c) >= 2
57
+ and all(isinstance(v, (int, float)) for v in c[:2])):
58
+ return None
59
+
60
+ def p(c):
61
+ return "x=%d, y=%d" % norm(c[0], c[1], w, h)
62
+
63
+ if f == "click" and a.get("coordinate"):
64
+ b = a.get("button", "left")
65
+ nome = "right_click" if b == "right" else "double_click" if a.get("double") else "click"
66
+ return f"{nome}({p(a['coordinate'])})"
67
+ if f == "type":
68
+ testo = a.get("text", a.get("keys", ""))
69
+ if not isinstance(testo, str):
70
+ return None
71
+ keys = re.fullmatch(r"\{VK_(\w+)\}(\w)", testo)
72
+ pre = f"click({p(a['coordinate'])})\n" if a.get("coordinate") else ""
73
+ if keys:
74
+ return pre + 'hotkey("%s+%s")' % (keys.group(1).lower().replace("control", "ctrl"), keys.group(2).lower())
75
+ if re.fullmatch(r"\{(ENTER|TAB|ESC|DELETE|BACKSPACE)\}", testo):
76
+ return pre + 'press("%s")' % testo.strip("{}").lower()
77
+ return pre + "write(%s)" % json.dumps(testo, ensure_ascii=False)
78
+ if f == "drag" and a.get("start_coordinate") and a.get("end_coordinate"):
79
+ return f"move({p(a['start_coordinate'])})\ndrag({p(a['end_coordinate'])})"
80
+ if f == "wheel_mouse_input" and a.get("coordinate") is not None:
81
+ return f"move({p(a['coordinate'])})\nscroll({int(a.get('wheel_dist', 0))})"
82
+ return None
83
+
84
+
85
+ def gui360(cartella, rnd, pool, max_n):
86
+ """blocks of examples from processed_data/{grounding_resize, action_prediction_train_resize}"""
87
+ gr = json.load(open(f"{cartella}/processed_data/grounding_resize/training_data.json", encoding="utf-8"))
88
+ ap = json.load(open(f"{cartella}/processed_data/action_prediction_train_resize/training_data.json", encoding="utf-8"))
89
+ pensiero, punto = {}, {}
90
+ for r in gr: # thought -> point, keyed by screenshot
91
+ img = r["images"][0].replace("\\", "/")
92
+ m = re.search(r"The instruction is:\n(.*?)\n\nOutput the coordinate", r["conversation"][0]["value"], re.S)
93
+ c = re.search(r"\[(\d+),\s*(\d+)\]", r["conversation"][1]["value"])
94
+ if m and c:
95
+ pensiero[img] = md.frase(m.group(1), 300)
96
+ punto[img] = (int(c.group(1)), int(c.group(2)))
97
+ traiett = {}
98
+ for r in ap: # group steps by trajectory (id = <...>_<traj>_<step>)
99
+ img = r["images"][0].replace("\\", "/")
100
+ tid, step = r["id"].rsplit("_", 1)
101
+ q = re.search(r"The instruction is:\n(.*?)\n\nThe history", r["conversation"][0]["value"], re.S)
102
+ t = re.search(r"<tool_call>\s*(\{.*\})\s*</tool_call>", r["conversation"][1]["value"], re.S)
103
+ if q and t:
104
+ try:
105
+ traiett.setdefault(tid, []).append((int(step), img, q.group(1).strip(), json.loads(t.group(1))))
106
+ except ValueError:
107
+ pass
108
+ cands = []
109
+ radice = f"{cartella}/processed_data/action_prediction_train_resize"
110
+ gradice = f"{cartella}/processed_data/grounding_resize"
111
+ for tid, passi in traiett.items():
112
+ storia = []
113
+ for step, img, compito, js in sorted(passi):
114
+ path = os.path.join(radice, img)
115
+ if not os.path.exists(path):
116
+ continue
117
+ w, h = Image.open(path).size # header only
118
+ act = gui360_azione(js, w, h)
119
+ th = pensiero.get(img)
120
+ if act:
121
+ if th:
122
+ gp = os.path.join(gradice, img)
123
+ gp = gp if img in punto and os.path.exists(gp) else None
124
+ cands.append((path, compito, list(storia), act, th, gp, punto.get(img)))
125
+ storia.append(md.frase(th or act.splitlines()[0], 160))
126
+ rnd.shuffle(cands)
127
+ print("gui360 candidates", len(cands), flush=True)
128
+ blocchi = []
129
+ for path, compito, storia, act, th, gp, pt in filtra(cands, lambda c: c[0], max_n, pool):
130
+ b = [{"cache": md.md5(path), "img": path, "user": md.p_azione("Windows computer", compito, storia),
131
+ "risposta": f"Thought: {th}\nAction: {act}", "tipo": "action_gui360"}]
132
+ if gp:
133
+ gw, gh = Image.open(gp).size
134
+ x, y = norm(*pt, gw, gh)
135
+ b.append({"cache": md.md5(gp), "img": gp, "user": md.P_CLIC + th, "risposta": '{"x": %d, "y": %d}' % (x, y),
136
+ "tipo": "click_gui360"})
137
+ blocchi.append(b)
138
+ return blocchi
139
+
140
+
141
+ def agentnet(jsonl, cartella, rnd, pool, max_n):
142
+ mac = re.compile(r"\bmac ?os\b|\bfinder\b|\bdock\b|\bmenu bar\b|\bcommand key|\bcmd\b|safari|spotlight", re.I)
143
+ passi = []
144
+ for riga in open(jsonl, encoding="utf-8"):
145
+ d = json.loads(riga)
146
+ if not d.get("task_completed") or (d.get("alignment_score") or 0) < 8:
147
+ continue
148
+ oss = " ".join(s["value"].get("observation", "") for s in d["traj"][:3])
149
+ dove = "Mac computer" if mac.search(oss) else "Windows computer"
150
+ compito, storia = d.get("natural_language_task") or d["instruction"], []
151
+ for s in d["traj"]:
152
+ v, img = s["value"], os.path.join(cartella, s["image"])
153
+ act = md.converti(v.get("code") or "")
154
+ if act and os.path.exists(img) and v.get("last_step_correct", True) is not False:
155
+ passi.append((img, dove, compito, list(storia), v, act))
156
+ storia.append(md.frase(v.get("action", ""), 160))
157
+ rnd.shuffle(passi)
158
+ blocchi = []
159
+ for img, dove, compito, storia, v, act in filtra(passi, lambda p: p[0], max_n, pool):
160
+ k = md.md5(img)
161
+ b = [{"cache": k, "img": img, "user": md.p_azione(dove, compito, storia),
162
+ "risposta": f"Thought: {md.frase(v.get('action', ''), 220)}\nAction: {act}", "tipo": "action_pc"}]
163
+ if rnd.random() < 0.25 and v.get("observation"):
164
+ b.append({"cache": k, "img": img, "user": md.P_LETTURA, "risposta": md.frase(v["observation"], 900), "tipo": "reading"})
165
+ mm = re.fullmatch(r"(?:double_|right_)?click\((x=\d+, y=\d+)\)", act)
166
+ t = re.sub(r"^(double[- ]|right[- ])?click (on |the )*", "", md.frase(v.get("action", ""), 120), flags=re.I).rstrip(".")
167
+ if mm and 3 <= len(t) <= 100:
168
+ x, y = re.findall(r"\d+", mm.group(1))
169
+ b.append({"cache": k, "img": img, "user": md.P_CLIC + t, "risposta": '{"x": %s, "y": %s}' % (x, y), "tipo": "click_pc"})
170
+ blocchi.append(b)
171
+ return blocchi
172
+
173
+
174
+ def v1_blocchi(path): # an existing v1 train.jsonl, regrouped by screenshot
175
+ per = {}
176
+ for riga in open(path, encoding="utf-8"):
177
+ e = json.loads(riga)
178
+ per.setdefault(e["cache"], []).append(e)
179
+ return list(per.values())
180
+
181
+
182
+ def scrivi(blocchi, out, rnd): # same grouping as v1: blocks of one screenshot stay inside one window of 4
183
+ rnd.shuffle(blocchi)
184
+ finestre, aperte = [], []
185
+ for b in blocchi:
186
+ b = b[:4]
187
+ for f in aperte:
188
+ if sum(map(len, f)) + len(b) <= 4:
189
+ f.append(b)
190
+ break
191
+ else:
192
+ aperte.append([b])
193
+ for f in [f for f in aperte if sum(map(len, f)) == 4]:
194
+ finestre.append(f)
195
+ aperte.remove(f)
196
+ finestre += aperte
197
+ rnd.shuffle(finestre)
198
+ os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
199
+ tipi = {}
200
+ with open(out, "w", encoding="utf-8") as fo:
201
+ for f in finestre:
202
+ for b in f:
203
+ for e in b:
204
+ fo.write(json.dumps(e, ensure_ascii=False) + "\n")
205
+ tipi[e["tipo"]] = tipi.get(e["tipo"], 0) + 1
206
+ print("examples", sum(tipi.values()), "screenshots", len(blocchi), tipi)
207
+
208
+
209
+ def main():
210
+ ap = argparse.ArgumentParser()
211
+ ap.add_argument("--gui360"), ap.add_argument("--agentnet-jsonl", nargs="*"), ap.add_argument("--agentnet-images")
212
+ ap.add_argument("--v1-jsonl"), ap.add_argument("--exclude"), ap.add_argument("--out", required=True)
213
+ ap.add_argument("--max-gui360", type=int, default=40000), ap.add_argument("--max-agentnet", type=int, default=20000)
214
+ ap.add_argument("--seed", type=int, default=0)
215
+ a = ap.parse_args()
216
+ rnd = random.Random(a.seed)
217
+ n = max(1, (os.cpu_count() or 2) - 1)
218
+ if a.exclude:
219
+ with multiprocessing.Pool(n) as p:
220
+ _V[:] = p.map(_hash, glob.glob(a.exclude, recursive=True), chunksize=8)
221
+ print("excluded benchmark images", len(_V), flush=True)
222
+ pool = multiprocessing.Pool(n) # forked after _V is set, so the workers see it
223
+ blocchi = []
224
+ if a.gui360:
225
+ g = gui360(a.gui360, rnd, pool, a.max_gui360)
226
+ print("gui360 blocks", len(g), flush=True)
227
+ blocchi += g
228
+ for f in a.agentnet_jsonl or []:
229
+ g = agentnet(f, a.agentnet_images, rnd, pool, a.max_agentnet)
230
+ print("agentnet blocks", f, len(g), flush=True)
231
+ blocchi += g
232
+ if a.v1_jsonl:
233
+ g = v1_blocchi(a.v1_jsonl)
234
+ print("v1 blocks", len(g), flush=True)
235
+ blocchi += g
236
+ pool.close()
237
+ scrivi(blocchi, a.out, rnd)
238
+
239
+
240
+ if __name__ == "__main__":
241
+ main()
training/tern_unpack.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CUDA kernel that unpacks PQ2_0 ternary weights to fp32 in ONE pass (writes W*scale), used by bonsai_hf.spacchetta.
2
+ Same elementwise math as the torch path: (float(q) - 1.0f) * scale_fp32, so the result is bit-identical (building W
3
+ involves no rounding). Layout: uint8 codes [out, in/4] (4 weights per byte, weight k = (byte >> 2k) & 3), fp16 scales
4
+ [out, in/128] (one group = 128 weights = 32 bytes).
5
+ Compiled on first use with torch.utils.cpp_extension (needs nvcc and, on Windows, an MSVC shell). TORCH_CUDA_ARCH_LIST
6
+ defaults to 6.1 (Pascal); set it for other GPUs. Self-check without a GPU: python tern_unpack.py"""
7
+ import os
8
+
9
+ import torch
10
+ from torch.utils.cpp_extension import load_inline
11
+
12
+ _CUDA = r"""
13
+ #include <torch/extension.h>
14
+ #include <ATen/cuda/CUDAContext.h>
15
+ #include <cuda_fp16.h>
16
+ #include <cstdint>
17
+
18
+ __global__ void unpack_pq2(const uint8_t* __restrict__ cod, const __half* __restrict__ sc, float* __restrict__ W,
19
+ long long total_bytes, int in4, int in128) {
20
+ long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; // one thread = one byte = 4 weights
21
+ if (i >= total_bytes) return;
22
+ long long row = i / in4;
23
+ int col4 = (int)(i - row * in4);
24
+ float s = __half2float(sc[row * in128 + (col4 >> 5)]); // 128 weights = 32 bytes per scale
25
+ unsigned b = cod[i];
26
+ float4 o;
27
+ o.x = ((float)( b & 3u) - 1.0f) * s;
28
+ o.y = ((float)((b >> 2) & 3u) - 1.0f) * s;
29
+ o.z = ((float)((b >> 4) & 3u) - 1.0f) * s;
30
+ o.w = ((float)((b >> 6) & 3u) - 1.0f) * s;
31
+ reinterpret_cast<float4*>(W)[i] = o;
32
+ }
33
+
34
+ torch::Tensor unpack(torch::Tensor cod, torch::Tensor sc, torch::Tensor out) {
35
+ TORCH_CHECK(cod.is_cuda() && sc.is_cuda() && out.is_cuda(), "tensors must be on the GPU");
36
+ TORCH_CHECK(cod.scalar_type() == torch::kUInt8 && sc.scalar_type() == torch::kHalf && out.scalar_type() == torch::kFloat32, "dtype");
37
+ TORCH_CHECK(cod.is_contiguous() && sc.is_contiguous() && out.is_contiguous(), "contiguous");
38
+ int64_t rows = cod.size(0), in4 = cod.size(1);
39
+ TORCH_CHECK(out.size(0) == rows && out.size(1) == in4 * 4 && sc.size(0) == rows && sc.size(1) * 32 == in4, "shapes");
40
+ long long total = (long long)rows * in4;
41
+ int threads = 256;
42
+ long long blocks = (total + threads - 1) / threads;
43
+ unpack_pq2<<<(unsigned)blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(
44
+ cod.data_ptr<uint8_t>(), reinterpret_cast<const __half*>(sc.data_ptr<at::Half>()), out.data_ptr<float>(), total, (int)in4, (int)sc.size(1));
45
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
46
+ return out;
47
+ }
48
+ """
49
+ _CPP = "torch::Tensor unpack(torch::Tensor cod, torch::Tensor sc, torch::Tensor out);"
50
+ _mod = None
51
+
52
+
53
+ def _carica():
54
+ global _mod
55
+ if _mod is None:
56
+ os.environ.setdefault("TORCH_CUDA_ARCH_LIST", "6.1")
57
+ _mod = load_inline(name="tern_unpack_pq2", cpp_sources=_CPP, cuda_sources=_CUDA, functions=["unpack"],
58
+ extra_cuda_cflags=["-O3"], verbose=False)
59
+ return _mod
60
+
61
+
62
+ def spacchetta_ref(codici, scale): # reference unpack (the original torch path)
63
+ q = torch.stack([(codici >> s) & 3 for s in (0, 2, 4, 6)], -1).reshape(codici.shape[0], -1)
64
+ return (q.float() - 1.0) * scale.float().repeat_interleave(128, dim=1)
65
+
66
+
67
+ if __name__ == "__main__": # compile, then check the per-thread indexing on CPU against the reference
68
+ _carica()
69
+ print("compiled")
70
+ torch.manual_seed(0)
71
+ out_f, in_f = 6, 512
72
+ cod = (torch.randint(0, 3, (out_f, in_f // 4, 4), dtype=torch.uint8) << torch.tensor([0, 2, 4, 6], dtype=torch.uint8)).sum(-1).to(torch.uint8)
73
+ sc = (torch.randn(out_f, in_f // 128) * 0.05).half()
74
+ ref = spacchetta_ref(cod, sc)
75
+ in4 = in_f // 4
76
+ W = torch.zeros(out_f * in_f)
77
+ for i in range(out_f * in4):
78
+ row, col4 = divmod(i, in4)
79
+ b, s = int(cod[row, col4]), float(sc[row, col4 >> 5].float())
80
+ for k in range(4):
81
+ W[i * 4 + k] = (float((b >> (2 * k)) & 3) - 1.0) * s
82
+ print("thread emulation == reference (bit):", bool(torch.equal(W.reshape(out_f, in_f), ref)))
83
+ if torch.cuda.is_available():
84
+ c, s = cod.cuda(), sc.cuda()
85
+ print("GPU kernel == reference (bit):", bool(torch.equal(_carica().unpack(c, s, torch.empty(out_f, in_f, device="cuda")).cpu(), ref)))
training/train.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """train.py (lora-v2): DENSE=1 and VISION_LIVE=1 for the Blackwell; otherwise identical to the 1080 kit.
2
+ LoRA training for Ternary-Bonsai-2-9B on a small GPU (written and tested on a GTX 1080, 8 GB, fp32).
3
+ This is the trainer that produced TernaryPilot v1. It runs in pieces: start it, stop it, it resumes where it was.
4
+
5
+ Data: one JSON line per example {"cache", "img", "user", "risposta", "tipo"}:
6
+ cache key of the screenshot embedding in CACHE_DIR (make it with vision_cache.py)
7
+ user prompt text (the image always comes first in the user turn)
8
+ risposta target answer (the loss is only on these tokens)
9
+ tipo a label for the per-type loss in the log (e.g. "click", "action_pc")
10
+ Examples of the same screenshot placed next to each other inside one accumulation window (ACCUM=4) share the image
11
+ prefix: it is computed once and every target only pays for its own suffix (3-4x faster with 4 targets per screenshot).
12
+ The file is read in order and restarts at the end, so shuffle and group it when you build it.
13
+
14
+ Usage:
15
+ python train.py train until HOURS of training time (pauses do not count)
16
+ python train.py --export NAME write RUN_DIR/NAME.gguf from the last checkpoint, no training
17
+ Stop: create RUN_DIR/STOP or press Ctrl+C. It saves the checkpoint and exports RUN_DIR/last.gguf.
18
+ Learning rate: warmup, constant, then the last 15% of HOURS decays to 10% (WSD). Before the decay it saves
19
+ RUN_DIR/ckpt-stable.pt: to continue a run with a larger HOURS, start from there with FROM_STABLE=1.
20
+
21
+ Environment: DATA (jsonl), RUN_DIR, HOURS (default 2.5), INIT_ADAPTER (optional .pt from a previous run, same rank),
22
+ plus BONSAI_GGUF, QWEN_SRC, GGUF_PY, CACHE_DIR used by bonsai_hf.py and vision_cache.py.
23
+ """
24
+ import json
25
+ import os
26
+ import sys
27
+ import time
28
+
29
+ import torch
30
+ from transformers import AutoTokenizer
31
+ from transformers.models.qwen3_5 import modeling_qwen3_5 as mq
32
+
33
+ import bonsai_hf as B
34
+ import bonsai_bw
35
+ import vision_cache as VC
36
+
37
+ QUI = os.path.dirname(os.path.abspath(__file__))
38
+ RUN = os.environ.get("RUN_DIR", os.path.join(QUI, "run"))
39
+ DATI = os.environ.get("DATA", os.path.join(QUI, "data", "train.jsonl"))
40
+ DA = os.environ.get("INIT_ADAPTER")
41
+ ORE = float(os.environ.get("HOURS", "2.5"))
42
+ RANK, ALPHA = int(os.environ.get("RANK", "16")), float(os.environ.get("ALPHA", "32"))
43
+ LR, ACCUM, CALDA = float(os.environ.get("LR", "1e-4")), int(os.environ.get("ACCUM", "4")), int(os.environ.get("WARMUP", "20"))
44
+ SALVA_OGNI = int(os.environ.get("SAVE_EVERY", "10"))
45
+ LIVE = os.environ.get("VISION_LIVE") == "1" # encode screenshots on the fly instead of reading CACHE_DIR
46
+ MAX_IMG_TOK = int(os.environ.get("MAX_IMG_TOK", "1024"))
47
+ os.makedirs(RUN, exist_ok=True)
48
+ CKPT, STABILE, STOP = (os.path.join(RUN, f) for f in ("ckpt.pt", "ckpt-stable.pt", "STOP"))
49
+
50
+ tok = AutoTokenizer.from_pretrained(VC.SRC)
51
+ IMG_PAD = tok.convert_tokens_to_ids("<|image_pad|>")
52
+ m, testa, cfg = B.carica(rank=RANK, alpha=ALPHA)
53
+ if os.environ.get("DENSE") == "1":
54
+ bonsai_bw.densifica(m, testa)
55
+ if LIVE:
56
+ from PIL import Image
57
+ TORRE, PROC = VC.torre(), VC.proc(MAX_IMG_TOK)
58
+ _ultima = {}
59
+ params = [p for n, p in m.named_parameters() if p.requires_grad]
60
+ nomi = [n for n, p in m.named_parameters() if p.requires_grad]
61
+
62
+
63
+ def carica_lora(st):
64
+ for n, p in zip(nomi, params):
65
+ p.data.copy_(st[n])
66
+
67
+
68
+ def esporta(nome):
69
+ path = os.path.join(RUN, nome + ".gguf")
70
+ B.salva_lora_gguf(m, path, RANK, ALPHA)
71
+ torch.save({n: p.detach().cpu() for n, p in zip(nomi, params)}, os.path.join(RUN, nome + ".pt"))
72
+ print("exported", path, flush=True)
73
+
74
+
75
+ if "--export" in sys.argv:
76
+ carica_lora(torch.load(CKPT)["lora"])
77
+ esporta(sys.argv[sys.argv.index("--export") + 1])
78
+ sys.exit(0)
79
+
80
+ campioni = [json.loads(x) for x in open(DATI, encoding="utf-8")]
81
+ opt = torch.optim.AdamW(params, lr=LR, weight_decay=0.0)
82
+ stato = {"passo": 0, "i": 0, "secondi": 0.0, "stabile": False}
83
+ sorgente = STABILE if os.environ.get("FROM_STABLE") == "1" else CKPT
84
+ if os.path.exists(sorgente):
85
+ ck = torch.load(sorgente)
86
+ carica_lora(ck["lora"])
87
+ opt.load_state_dict(ck["opt"])
88
+ stato = ck["stato"]
89
+ stato["stabile"] = stato["secondi"] >= 0.85 * ORE * 3600 # a larger HOURS opens the constant phase again
90
+ print(f"resumed from {sorgente}: step {stato['passo']}, {stato['secondi'] / 3600:.2f} h", flush=True)
91
+ elif DA:
92
+ carica_lora(torch.load(DA))
93
+ print("starting from", DA, flush=True)
94
+
95
+
96
+ def fattore():
97
+ caldo = min(1.0, (stato["passo"] + 1) / CALDA)
98
+ f = stato["secondi"] / (ORE * 3600)
99
+ return caldo * (1.0 if f < 0.85 else max(0.1, 1.0 - 0.9 * (f - 0.85) / 0.15))
100
+
101
+
102
+ def salva(path):
103
+ torch.save({"lora": {n: p.detach().cpu() for n, p in zip(nomi, params)}, "opt": opt.state_dict(), "stato": dict(stato)},
104
+ path + ".tmp")
105
+ os.replace(path + ".tmp", path)
106
+
107
+
108
+ m.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
109
+ m.disable_input_require_grads() # transformers forces requires_grad on the embeddings; not needed with non-reentrant checkpointing
110
+ CKPT_TOK = int(os.environ.get("CKPT_TOKENS", "3072")) # checkpoint only longer sequences: 19.6 MiB/token of activations without it
111
+ strati_ckpt = [x for x in m.modules() if hasattr(x, "gradient_checkpointing") and x is not m]
112
+ m.train()
113
+ with torch.device("meta"):
114
+ falso = mq.Qwen3_5Model(mq.Qwen3_5Config(**json.load(open(VC.SRC + "/config.json"))))
115
+
116
+
117
+ def prepara(c): # ids (1, L), embeddings (1, L, D), M-RoPE positions, prompt and answer lengths
118
+ if LIVE:
119
+ if _ultima.get("k") != c["cache"]:
120
+ x = PROC(images=[Image.open(c["img"]).convert("RGB")], return_tensors="pt")
121
+ with torch.no_grad():
122
+ e = TORRE(x["pixel_values"].cuda().float(), grid_thw=x["image_grid_thw"].cuda())
123
+ e = e.pooler_output if hasattr(e, "pooler_output") else e
124
+ _ultima.update(k=c["cache"], emb=e.half().float(), thw=x["image_grid_thw"][0]) # same fp16 rounding as the cache
125
+ emb, thw = _ultima["emb"], _ultima["thw"]
126
+ else:
127
+ d = torch.load(f"{VC.CACHE}/{c['cache']}.pt")
128
+ emb, thw = d["emb"].cuda().float(), d["thw"]
129
+ msg = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": c["user"]}]}]
130
+ pre = tok.apply_chat_template(msg, tokenize=False, add_generation_prompt=True, enable_thinking=False)
131
+ pre = pre.replace("<|image_pad|>", "<|image_pad|>" * emb.shape[0], 1)
132
+ ip = tok(pre, add_special_tokens=False)["input_ids"]
133
+ ir = tok(c["risposta"] + "<|im_end|>", add_special_tokens=False)["input_ids"]
134
+ ids = torch.tensor([ip + ir], device="cuda")
135
+ ic = ids.cpu()
136
+ pos, _ = falso.get_rope_index(ic, (ic == IMG_PAD).int(), image_grid_thw=thw.reshape(1, 3), attention_mask=torch.ones_like(ic))
137
+ e = m.embed_tokens(ids).masked_scatter((ids == IMG_PAD).unsqueeze(-1), emb)
138
+ return ids, e, pos.cuda(), len(ip), len(ir)
139
+
140
+
141
+ def perdita(c):
142
+ ids, e, pos, nip, nir = prepara(c)
143
+ for x in strati_ckpt:
144
+ x.gradient_checkpointing = ids.shape[1] > CKPT_TOK
145
+ h = m(inputs_embeds=e, position_ids=pos, use_cache=False).last_hidden_state[0]
146
+ return torch.nn.functional.cross_entropy(testa(h[nip - 1:nip + nir - 1]).float(), ids[0, nip:])
147
+
148
+
149
+ def perdita_gruppo(gr): # same screenshot: common prefix computed once
150
+ P = [prepara(c) for c in gr]
151
+ lp = min(p[3] for p in P) - 1
152
+ for p in P[1:]:
153
+ d = (p[0][0, :lp] != P[0][0][0, :lp]).nonzero()
154
+ lp = int(d[0]) if len(d) else lp
155
+ assert lp > 0 and all(torch.equal(p[2][..., :lp], P[0][2][..., :lp]) for p in P)
156
+ cs = [m.rotary_emb(p[1], p[2]) for p in P]
157
+ lens = [lp] + [p[0].shape[1] - lp for p in P]
158
+ X = torch.cat([P[0][1][:, :lp]] + [p[1][:, lp:] for p in P], 1)
159
+ cos, sin = (torch.cat([cs[0][j][:, :lp]] + [c[j][:, lp:] for c in cs], 1) for j in (0, 1))
160
+ lungo = X.shape[1] > CKPT_TOK
161
+ for L in m.layers:
162
+ X = (torch.utils.checkpoint.checkpoint(B.strato_ramificato, L, X, cos, sin, lens, use_reentrant=False) if lungo
163
+ else B.strato_ramificato(L, X, cos, sin, lens))
164
+ X, ini, sel = m.norm(X), lp, []
165
+ for p in P:
166
+ sel.append(X[0, ini + p[3] - 1 - lp:ini + p[3] - 1 - lp + p[4]])
167
+ ini += p[0].shape[1] - lp
168
+ logit = testa(torch.cat(sel)).float()
169
+ return [torch.nn.functional.cross_entropy(lg, p[0][0, p[3]:]) for lg, p in zip(logit.split([p[4] for p in P]), P)]
170
+
171
+
172
+ print(f"examples {len(campioni)}, HOURS {ORE}, step {stato['passo']}, rank {RANK}, lr {LR}, accum {ACCUM}", flush=True)
173
+ acc, per_tipo, t_log = [], {}, time.time()
174
+ try:
175
+ while stato["secondi"] < ORE * 3600 and not os.path.exists(STOP):
176
+ t0 = time.time()
177
+ for g in opt.param_groups:
178
+ g["lr"] = LR * fattore()
179
+ opt.zero_grad(set_to_none=True)
180
+ gruppi = []
181
+ for _ in range(ACCUM):
182
+ c = campioni[stato["i"] % len(campioni)]
183
+ stato["i"] += 1
184
+ if gruppi and gruppi[-1][0]["cache"] == c["cache"]:
185
+ gruppi[-1].append(c)
186
+ else:
187
+ gruppi.append([c])
188
+ for gr in gruppi:
189
+ perd = [perdita(gr[0])] if len(gr) == 1 else perdita_gruppo(gr)
190
+ (sum(perd) / ACCUM).backward()
191
+ for c, p in zip(gr, perd):
192
+ acc.append(p.item())
193
+ per_tipo.setdefault(c["tipo"], []).append(p.item())
194
+ torch.nn.utils.clip_grad_norm_(params, 1.0)
195
+ opt.step()
196
+ opt.zero_grad(set_to_none=True)
197
+ if os.environ.get("EMPTY_CACHE", "1") == "1":
198
+ torch.cuda.empty_cache() # needed at 8 GB on Windows; off on the Blackwell
199
+ stato["passo"] += 1
200
+ stato["secondi"] += time.time() - t0
201
+ if not stato["stabile"] and stato["secondi"] >= 0.85 * ORE * 3600:
202
+ salva(STABILE)
203
+ stato["stabile"] = True
204
+ print("saved ckpt-stable (lr decay starts)", flush=True)
205
+ if stato["passo"] % SALVA_OGNI == 0:
206
+ salva(CKPT)
207
+ tipi = " ".join(f"{k}={sum(v) / len(v):.3f}" for k, v in sorted(per_tipo.items()))
208
+ print(f"step {stato['passo']} {stato['secondi'] / 3600:.2f}/{ORE} h loss {sum(acc) / len(acc):.4f} [{tipi}] "
209
+ f"lr {LR * fattore():.2e} {(time.time() - t_log) / len(acc):.1f} s/example epoch "
210
+ f"{stato['i'] / len(campioni):.2f} peak {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB", flush=True)
211
+ acc, per_tipo, t_log = [], {}, time.time()
212
+ except KeyboardInterrupt:
213
+ print("interrupted: saving", flush=True)
214
+ salva(CKPT)
215
+ if os.path.exists(STOP):
216
+ os.remove(STOP)
217
+ esporta("last")
218
+ print(f"stopped at step {stato['passo']}, {stato['secondi'] / 3600:.2f} h of training", flush=True)
training/vision_cache.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Encodes every screenshot once with Bonsai's vision tower (weights from the mmproj GGUF, the same tower llama.cpp runs)
2
+ and saves the embeddings (image tokens x 4096, fp16), so the tower is not on the GPU during training.
3
+ Usage: python vision_cache.py <train.jsonl> [max_image_tokens=1024]
4
+ Paths: MMPROJ (Ternary-Bonsai-2-9B-mmproj-BF16.gguf), QWEN_SRC (config.json + preprocessor_config.json from
5
+ Qwen/Qwen3.5-9B), CACHE_DIR (output folder), GGUF_PY (gguf-py of the PrismML fork)."""
6
+ import json
7
+ import os
8
+ import sys
9
+
10
+ import numpy as np
11
+ import torch
12
+ from PIL import Image
13
+ from transformers import AutoImageProcessor
14
+ from transformers.models.qwen3_5 import modeling_qwen3_5 as mq
15
+
16
+ sys.path.insert(0, os.environ.get("GGUF_PY", "llama.cpp/gguf-py"))
17
+ import gguf # noqa: E402
18
+
19
+ MMPROJ = os.environ.get("MMPROJ", "Ternary-Bonsai-2-9B-mmproj-BF16.gguf")
20
+ SRC = os.environ.get("QWEN_SRC", "qwen35-9b")
21
+ CACHE = os.environ.get("CACHE_DIR", "vision-cache")
22
+
23
+
24
+ def torre(device="cuda"):
25
+ cfg = mq.Qwen3_5Config(**json.load(open(SRC + "/config.json"))).vision_config
26
+ cfg._attn_implementation = "sdpa"
27
+ v = mq.Qwen3_5VisionModel(cfg)
28
+ r = gguf.GGUFReader(MMPROJ)
29
+
30
+ def t(nome):
31
+ x = r.get_tensor([i for i, tt in enumerate(r.tensors) if tt.name == nome][0])
32
+ a = np.array(x.data)
33
+ if x.tensor_type == gguf.GGMLQuantizationType.BF16:
34
+ a = (a.view(np.uint16).astype(np.uint32) << 16).view(np.float32)
35
+ return torch.from_numpy(a.astype(np.float32).reshape([int(s) for s in reversed(x.shape)]))
36
+
37
+ sd = {"patch_embed.proj.weight": torch.stack([t("v.patch_embd.weight"), t("v.patch_embd.weight.1")], 2),
38
+ "patch_embed.proj.bias": t("v.patch_embd.bias"), "pos_embed.weight": t("v.position_embd.weight"),
39
+ "merger.norm.weight": t("v.post_ln.weight"), "merger.norm.bias": t("v.post_ln.bias"),
40
+ "merger.linear_fc1.weight": t("mm.0.weight"), "merger.linear_fc1.bias": t("mm.0.bias"),
41
+ "merger.linear_fc2.weight": t("mm.2.weight"), "merger.linear_fc2.bias": t("mm.2.bias")}
42
+ for i in range(cfg.depth):
43
+ for hf, gg in (("attn.qkv", "attn_qkv"), ("attn.proj", "attn_out"), ("mlp.linear_fc1", "ffn_up"), ("mlp.linear_fc2", "ffn_down"),
44
+ ("norm1", "ln1"), ("norm2", "ln2")):
45
+ for k in ("weight", "bias"):
46
+ sd[f"blocks.{i}.{hf}.{k}"] = t(f"v.blk.{i}.{gg}.{k}")
47
+ mancanti = v.load_state_dict(sd, strict=False)
48
+ assert not mancanti.unexpected_keys, mancanti
49
+ assert all("rotary" in k for k in mancanti.missing_keys), mancanti.missing_keys
50
+ return v.to(device).float().eval()
51
+
52
+
53
+ def proc(max_tok):
54
+ p = AutoImageProcessor.from_pretrained(SRC)
55
+ p.max_pixels = max_tok * 32 * 32
56
+ p.min_pixels = 64 * 32 * 32
57
+ p.size = {"shortest_edge": p.min_pixels, "longest_edge": p.max_pixels}
58
+ return p
59
+
60
+
61
+ if __name__ == "__main__":
62
+ righe = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]
63
+ mt = int(sys.argv[2]) if len(sys.argv) > 2 else 1024
64
+ os.makedirs(CACHE, exist_ok=True)
65
+ v, p = torre(), proc(mt)
66
+ fatti = 0
67
+ for r in {r["cache"]: r for r in righe}.values():
68
+ f = f"{CACHE}/{r['cache']}.pt"
69
+ if os.path.exists(f):
70
+ continue
71
+ x = p(images=[Image.open(r["img"]).convert("RGB")], return_tensors="pt")
72
+ with torch.no_grad():
73
+ e = v(x["pixel_values"].cuda().float(), grid_thw=x["image_grid_thw"].cuda())
74
+ e = e.pooler_output if hasattr(e, "pooler_output") else e
75
+ torch.save({"emb": e.half().cpu(), "thw": x["image_grid_thw"][0]}, f + ".tmp")
76
+ os.replace(f + ".tmp", f)
77
+ fatti += 1
78
+ if fatti % 50 == 0:
79
+ print("encoded", fatti, flush=True)
80
+ print("done", fatti)