File size: 9,929 Bytes
0c64c71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
"""Construct routing states and candidate outcome rows from dataset/responses.parquet.

States per query q (20 models):
  k=0 : 1 query-only state                                   (candidates: all 20 models, Q_best = 0 baseline = "no response yet")
  k=1 : 20 one-model states (complete)                       (candidates: the other 19 -> full one-model candidate matrix, nothing downsampled)
  k=2 : 12 sampled ordered pairs   (8 uniform random, 2 'weak' pairs = two lowest-Q models, 2 'contains-best' pairs)
  k=3 :  6 sampled ordered triples (4 uniform random, 1 weak, 1 contains-best)
`sample_stratum` records how each sampled state was drawn so analyses can restrict to the unbiased 'random' stratum.
Router-visible columns are prefixed feat_ and are computed ONLY from the called models' responses (generation-time signals, no quality, no candidate information).
Label columns are prefixed label_ (offline outcomes).
Outputs: dataset/states.parquet, dataset/candidates.parquet, dataset/response_features.parquet, dataset/state_build_manifest.json
Usage: python build_states.py [--limit-queries N]
"""
import argparse
import hashlib
import json
import re
import sys
from multiprocessing import get_context
from pathlib import Path

import numpy as np
import pandas as pd

ROOT = Path("/mnt/localssd/seqroute1m")
LAMBDAS = [0.0, 0.1, 0.25, 0.5, 1.0, 2.0]
SEED = 20261010
D = {}


def final_text(t, reasoning):
    t = t or ""
    if "</think>" in t:
        return t.rsplit("</think>", 1)[1].strip()
    return t.strip()


def toks(s):
    return set(re.findall(r"\w+", s.lower())[:300])


def norm_ans(a):
    return None if a is None or (isinstance(a, float) and np.isnan(a)) else re.sub(r"\s+", " ", str(a).strip().lower())


def init(path, models):
    d = pd.read_parquet(path)
    D["models"] = models
    D["m2i"] = {m: i for i, m in enumerate(models)}
    D["g"] = {q: g for q, g in d.groupby("query_id", sort=False)}


