File size: 12,592 Bytes
8ad880b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""Build the SeqRoute-1M master query pool (30,000), the 20,000-query generation subset, the 10,000 expansion pool, splits and nested scaling subsets.

Usage: python build_queries.py
Writes /mnt/localssd/seqroute1m/queries/{master_queries.parquet, queries_20k.parquet} and manifests/{queries,splits,subsets}*.json
Everything is deterministic from SEED.  Splits are query-level (grouped by source group_id so paraphrase / same-passage / same-table / same-MBPP-task items never straddle splits),
stratified by task family x source dataset, 70/15/15, and are defined over the whole 30k master; the 20k subset inherits them.
"""
import hashlib
import json
import random
import sys
import time
from collections import defaultdict
from pathlib import Path

import pandas as pd

sys.path.insert(0, "src")
sys.path.insert(0, ".")
from llmroute.seqroute import families as F, synth as S

import os
ROOT = Path(os.environ.get("SEQROUTE_BUILD_ROOT", "/mnt/localssd/seqroute1m"))
SEED = 20261010
N_MASTER, N_GEN = 30000, 20000
# (family) -> (base target in master, max_tokens non-reasoning, max_tokens reasoning)
FAMILIES = {
    "math_word": (1500, 1536, 6144), "math_competition": (1700, 3072, 8192), "knowledge": (1700, 1024, 4096), "science": (1700, 1536, 6144), "logic_reasoning": (1700, 1536, 6144),
    "code_generation": (1700, 2048, 6144), "code_repair": (1300, 2048, 6144), "summ_news": (1500, 384, 4096), "summ_abstractive": (1500, 256, 4096), "simplification": (1500, 256, 3072),
    "translation": (1500, 512, 4096), "information_extraction": (1500, 768, 4096), "classification": (1500, 64, 3072), "json_generation": (1200, 512, 3072),
    "instruction_following": (1600, 2048, 6144), "long_context_qa": (1100, 512, 4096), "reading_comprehension": (1500, 256, 4096), "table_reasoning": (1500, 1024, 4096),
    "planning": (1400, 4096, 8192), "multilingual": (1500, 1536, 6144),
}
CTX = 16384
TOK_SAFETY = 1.2     # prompt tokens are counted with the Qwen3 tokenizer; other models' tokenizers differ by up to ~15%


def hh(*parts, n=16):
    return hashlib.sha1("\x1f".join(str(p) for p in parts).encode()).hexdigest()[:n]


def waterfill(avail: dict, total: int) -> dict:
    """Equal allocation across sources, capped by availability, remainder redistributed."""
    alloc = {k: 0 for k in avail}
    left, active = total, [k for k in avail if avail[k] > 0]
    while left > 0 and active:
        share = max(left // len(active), 1)
        nxt = []
        for k in active:
            take = min(share, avail[k] - alloc[k], left)
            alloc[k] += take
            left -= take
            if alloc[k] < avail[k]:
                nxt.append(k)
        if all(min(share, avail[k] - alloc[k]) == 0 for k in nxt) and not nxt:
            break
        active = nxt
    return alloc


def pick(rows: list[dict], total: int, rng: random.Random) -> list[dict]:
    by = defaultdict(list)
    for r in rows:
        by[r["source_dataset"]].append(r)
    for v in by.values():
        rng.shuffle(v)
    al = waterfill({k: len(v) for k, v in by.items()}, min(total, len(rows)))
    out = []
    for k, v in by.items():
        out += v[:al[k]]
    return out


def assign_splits(df):
    df["split"] = ""
    for (fam, src), g in df.groupby(["task_family", "source_dataset"]):
        groups = sorted(g.group_id.unique(), key=lambda x: hh("split", SEED, x))
        sizes = g.group_id.value_counts()
        n, acc, assign = len(g), 0, {}
        for gid in groups:
            frac = acc / n
            assign[gid] = "train" if frac < 0.70 else ("val" if frac < 0.85 else "test")
            acc += sizes[gid]
        df.loc[g.index, "split"] = g.group_id.map(assign)
    df["legacy_split"] = df["split"]
    nstrata = df.groupby("group_id").apply(lambda g: g[["task_family", "source_dataset"]].drop_duplicates().shape[0])
    linked = set(nstrata[nstrata > 1].index)
    fixed = {}
    for gid in linked:
        u = int(hh("linked", SEED, gid, n=8), 16) / 16 ** 8
        fixed[gid] = "train" if u < 0.70 else ("val" if u < 0.85 else "test")
    for (fam, src), g in df.groupby(["task_family", "source_dataset"]):
        sizes = g.group_id.value_counts()
        cnt = {"train": 0, "val": 0, "test": 0}
        assign = {}
        for gid in sizes.index:
            if gid in fixed:
                assign[gid] = fixed[gid]; cnt[fixed[gid]] += sizes[gid]
        n, tot = len(g), 0
        for gid in sorted((x for x in sizes.index if x not in fixed), key=lambda x: hh("split", SEED, x)):
            tot_now = sum(cnt.values()) or 1
            deficit = {sp: w * max(n, 1) - cnt[sp] for sp, w in (("train", 0.70), ("val", 0.15), ("test", 0.15))}
            sp = max(deficit, key=lambda k: (deficit[k], k == "train"))
            assign[gid] = sp; cnt[sp] += sizes[gid]
        df.loc[g.index, "split"] = g.group_id.map(assign)
    return df


def main():
    t0 = time.time()
    fam_fns = {"math_word": F.math_word, "math_competition": F.math_competition, "knowledge": F.knowledge, "science": F.science, "logic_reasoning": F.logic_reasoning,
               "code_generation": F.code_generation, "summ_news": F.summ_news, "summ_abstractive": F.summ_abstractive, "simplification": F.simplification, "translation": F.translation,
               "information_extraction": F.information_extraction, "classification": F.classification, "json_generation": F.json_generation, "instruction_following": S.instruction_following,
               "long_context_qa": F.long_context_qa, "reading_comprehension": F.reading_comprehension, "table_reasoning": F.table_reasoning, "planning": S.planning, "multilingual": F.multilingual}
    pools = {}
    for fam, fn in fam_fns.items():
        pools[fam] = fn()
        print(fam, len(pools[fam]), f"{time.time() - t0:.0f}s", flush=True)
    pools["code_repair"] = F.code_repair_humanevalfix() + F.code_repair_mbpp(1300, SEED) + F.code_repair_mbpp(1300, SEED + 1)
    print("code_repair", len(pools["code_repair"]), f"{time.time() - t0:.0f}s", flush=True)

    from transformers import AutoTokenizer
    tok = AutoTokenizer.from_pretrained("/mnt/localssd/models/qwen3_8b")
    rng = random.Random(SEED)
    chosen, dropped = {}, defaultdict(int)
    for fam, rows in pools.items():
        seen, uniq = set(), []
        for r in rows:
            k = hh(fam, r["prompt"])
            if k in seen:
                dropped[fam, "duplicate_prompt"] += 1
                continue
            seen.add(k)
            uniq.append(r)
        base, _, rmax = FAMILIES[fam]
        cand = pick(uniq, int(base * 1.35) + 50, rng)
        lens = [len(x) for x in tok([r["prompt"] for r in cand], add_special_tokens=False)["input_ids"]]
        ok = []
        for r, n in zip(cand, lens):
            r["prompt_tokens_qwen3"] = n
            if n * TOK_SAFETY + rmax + 256 > CTX:
                dropped[fam, "too_long"] += 1
                continue
            ok.append(r)
        chosen[fam] = ok
        print(fam, "candidates", len(cand), "after length filter", len(ok), flush=True)

    # sizes: base targets capped by availability; the shortfall is redistributed (proportionally to base target) to families with spare candidates
    tgt = {f: min(FAMILIES[f][0], len(chosen[f])) for f in chosen}
    while sum(tgt.values()) < N_MASTER:
        spare = {f: len(chosen[f]) - tgt[f] for f in chosen if len(chosen[f]) > tgt[f]}
        if not spare:
            raise SystemExit(f"cannot reach {N_MASTER}; have {sum(tgt.values())}")
        need = N_MASTER - sum(tgt.values())
        wsum = sum(FAMILIES[f][0] for f in spare)
        for f in spare:
            tgt[f] += min(spare[f], max(1, round(need * FAMILIES[f][0] / wsum)))
            if sum(tgt.values()) >= N_MASTER:
                break
    while sum(tgt.values()) > N_MASTER:
        f = max(tgt, key=tgt.get)
        tgt[f] -= 1
    master = []
    for fam, rows in chosen.items():
        sel = pick(rows, tgt[fam], rng)
        for r in sel:
            r["max_tokens_nonreasoning"], r["max_tokens_reasoning"] = FAMILIES[fam][1], FAMILIES[fam][2]
        master += sel
    df = pd.DataFrame(master)
    df["query_id"] = [f"{f[:4]}_{hh(f, s, i, p, n=12)}" for f, s, i, p in zip(df.task_family, df.source_dataset, df.source_id, df.prompt)]
    assert df.query_id.is_unique, "query_id collision"
    df["payload"] = df.payload.map(lambda p: json.dumps(p, ensure_ascii=False, default=lambda o: o.tolist() if hasattr(o, "tolist") else str(o)))
    print("master", len(df), dict(df.task_family.value_counts()), flush=True)

    # ---- splits over the 30k master: 70/15/15 by group within (family, source) ----------------------------------------------------------
    # `legacy_split` (strata handled independently) is only used to draw the 20k subset; the final `split` additionally keeps a group that spans several
    # strata (e.g. HumanEval / HumanEval-Fix, MBPP / MBPP-mutants) in a single split.
    df = assign_splits(df)
    # ---- 20k generation subset: proportional within (family, source, split) ---------------------------------------------------------------
    df["in_20k"] = False
    r2 = random.Random(SEED + 7)
    for key, g in df.groupby(["task_family", "source_dataset", "legacy_split"]):
        k = round(len(g) * N_GEN / N_MASTER)
        idx = list(g.index)
        r2.shuffle(idx)
        df.loc[idx[:k], "in_20k"] = True
    # fix rounding to exactly 20,000
    cur = int(df.in_20k.sum())
    pool_in, pool_out = list(df.index[df.in_20k]), list(df.index[~df.in_20k])
    r2.shuffle(pool_in); r2.shuffle(pool_out)
    if cur > N_GEN:
        df.loc[pool_in[:cur - N_GEN], "in_20k"] = False
    elif cur < N_GEN:
        df.loc[pool_out[:N_GEN - cur], "in_20k"] = True
    assert int(df.in_20k.sum()) == N_GEN
    # ---- nested scaling subsets within the 20k: stratified interleaved ordering over the train split ----------------------------------
    df["scale_rank"] = -1.0
    tr = df[(df.split == "train") & df.in_20k]
    for _, g in tr.groupby(["task_family", "source_dataset"]):
        idx = sorted(g.index, key=lambda i: hh("scale", SEED, df.at[i, "query_id"]))
        for rank, i in enumerate(idx):
            df.at[i, "scale_rank"] = (rank + 0.5) / len(idx)
    order = tr.index[tr.index.map(lambda i: True)]
    order = sorted(order, key=lambda i: (df.at[i, "scale_rank"], hh("tie", df.at[i, "query_id"])))
    df["scale_order"] = -1
    for pos, i in enumerate(order):
        df.at[i, "scale_order"] = pos
    df["prompt_chars"] = df.prompt.str.len()
    (ROOT / "queries").mkdir(parents=True, exist_ok=True)
    df.to_parquet(ROOT / "queries/master_queries.parquet")
    df[df.in_20k].reset_index(drop=True).to_parquet(ROOT / "queries/queries_20k.parquet")
    M = ROOT / "manifests"
    M.mkdir(exist_ok=True)
    for sp in ("train", "val", "test"):
        json.dump(sorted(df[df.split == sp].query_id), open(M / f"master_{sp}_ids.json", "w"))
        json.dump(sorted(df[(df.split == sp) & df.in_20k].query_id), open(M / f"gen20k_{sp}_ids.json", "w"))
    json.dump(sorted(df[~df.in_20k].query_id), open(M / "expansion_10k_ids.json", "w"))
    trn = df[(df.split == "train") & df.in_20k].sort_values("scale_order")
    for n in (1000, 2000, 5000, 10000, len(trn)):
        json.dump(list(trn.query_id[:n]), open(M / f"scaling_train_{n}_ids.json", "w"))
    man = dict(created=time.strftime("%F %T"), seed=SEED, n_master=len(df), n_gen20k=int(df.in_20k.sum()), n_expansion=int((~df.in_20k).sum()),
               per_family_master=df.groupby("task_family").size().to_dict(), per_family_20k=df[df.in_20k].groupby("task_family").size().to_dict(),
               per_source_20k=df[df.in_20k].groupby(["task_family", "source_dataset"]).size().rename("n").reset_index().to_dict("records"),
               split_master=df.split.value_counts().to_dict(), split_20k=df[df.in_20k].split.value_counts().to_dict(),
               dropped={f"{k[0]}:{k[1]}": v for k, v in dropped.items()}, token_safety=TOK_SAFETY, ctx=CTX,
               split_rule="group-level (group_id) 70/15/15 within (task_family, source_dataset) over the 30k master; 20k subset = proportional sample within (family, source, split)",
               scaling_note="scaling_train_N = first N train queries of the 20k set in a stratified interleaved order (nested); val/test fixed. Train of the 20k is 14,000; sizes beyond need the expansion pool.")
    json.dump(man, open(M / "queries_manifest.json", "w"), indent=1)
    print(df[df.in_20k].groupby(["task_family", "split"]).size().unstack().to_string())
    print("done", f"{time.time() - t0:.0f}s")


if __name__ == "__main__":
    main()