File size: 6,769 Bytes
0cc835c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""Compare the app's phrase lookup with trained gesture models on data/{val,test,test_real,hard}.jsonl.

python evaluate.py lookup:<sentence-transformers repo>   (the app's current method)
python evaluate.py torch:<trained repo or dir>
python evaluate.py onnx:<dir with model.onnx + gesture_heads.npz>

The threshold is chosen on val, then applied unchanged to the test sets ("@val"); "@best" picks it per set (optimistic).
"""

import os
import re
import sys
import json
from pathlib import Path

import numpy as np

DATA = Path(os.environ.get("DATA", Path(__file__).parent / "data"))
SENTENCE = re.compile(r"(?<=[.!?…])\s+|(?<=[。!?])")
SETS = ["val", "test", "test_real", "hard"]


def load(name: str) -> list[dict]:
    path = DATA / f"{name}.jsonl"
    return [json.loads(line) for line in path.open()] if path.exists() else []


POSITIVE = {"success1", "success2", "laughing2", "grateful1", "loving1", "amazed1", "surprised1", "welcoming2", "helpful1", "relief1", "yes1", "understanding2"}
NEGATIVE = {"downcast1", "fear1", "disgusted1", "irritated1", "rage1", "resigned1", "no1"}


def valence(move: str) -> str:
    return "+" if move in POSITIVE else "-" if move in NEGATIVE else "0"


def score(rows: list[dict], preds: list[tuple[str, float]], threshold: float) -> dict:
    right = wrong = missed = severe = 0
    for row, (move, prob) in zip(rows, preds):
        got = move if move != "none" and prob >= threshold else "none"
        right += got in row["ok"]
        wrong += got not in row["ok"] and got != "none"
        missed += got not in row["ok"] and got == "none"
        # severe: a gesture of the opposite feeling to every acceptable one (happy for angry, sad for good news)
        wanted = {valence(m) for m in row["ok"] if m != "none"}
        opposite = {"+": "-", "-": "+"}.get(valence(got))
        severe += got not in row["ok"] and opposite in wanted and valence(got) not in wanted
    return {"acc": round(right / max(1, len(rows)), 3), "wrong": wrong, "missed": missed, "severe": severe}


def lookup_predictor(repo: str):
    from sentence_transformers import SentenceTransformer

    model = SentenceTransformer(repo)
    phrases = json.loads((Path(__file__).parent / "gesture_phrases.json").read_text())
    index = {}
    for kind in ("say", "react"):
        texts = [p for e in phrases for p in e[kind]]
        moves = [e["move"] or "none" for e in phrases for _ in e[kind]]
        index[kind] = (model.encode(texts, normalize_embeddings=True), moves)

    def predict(rows: list[dict]) -> list[tuple[str, float]]:
        out = []
        for row in rows:
            vectors, moves = index[row["kind"]]
            sentences = [s for s in SENTENCE.split(row["text"]) if s.strip()] or [row["text"]]
            sims = model.encode(sentences, normalize_embeddings=True) @ vectors.T
            best = ("none", 0.0)
            for s in sims:
                i = int(s.argmax())
                if moves[i] != "none" and s[i] > best[1]:
                    best = (moves[i], float(s[i]))
            out.append(best)
        return out

    return predict


def head_predictor(kind_of_model: str, path: str):
    from huggingface_hub import snapshot_download

    local = Path(path) if Path(path).exists() else Path(snapshot_download(path))
    heads = np.load(local / "gesture_heads.npz")
    labels = json.loads((local / "gesture_labels.json").read_text())
    prefix = json.loads((local / "training.json").read_text())["args"].get("prefix", "")
    from transformers import AutoTokenizer

    tokenizer = AutoTokenizer.from_pretrained(local)
    if kind_of_model == "torch":
        import torch
        from transformers import AutoModel

        model = AutoModel.from_pretrained(local).eval()

        def hidden(batch):
            with torch.no_grad():
                return model(**{k: torch.tensor(v) for k, v in batch.items()}).last_hidden_state.numpy()
    else:
        import onnxruntime as ort

        options = ort.SessionOptions()
        options.intra_op_num_threads = 2
        session = ort.InferenceSession(str(local / sys.argv[2] if len(sys.argv) > 2 else local / "model.onnx"), options, providers=["CPUExecutionProvider"])
        inputs = {i.name for i in session.get_inputs()}

        def hidden(batch):
            feed = {k: v for k, v in batch.items() if k in inputs}
            if "token_type_ids" in inputs and "token_type_ids" not in feed:
                feed["token_type_ids"] = np.zeros_like(batch["input_ids"])
            return session.run(None, feed)[0]

    def predict(rows: list[dict]) -> list[tuple[str, float]]:
        out = []
        for start in range(0, len(rows), 64):
            chunk = rows[start : start + 64]
            batch = tokenizer([prefix + r["text"] for r in chunk], padding=True, truncation=True, max_length=64, return_tensors="np")
            batch = {k: v.astype(np.int64) for k, v in batch.items()}
            h = hidden(batch)
            mask = batch["attention_mask"][..., None]
            pooled = (h * mask).sum(1) / mask.sum(1)
            pooled = pooled / np.linalg.norm(pooled, axis=1, keepdims=True) * 10.0
            for r, v in zip(chunk, pooled):
                logits = heads[f"{r['kind']}_weight"] @ v + heads[f"{r['kind']}_bias"]
                p = np.exp(logits - logits.max())
                p /= p.sum()
                j = int(p.argmax())
                out.append((labels[r["kind"]][j], float(p[j])))
        return out

    return predict


spec = sys.argv[1]
method, _, target = spec.partition(":")
predict = lookup_predictor(target) if method == "lookup" else head_predictor(method, target)
thresholds = [t / 100 for t in range(0, 100, 5)]
results, preds = {}, {}
for name in SETS:
    rows = load(name)
    if rows:
        preds[name] = (rows, predict(rows))
val_rows, val_preds = preds["val"]
val_thr = max(thresholds, key=lambda t: (score(val_rows, val_preds, t)["acc"], -score(val_rows, val_preds, t)["wrong"]))
if os.environ.get("THREE_WAY"):  # also score on test rows where Kimi-K3's best is acceptable too
    for name in ("test", "test_real"):
        kimi = {(r["kind"], r["text"]): r for r in map(json.loads, open(Path(__file__).parent / f"lab_{name}_kimi.jsonl"))}
        rows, p = preds[name]
        keep = [i for i, r in enumerate(rows) if kimi[(r["kind"], r["text"])]["best"] in r["ok"]]
        preds[name + "_3way"] = ([rows[i] for i in keep], [p[i] for i in keep])
for name, (rows, p) in preds.items():
    best_thr = max(thresholds, key=lambda t: (score(rows, p, t)["acc"], -score(rows, p, t)["wrong"]))
    results[name] = {"n": len(rows), "@val": score(rows, p, val_thr), "@best": score(rows, p, best_thr) | {"thr": best_thr}}
print(json.dumps({"model": spec, "val_thr": val_thr, **results}))