File size: 10,457 Bytes
6da8440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d155ca
6da8440
 
 
 
 
 
292dc80
6da8440
e5d809c
6da8440
 
e5d809c
 
6da8440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Builds the Bloxy v1 training set (~30k chat examples) from 19 Hugging Face datasets.

Usage:
    pip install -r requirements-data.txt
    python scripts/build_dataset.py                 # full build -> out/
    python scripts/build_dataset.py --scale 0.05    # quick smoke test (~1.5k examples)
    python scripts/build_dataset.py --only procedural_builds,minecraft_builds

Outputs (in out/):
    train.jsonl.gz     training examples: {"messages": [...], "tools": [...]?, "source", "category"}
    val.jsonl          small held-out slice for eval loss
    robloxqa_test.jsonl  multiple-choice exam (never trained on)
    stats.json         counts, token estimates, cost estimate
    samples.md         a few examples from every source to eyeball
"""

from __future__ import annotations

import argparse
import json
import random
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from bloxy_data import sources as S  # noqa: E402
from bloxy_data.common import answer_key, est_tokens, example_key, luau_compiles, write_jsonl  # noqa: E402

# Builds whose Luau we generate ourselves get compiled to prove they're valid.
LUAU_CHECKED = {"minecraft_builds", "minecraftbuildings", "procedural_builds", "hack337_schematics", "brick_builds"}

# name -> (category, target, function). Targets add up to ~30k.
RECIPE = [
    # Building (~60%)
    ("minecraft_builds",   "building", 6500, lambda n, r, l: S.minecraft_builds(n, r, l)),
    ("minecraftbuildings", "building", 1000, lambda n, r, l: S.minecraftbuildings(n, r, l)),
    ("hack337_schematics", "building", 1500, lambda n, r, l: S.hack337_schematics(n, r, l)),
    ("blender_3dcode",     "building", 1500, lambda n, r, l: S.blender_3dcode(n, r, l)),
    ("cadquery_code",      "building", 2500, lambda n, r, l: S.cadquery_code(n, r, l)),
    ("cadquery_plans",     "building", 1000, lambda n, r, l: S.cadquery_plans(n, r, l)),
    ("omar_cadquery",      "building", 1000, lambda n, r, l: S.omar_cadquery(n, r, l)),
    ("brick_builds",       "building", 3500, lambda n, r, l: S.brick_builds(n, r, l)),
    ("procedural_builds",  "building", 2000, lambda n, r, l: S.procedural_builds(n, r, l)),
    # Studio tool use (~25%)
    ("robloxagent_v2",     "agent",    3750, lambda n, r, l: S.roblox_agent("Pinkstack/RobloxAgent-v2", n, r, l)),
    ("robloxagent_v1",     "agent",    3750, lambda n, r, l: S.roblox_agent("Pinkstack/RobloxAgent-toolreason-v1-2500", n, r, l)),
    # Luau scripting (~12%)
    ("luau_coder",         "luau",     1000, lambda n, r, l: S.luau_coder(n, r, l)),
    ("luaudev",            "luau",      700, lambda n, r, l: S.luaudev(n, r, l)),
    ("luau_reasoning",     "luau",      600, lambda n, r, l: S.luau_reasoning(n, r, l)),
    ("luau_coding_l1",     "luau",      500, lambda n, r, l: S.instruction_rows("8BitStudio/Roblox-luau-coding_L1", n, r, l)),
    ("luau_corpus",        "luau",      400, lambda n, r, l: S.luau_corpus(n, r, l)),
    ("danik_roblox",       "luau",      300, lambda n, r, l: S.instruction_rows("danik7x/roblox-ai-training-data", n, r, l)),
    # Roblox knowledge (~3%)
    ("roblox_docs",        "knowledge", 400, lambda n, r, l: S.docs_rows("khtsly/roblox_docs_corpus_text", n, r, l, config="en-us")),
    ("roblox_info_dump",   "knowledge", 300, lambda n, r, l: S.docs_rows("TorpedoSoftware/roblox-info-dump", n, r, l, title_col="url")),
    ("devforum",           "knowledge", 300, lambda n, r, l: S.devforum(n, r, l)),
    # Radin-dev1/BloxyAItraining: Roblox building / Luau skill guides
    ("bloxy_skill_guides", "knowledge", 120, lambda n, r, l: S.bloxy_skill_guides(n, r, l)),
]
# Kermitkiller666/Minecraftbuilding2 and /Minecraft-Building1 are image-input
# datasets (cross-section PNGs -> /setblock), so they are left out of this
# text-only v1. Their share went to minecraft_builds.

ANSWER_REUSE_OK = {"bloxy_skill_guides"}

# Shortfalls (a source with fewer usable rows than its target) are refilled
# from these, so the final mix keeps its shape.
FILLERS = {"building": "procedural_builds", "agent": "luau_coder", "luau": "luau_coder", "knowledge": None}
# Keep synthetic builds to a sane share so Bloxy doesn't only learn 13 templates.
FILLER_CAP = {"procedural_builds": 4000}  # at --scale 1
SECOND_FILLER = {"building": "cadquery_code"}


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=str(ROOT / "out"))
    ap.add_argument("--scale", type=float, default=1.0, help="multiply every target (0.05 = smoke test)")
    ap.add_argument("--only", default="", help="comma list of source names")
    ap.add_argument("--seed", type=int, default=42)
    ap.add_argument("--val", type=int, default=300)
    ap.add_argument("--luau", default="", help="path to luau-compile; drops generated builds that don't compile")
    args = ap.parse_args()

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    only = {s for s in args.only.split(",") if s}
    rng = random.Random(args.seed)
    log_lines: list[str] = []

    def log(msg: str) -> None:
        print(msg, flush=True)
        log_lines.append(msg)

    by_source: dict[str, list[dict]] = defaultdict(list)
    seen_ex, seen_ans = set(), set()
    dupes = Counter()
    bad_luau = Counter()
    errors = {}

    def take(name: str, cat: str, n: int, fn) -> int:
        got = 0
        t0 = time.time()
        try:
            # ask for extra so duplicates/filters don't leave us short
            for item in fn(int(n * 1.3) + 10, random.Random(rng.random()), log):
                rec = item if isinstance(item, dict) else {"messages": item}
                if args.luau and name in LUAU_CHECKED and not luau_compiles(rec["messages"], args.luau):
                    bad_luau[name] += 1
                    continue
                k1, k2 = example_key(rec["messages"]), answer_key(rec["messages"])
                # agent runs and the skill guides legitimately reuse answers under new questions
                if k1 in seen_ex or (name not in ANSWER_REUSE_OK and cat != "agent" and k2 in seen_ans):
                    dupes[name] += 1
                    continue
                seen_ex.add(k1)
                seen_ans.add(k2)
                rec["source"], rec["category"] = name, cat
                by_source[name].append(rec)
                got += 1
                if got >= n:
                    break
        except Exception as e:  # keep going: one broken dataset must not kill the build
            import traceback

            errors[name] = repr(e)
            log(f"  !! {name} failed: {e!r}")
            traceback.print_exc()
        log(f"  -> {name}: {got}/{n} in {time.time() - t0:.0f}s")
        return got

    short: Counter = Counter()
    for name, cat, target, fn in RECIPE:
        if only and name not in only:
            continue
        n = max(1, int(target * args.scale))
        log(f"[{cat}] {name} (target {n})")
        got = take(name, cat, n, fn)
        if got < n:
            short[cat] += n - got

    for cat, missing in short.items():
        filler = FILLERS.get(cat)
        if not filler or missing <= 0 or (only and filler not in only):
            continue
        fn = next(f for nm, c, t, f in RECIPE if nm == filler)
        cap = int(FILLER_CAP[filler] * args.scale) if filler in FILLER_CAP else None
        n = missing if cap is None else max(0, min(missing, cap - len(by_source.get(filler, []))))
        if n:
            log(f"[{cat}] refilling {n} from {filler}")
            missing -= take(filler, cat, n, fn)
        second = SECOND_FILLER.get(cat)
        if missing > 0 and second and not (only and second not in only):
            fn2 = next(f for nm, c, t, f in RECIPE if nm == second)
            log(f"[{cat}] refilling {missing} from {second}")
            take(second, cat, missing, fn2)

    rows = [r for rs in by_source.values() for r in rs]
    rng.shuffle(rows)
    val = rows[: args.val]
    train = rows[args.val:]
    write_jsonl(out / "train.jsonl.gz", train)
    write_jsonl(out / "val.jsonl", val)

    if not only:
        try:
            n_eval = write_jsonl(out / "robloxqa_test.jsonl", S.robloxqa_eval(random.Random(7)))
            log(f"eval: {n_eval} RobloxQA questions")
        except Exception as e:
            errors["robloxqa_eval"] = repr(e)
            log(f"  !! robloxqa eval failed: {e!r}")

    toks = Counter()
    cnt = Counter()
    for r in train:
        t = est_tokens(r["messages"]) + (len(json.dumps(r.get("tools", []))) // 4 if r.get("tools") else 0)
        toks[r["category"]] += t
        cnt[r["category"]] += 1
    total_tokens = sum(toks.values())
    # A6000 + Unsloth QLoRA on a 12B model: ~1,500-2,500 tokens/s.
    hours = (total_tokens / 2000) / 3600
    stats = {
        "examples": len(train), "val": len(val),
        "by_category": dict(cnt), "by_source": {k: len(v) for k, v in by_source.items()},
        "est_tokens": total_tokens, "est_tokens_by_category": dict(toks),
        "est_train_hours_12b_a6000_1epoch": round(hours, 1),
        "est_cost_usd_a6000": round(hours * 0.59, 2),
        "duplicates_dropped": dict(dupes), "luau_compile_failures": dict(bad_luau),
        "luau_checked": bool(args.luau), "errors": errors,
    }
    (out / "stats.json").write_text(json.dumps(stats, indent=2))

    with open(out / "samples.md", "w", encoding="utf-8") as f:
        for name, rs in by_source.items():
            f.write(f"\n\n# {name} ({len(rs)})\n")
            for r in rs[:2]:
                for m in r["messages"]:
                    body = m.get("content") or ""
                    if m.get("tool_calls"):
                        body += "\n" + json.dumps([c["function"] for c in m["tool_calls"]])[:600]
                    f.write(f"\n**{m['role']}**: {body[:1500]}\n")
                f.write("\n---\n")
    ex_dir = out / "example_builds"
    ex_dir.mkdir(exist_ok=True)
    import re as _re
    for name in sorted(LUAU_CHECKED):
        for i, r in enumerate(by_source.get(name, [])[:4]):
            code = _re.findall(r"```lua\n(.*?)```", r["messages"][-1]["content"], _re.DOTALL)
            if code:
                (ex_dir / f"{name}_{i}.luau").write_text(f"-- {r['messages'][1]['content'][:200]}\n{code[0]}")
    (out / "build_log.txt").write_text("\n".join(log_lines))
    print(json.dumps(stats, indent=2))


if __name__ == "__main__":
    main()