def per_query(qid):
    models, m2i = D["models"], D["m2i"]
    n = len(models)
    g = D["g"][qid].set_index("model_id")
    g = g.reindex(models)
    Q = g.Q.to_numpy(float)
    cn = g.cost_norm.to_numpy(float)
    gs = g.gpu_seconds.to_numpy(float)
    ctok = g.completion_tokens.to_numpy(float)
    lc = g.label_confidence.to_numpy(float)
    fam = g.task_family.iloc[0]
    src = g.source_dataset.iloc[0]
    split = g.split.iloc[0]
    # response-visible features
    f_logtok = np.log1p(ctok)
    f_meanlp, f_p05, f_frac2 = g.mean_lp.to_numpy(float), g.p05_lp.to_numpy(float), g.frac_lp_lt_2.to_numpy(float)
    f_ent = g.mean_entropy_top5.to_numpy(float)
    f_trunc = (g.finish_reason.to_numpy() == "length").astype(float)
    f_parse = g.parse_ok.astype(float).to_numpy()
    ans = [norm_ans(a) for a in g.answer_extracted]
    ts = [toks(final_text(t, None)) for t in g.text]
    rng = np.random.default_rng(int(hashlib.sha1(f"{SEED}|{qid}".encode()).hexdigest()[:8], 16))

    def jac(i, j):
        a, b = ts[i], ts[j]
        return len(a & b) / max(len(a | b), 1)

    def feats(called):
        k = len(called)
        if k == 0:
            return dict(feat_n_called=0)
        c = list(called)
        out = dict(feat_n_called=k, feat_last_model=models[c[-1]], feat_mean_log_tokens=float(np.mean(f_logtok[c])), feat_max_log_tokens=float(np.max(f_logtok[c])),
                   feat_mean_lp=float(np.nanmean(f_meanlp[c])) if not np.all(np.isnan(f_meanlp[c])) else np.nan, feat_min_p05_lp=float(np.nanmin(f_p05[c])) if not np.all(np.isnan(f_p05[c])) else np.nan,
                   feat_mean_frac_lp_lt2=float(np.nanmean(f_frac2[c])) if not np.all(np.isnan(f_frac2[c])) else np.nan, feat_mean_entropy=float(np.nanmean(f_ent[c])) if not np.all(np.isnan(f_ent[c])) else np.nan,
                   feat_any_truncated=float(f_trunc[c].max()), feat_frac_parse_ok=float(np.mean(f_parse[c])), feat_spent_cost_norm=float(np.sum(cn[c])), feat_spent_gpu_s=float(np.sum(gs[c])),
                   feat_last_mean_lp=float(f_meanlp[c[-1]]), feat_last_log_tokens=float(f_logtok[c[-1]]), feat_last_truncated=float(f_trunc[c[-1]]), feat_last_parse_ok=float(f_parse[c[-1]]))
        if k >= 2:
            av = [ans[i] for i in c if ans[i] is not None]
            out["feat_n_distinct_answers"] = float(len(set(av))) if len(av) >= 2 else np.nan
            out["feat_answer_agreement"] = float(max(av.count(x) for x in set(av)) / len(av)) if len(av) >= 2 else np.nan
            js = [jac(a, b) for ai, a in enumerate(c) for b in c[ai + 1:]]
            out["feat_text_jaccard_mean"], out["feat_text_jaccard_max"] = float(np.mean(js)), float(np.max(js))
        return out

    order_best = np.argsort(-Q, kind="stable")
    order_weak = np.argsort(Q, kind="stable")
    states = [((), "all")]
    states += [((i,), "all") for i in range(n)]
    seen = set()

    def add_state(t, stratum):
        if t not in seen:
            seen.add(t); states.append((t, stratum))
    allp = [(i, j) for i in range(n) for j in range(n) if i != j]
    for idx in rng.permutation(len(allp))[:8]:
        add_state(allp[idx], "random")
    w = list(order_weak[:2]); add_state((w[0], w[1]) if rng.random() < .5 else (w[1], w[0]), "weak")
    w2 = [int(order_weak[2]), int(order_weak[3])]; add_state(tuple(w2), "weak")
    for _ in range(2):
        b = int(order_best[0]); o = int(rng.choice([x for x in range(n) if x != b]))
        add_state((b, o) if rng.random() < .5 else (o, b), "contains_best")
    for _ in range(4):
        add_state(tuple(int(x) for x in rng.permutation(n)[:3]), "random")
    add_state(tuple(int(x) for x in order_weak[:3]), "weak")
    b = int(order_best[0]); o = [int(x) for x in rng.permutation([x for x in range(n) if x != b])[:2]]
    t = [b] + o; rng.shuffle(t); add_state(tuple(t), "contains_best")

    S, C = [], []
    for called, stratum in states:
        called = tuple(int(x) for x in called)
        k = len(called)
        qbest = 0.0 if k == 0 else float(np.nanmax(Q[list(called)]))
        cand = [j for j in range(n) if j not in called and not np.isnan(Q[j])]
        sid = f"{qid}:{k}:" + "-".join(str(i) for i in called)
        delta = Q[cand] - qbest
        pg = np.maximum(delta, 0.0)
        row = dict(state_id=sid, query_id=qid, split=split, task_family=fam, source_dataset=src, k=k, sample_stratum=stratum, called_models=[models[i] for i in called], n_candidates=len(cand),
                   label_Q_best=qbest, label_Q_called=[float(Q[i]) for i in called], label_best_next_gain=float(pg.max()) if len(cand) else 0.0,
                   label_best_next_model=models[cand[int(np.argmax(pg))]] if len(cand) and pg.max() > 0 else "STOP")
        for lam in LAMBDAS:
            u = pg - lam * cn[cand]
            j = int(np.argmax(u)) if len(cand) else -1
            if j >= 0 and u[j] > 0:
                row[f"label_oracle_action_l{lam}"], row[f"label_oracle_utility_l{lam}"], row[f"label_oracle_gain_l{lam}"] = models[cand[j]], float(u[j]), float(pg[j])
            else:
                row[f"label_oracle_action_l{lam}"], row[f"label_oracle_utility_l{lam}"], row[f"label_oracle_gain_l{lam}"] = "STOP", 0.0, 0.0
        row.update(feats(called))
        S.append(row)
        C.append(pd.DataFrame(dict(state_id=sid, query_id=qid, k=k, candidate_model=[models[j] for j in cand], label_Q=Q[cand], label_delta_Q=delta, label_positive_gain=pg,
                                   label_improves=(delta > 0), cost_norm=cn[cand], cost_gpu_s=gs[cand], label_completion_tokens=ctok[cand], label_confidence=lc[cand])))
    resp = pd.DataFrame(dict(query_id=qid, model_id=models, feat_log_tokens=f_logtok, feat_mean_lp=f_meanlp, feat_p05_lp=f_p05, feat_frac_lp_lt2=f_frac2, feat_mean_entropy=f_ent,
                             feat_truncated=f_trunc, feat_parse_ok=f_parse))
    return pd.DataFrame(S), pd.concat(C, ignore_index=True), resp


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--limit-queries", type=int, default=0)
    ap.add_argument("--procs", type=int, default=64)
    ap.add_argument("--only-20k", action="store_true", default=True)
    a = ap.parse_args()
    models = [m["id"] for m in json.load(open(ROOT / "manifests/models.json"))]
    path = ROOT / "dataset/responses.parquet"
    d = pd.read_parquet(path, columns=["query_id", "model_id", "Q", "in_20k"])
    d = d[d.in_20k.astype(bool)]
    cnt = d.dropna(subset=["Q"]).groupby("query_id").model_id.nunique()
    complete = sorted(cnt[cnt == len(models)].index)
    print(f"queries with all {len(models)} responses scored: {len(complete)} / {d.query_id.nunique()}", flush=True)
    if a.limit_queries:
        complete = complete[:a.limit_queries]
    ctx = get_context("fork")
    parts_S, parts_C, parts_R = [], [], []
    init(path, models)      # load once in the parent; forked workers share it copy-on-write
    with ctx.Pool(a.procs) as pool:
        for i, (s, c, r) in enumerate(pool.imap(per_query, complete, chunksize=8)):
            parts_S.append(s); parts_C.append(c); parts_R.append(r)
            if (i + 1) % 2000 == 0:
                print(f"  {i + 1} queries", flush=True)
    S = pd.concat(parts_S, ignore_index=True)
    C = pd.concat(parts_C, ignore_index=True)
    R = pd.concat(parts_R, ignore_index=True)
    out = ROOT / "dataset"
    S.to_parquet(out / "states.parquet", compression="zstd", index=False)
    C["candidate_model"] = C.candidate_model.astype("category")
    C.to_parquet(out / "candidates.parquet", compression="zstd", index=False)
    R.to_parquet(out / "response_features.parquet", compression="zstd", index=False)
    json.dump(dict(n_queries=len(complete), n_states=len(S), n_candidate_rows=len(C), lambdas=LAMBDAS, states_per_k=S.k.value_counts().sort_index().to_dict(), seed=SEED,
                   baseline_Q_best_empty_state=0.0), open(out / "state_build_manifest.json", "w"), indent=1)
    print(f"states {len(S)}, candidate rows {len(C)}, queries {len(complete)}")


if __name__ == "__main__":
    main()