Add milo_pointer.py
Browse files- milo_pointer.py +141 -0
milo_pointer.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Milo Pointer: a 149M on-device model that picks the next UI action from an accessibility tree.
|
| 2 |
+
|
| 3 |
+
from milo_pointer import MiloPointer
|
| 4 |
+
m = MiloPointer.load("milo-pointer") # folder with model.safetensors
|
| 5 |
+
a = m.predict(goal="Turn on dark mode", instruction="Open display settings",
|
| 6 |
+
elements=[{"cls": "TextView", "text": "Display", "b": [0, 400, 1080, 520], "click": 1}, ...],
|
| 7 |
+
width=1080, height=2400)
|
| 8 |
+
# {'action_type': 'click', 'element': 3, 'confidence': 0.998, 'defer': False}
|
| 9 |
+
|
| 10 |
+
Elements are dicts with: cls, text, desc, hint, rid (resource id), b = [left, top, right, bottom] in pixels, and 0/1 flags
|
| 11 |
+
click, long, edit, scroll, checked, sel. Only the first 220 elements are read. When `defer` is True the model is unsure
|
| 12 |
+
(confidence below the threshold registered for the AndroidControl router); send the step to a larger model instead.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import re
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
from transformers import AutoModel, AutoTokenizer
|
| 21 |
+
|
| 22 |
+
BASE = "answerdotai/ModernBERT-base"
|
| 23 |
+
TYPES = [
|
| 24 |
+
"click",
|
| 25 |
+
"long_press",
|
| 26 |
+
"input_text",
|
| 27 |
+
"scroll_up",
|
| 28 |
+
"scroll_down",
|
| 29 |
+
"scroll_left",
|
| 30 |
+
"scroll_right",
|
| 31 |
+
"navigate_back",
|
| 32 |
+
"navigate_home",
|
| 33 |
+
"open_app",
|
| 34 |
+
"wait",
|
| 35 |
+
]
|
| 36 |
+
DEFER_BELOW = 0.9854
|
| 37 |
+
MAXLEN = 3072
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _words(rid):
|
| 41 |
+
return " ".join(re.sub(r"([a-z])([A-Z])", r"\1 \2", rid).replace("_", " ").split()).lower()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def el_text(e, W, H): # identical to the training rendering
|
| 45 |
+
g = lambda k: e.get(k) or ""
|
| 46 |
+
main = (g("text") or g("desc") or g("hint"))[:80]
|
| 47 |
+
extra = [_words(g("rid"))] if g("rid") else []
|
| 48 |
+
if g("desc") and g("text"):
|
| 49 |
+
extra.append(g("desc")[:40])
|
| 50 |
+
if g("hint") and (g("text") or g("desc")):
|
| 51 |
+
extra.append("hint " + g("hint")[:30])
|
| 52 |
+
x = (e["b"][0] + e["b"][2]) / 2 / max(W, 1)
|
| 53 |
+
y = (e["b"][1] + e["b"][3]) / 2 / max(H, 1)
|
| 54 |
+
flags = [
|
| 55 |
+
f
|
| 56 |
+
for f, k in (
|
| 57 |
+
("tap", "click"),
|
| 58 |
+
("edit", "edit"),
|
| 59 |
+
("scroll", "scroll"),
|
| 60 |
+
("checked", "checked"),
|
| 61 |
+
("selected", "sel"),
|
| 62 |
+
)
|
| 63 |
+
if e.get(k)
|
| 64 |
+
]
|
| 65 |
+
return f"{g('cls')} {main} | {' | '.join(extra)} @{int(y*10)},{int(x*10)} {' '.join(flags)}"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class _Net(nn.Module):
|
| 69 |
+
def __init__(self, cfg):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.enc = AutoModel.from_config(cfg)
|
| 72 |
+
h = cfg.hidden_size
|
| 73 |
+
self.head_type = nn.Linear(h, len(TYPES))
|
| 74 |
+
self.pt = nn.Linear(h, 1)
|
| 75 |
+
self.se = nn.Linear(h, 2)
|
| 76 |
+
|
| 77 |
+
def forward(self, ids):
|
| 78 |
+
hs = self.enc(input_ids=ids).last_hidden_state[0]
|
| 79 |
+
return self.head_type(hs[0]), self.pt(hs).squeeze(-1), self.se(hs)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class MiloPointer:
|
| 83 |
+
def __init__(self, net, tok, device):
|
| 84 |
+
self.net, self.tok, self.device = net, tok, device
|
| 85 |
+
|
| 86 |
+
@classmethod
|
| 87 |
+
def load(cls, path, device=None):
|
| 88 |
+
from safetensors.torch import load_file
|
| 89 |
+
from transformers import AutoConfig
|
| 90 |
+
|
| 91 |
+
device = device or (
|
| 92 |
+
"cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 93 |
+
)
|
| 94 |
+
p = Path(path)
|
| 95 |
+
tok = AutoTokenizer.from_pretrained(p if (p / "tokenizer.json").exists() else BASE)
|
| 96 |
+
cfg = AutoConfig.from_pretrained(p if (p / "config.json").exists() else BASE)
|
| 97 |
+
net = _Net(cfg)
|
| 98 |
+
net.load_state_dict(
|
| 99 |
+
{k: v.float() for k, v in load_file(str(p / "model.safetensors")).items()}, strict=False
|
| 100 |
+
)
|
| 101 |
+
net = net.to(device).eval()
|
| 102 |
+
if device != "cpu":
|
| 103 |
+
net = net.half()
|
| 104 |
+
return cls(net, tok, device)
|
| 105 |
+
|
| 106 |
+
@torch.no_grad()
|
| 107 |
+
def predict(self, goal, instruction, elements, width, height, last_step="new step"):
|
| 108 |
+
tok = self.tok
|
| 109 |
+
prefix = f"{instruction} || {last_step} || goal: {goal}"
|
| 110 |
+
p = tok(prefix, add_special_tokens=False, return_offsets_mapping=True)
|
| 111 |
+
ids = [tok.cls_token_id] + p["input_ids"] + [tok.sep_token_id]
|
| 112 |
+
offs = [(0, 0)] + p["offset_mapping"] + [(0, 0)]
|
| 113 |
+
marks, kept = [], []
|
| 114 |
+
for k, e in enumerate(elements[:220]):
|
| 115 |
+
t = tok(el_text(e, width, height), add_special_tokens=False)["input_ids"][:28]
|
| 116 |
+
if len(ids) + len(t) + 2 > MAXLEN:
|
| 117 |
+
break
|
| 118 |
+
marks.append(len(ids))
|
| 119 |
+
ids += [tok.mask_token_id] + t
|
| 120 |
+
kept.append(k)
|
| 121 |
+
ids.append(tok.sep_token_id)
|
| 122 |
+
lt, lp, lse = (x.float() for x in self.net(torch.tensor([ids], device=self.device)))
|
| 123 |
+
pt = torch.softmax(lt, -1)
|
| 124 |
+
conf = float(pt.max())
|
| 125 |
+
ty = TYPES[int(pt.argmax())]
|
| 126 |
+
out = {"action_type": ty}
|
| 127 |
+
if ty in ("click", "long_press") and marks:
|
| 128 |
+
sm = torch.softmax(lp[marks], -1)
|
| 129 |
+
j = int(sm.argmax())
|
| 130 |
+
conf *= float(sm[j])
|
| 131 |
+
k = kept[j]
|
| 132 |
+
eb = elements[k]["b"]
|
| 133 |
+
out.update(element=k, x=(eb[0] + eb[2]) // 2, y=(eb[1] + eb[3]) // 2)
|
| 134 |
+
elif ty in ("input_text", "open_app"):
|
| 135 |
+
n = len(offs)
|
| 136 |
+
s = int(lse[:n, 0].argmax())
|
| 137 |
+
e = int(lse[s:n, 1].argmax()) + s
|
| 138 |
+
out["text" if ty == "input_text" else "app_name"] = prefix[offs[s][0] : offs[e][1]]
|
| 139 |
+
out["confidence"] = round(conf, 4)
|
| 140 |
+
out["defer"] = conf < DEFER_BELOW
|
| 141 |
+
return out
|