Repository navigation
Expand file tree
/
Copy pathcommon.py
More file actions
114 lines (102 loc) · 5.44 KB
/
Copy pathcommon.py
File metadata and controls
114 lines (102 loc) · 5.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import base64
import io
import json
import mimetypes
from pathlib import Path
import numpy as np
import requests
from PIL import Image
from model import Ensemble
def image_data_url(path, max_pixels=1_310_720):
path = Path(path)
with Image.open(path) as source:
if source.width * source.height <= max_pixels:
payload = path.read_bytes()
mime = mimetypes.guess_type(path.name)[0] or "image/png"
else:
ratio = (max_pixels / (source.width * source.height)) ** 0.5
size = max(1, int(source.width * ratio)), max(1, int(source.height * ratio))
buffer = io.BytesIO()
source.convert("RGB").resize(size, Image.Resampling.LANCZOS).save(
buffer, format="PNG", optimize=True)
payload, mime = buffer.getvalue(), "image/png"
return f"data:{mime};base64," + base64.b64encode(payload).decode("ascii")
def post_chat_completion(server_url, payload, timeout_seconds=900):
response = requests.post(server_url.rstrip("/") + "/v1/chat/completions",
json=payload, timeout=timeout_seconds)
response.raise_for_status()
return response.json()
def read_jsonl(path):
with Path(path).open(encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def run_offline(args, benchmark, build_messages, parse_response, score_action,
schema=None):
rows = read_jsonl(args.samples)
if not rows:
raise ValueError("evaluation samples are empty")
with np.load(args.features, allow_pickle=False) as data:
ids = data["sample_ids"].astype(str).tolist()
if len(ids) != len(set(ids)):
raise ValueError("duplicate feature IDs")
by_id = {value: i for i, value in enumerate(ids)}
query_ids = [str(row["query_id"]) for row in rows]
if len(query_ids) != len(set(query_ids)) or set(query_ids) != set(ids):
raise ValueError("sample/feature IDs do not match")
order = np.asarray([by_id[value] for value in query_ids], int)
state = np.asarray(data["state"][order], np.float32)
memories = np.asarray(data["memories"][order], np.float32)
router = Ensemble(args.router, args.device)
selected, scores = router.select(state, memories)
bank = read_jsonl(args.bank) if benchmark == "aitw" else None
args.output.parent.mkdir(parents=True, exist_ok=True)
values = []
with args.output.open("w", encoding="utf-8") as handle:
for index, row in enumerate(rows):
condition = "image_step" if selected[index] else "text_step"
if benchmark == "aitw":
memory = bank[int(row["text_step_index"])]
if memory.get("task_id") == row.get("task_id") and row.get("task_id") is not None:
raise ValueError("memory and query belong to the same trajectory")
prompt = build_messages(row, memory, condition)
else:
# Freeze the text-retrieved memory ID for both presentations.
row = dict(row, image_memory=row["text_memory"],
image_memory_id=row["text_memory_id"])
query_trajectory = row.get("trajectory_id")
memory_trajectory = row["text_memory"].get("trajectory_id")
if query_trajectory is not None and query_trajectory == memory_trajectory:
raise ValueError("memory and query belong to the same trajectory")
if row.get("support_trajectory_id") is not None and memory_trajectory != row["support_trajectory_id"]:
raise ValueError("memory is outside the designated support trajectory")
prompt = build_messages(row, condition)
payload = {"model": args.model, "messages": prompt, "temperature": 0,
"seed": 42, "max_tokens": 128,
"chat_template_kwargs": {"enable_thinking": False}}
if schema is not None:
payload["response_format"] = {"type": "json_schema", "json_schema": {
"name": "single_android_action", "strict": True, "schema": schema}}
result = post_chat_completion(args.actor_url, payload)
try:
action = parse_response(result["choices"][0]["message"]["content"])
except (ValueError, TypeError, KeyError):
action = None
value = float(score_action(row, action))
values.append(value)
handle.write(json.dumps({"query_id": row["query_id"],
"selected": condition, "router_score": float(scores[index]),
"predicted_action": action, "action_score": value}, ensure_ascii=False) + "\n")
print(json.dumps({"benchmark": benchmark, "steps": len(values),
"action_score": float(np.mean(values))}))
def offline_parser(description, needs_bank=False):
import argparse
parser = argparse.ArgumentParser(description=description)
parser.add_argument("--samples", type=Path, required=True)
parser.add_argument("--features", type=Path, required=True)
parser.add_argument("--router", type=Path, required=True)
parser.add_argument("--actor-url", required=True)
parser.add_argument("--model", default="Qwen3.5-9B")
parser.add_argument("--device", default="cpu")
parser.add_argument("--output", type=Path, required=True)
if needs_bank:
parser.add_argument("--bank", type=Path, required=True)
return parser