Datasets:
File size: 15,182 Bytes
d296683 | 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | #!/usr/bin/env python3
"""v3-Trainingsdaten (rein deterministisch, ohne 27B; die Wahrheit ist immer bekannt).
Neu gegenueber v2/Hardcore:
* Leerzeichen zaehlen als Zeichen und stehen als sichtbares Symbol (SPACE) in Spreizung/Positionen
* neue Beispiele: Ueberlaenge 46-80 Zeichen, Saetze, Code, Pfade/URLs/Mails, Sonderzeichen-Gruppen
* Zaehlspektakel beginnt mit einer Ansage 'Ich zaehle bis N!'; Variante 'counter' schreibt hinter jede Zahl [k/N]
* die alten Beispiele (v2 + Hardcore, 4172) werden ins neue Format umgeschrieben (stoerender '.' nach dem Think-Block entfaellt)
Ausgabe: v3/dataset_v3_<variante>.jsonl, v3/heldout_v3.json (frisches Testset, nie im Training).
Aufruf: v3_data.py [--selftest]
"""
import json
import os
import random
import re
import string
import sys
from collections import Counter
from pathlib import Path
os.environ["CUDA_VISIBLE_DEVICES"] = ""
sys.path.insert(0, "/mnt/models/graf_zahl")
from generate_hardcore_massive import PERF_RE, TC, TO, canonical_number # noqa: E402
PLATTE = "/home/david/Schreibtisch/Platte"
OUTDIR = Path(f"{PLATTE}/models/graf_zahl/v3")
MIX = f"{PLATTE}/models/graf_zahl/mixed_hardcore_dataset.jsonl"
CPT = "/mnt/models/graf_zahl/cpt_data/fineweb_heal_dataset.jsonl"
POOL = "/mnt/models/graf_zahl/word_pool_hardcore.json"
TESTS = [f"{PLATTE}/models/graf_zahl/ab_test_results.json", f"{PLATTE}/models/graf_zahl/generalization_results.json"]
TOKENIZER = f"{PLATTE}/models/graf_zahl/qwen_healed_merged"
SPACE = "␣"
SEED = 3407
VARIANTS = ("plain", "counter")
N_LONG, N_SPACE_CODE, N_RUNS = 500, 700, 300
def sym(c):
return SPACE if c == " " else c
def build_think(text):
n = len(text)
lines = [TO, f"Wort: {text}", "Spreizung: " + " - ".join(sym(c) for c in text), "Zählung:"]
lines += [f"[Position {i}: {sym(c)}] -> Zähler: {i}." for i, c in enumerate(text, 1)]
lines += [f"Zur Sicherheit nachgezählt: {n}.", TC]
return "\n".join(lines)
def build_spectacle(n, comments, variant):
items = []
for i in range(1, n + 1):
s = f"{canonical_number(i)}! Ah ah ah! ({comments[i - 1]})"
items.append(s + f" [{i}/{n}]" if variant == "counter" else s)
return f"Ich zähle bis {n}!\n" + " ".join(items) + f" Das sind {n}."
def build_assistant(text, comments, variant):
return build_think(text) + "\n" + build_spectacle(len(text), comments, variant)
ITEM_RE = re.compile(r"([A-Za-zäöüÄÖÜß]+)! Ah ah ah! \(([^()\n]{1,80})\)(?: \[(\d+)/(\d+)\])?")
def validate(text, assistant, variant):
"""Rueckgabe: Fehlertext oder None. Prueft gegen die Wahrheit (text)."""
n = len(text)
head = build_think(text) + f"\nIch zähle bis {n}!\n"
if not assistant.startswith(head):
return "Think-Block oder Ansage weicht ab"
perf = assistant[len(head):]
items = ITEM_RE.findall(perf)
if len(items) != n:
return f"{len(items)} Zahlen statt {n}"
for i, (num, _, k, nn) in enumerate(items, 1):
if num != canonical_number(i):
return f"Zahlwort {i}"
if variant == "counter" and (k, nn) != (str(i), str(n)):
return f"Zaehler {i}"
if build_assistant(text, [c for _, c, _, _ in items], variant) != assistant:
return "Format weicht ab"
return None
# --------------------------------------------------------------------------- Textquellen
def load_sentences(exclude_words, limit_articles=8000):
out = []
for i, line in enumerate(open(CPT, encoding="utf-8")):
if i >= limit_articles:
break
for s in re.split(r"(?<=[a-zäöüß][.!?])\s+", json.loads(line)["text"][:4000]):
s = s.strip()
if (20 <= len(s) <= 80 and re.fullmatch(r"[A-Za-zÄÖÜäöüß0-9 ,.;:!?()\-]+", s) and " " not in s
and s[0].isupper() and s[-1] in ".!?" and len(s.split()) >= 4
and sum(c.isalpha() for c in s) >= 0.7 * len(s)
and not any(w in s.lower() for w in exclude_words)):
out.append(s)
return sorted(set(out))
def load_pool_words(exclude_words):
return [p["wort"] for p in json.load(open(POOL, encoding="utf-8"))
if not any(w in p["wort"].lower() for w in exclude_words)]
def load_excluded():
words, strings = set(), set()
for p in TESTS:
for r in json.load(open(p, encoding="utf-8")):
t = r.get("wort") or r.get("text")
(strings if r.get("text") else words).add(t.lower())
strings.add(t)
return words | {w for w in strings if len(w) >= 8 and w.isalpha()}, strings
def load_comments():
c = Counter()
for line in open(f"/mnt/models/graf_zahl/dataset_massive_v2.jsonl", encoding="utf-8"):
for _, cm in PERF_RE.findall(json.loads(line)["messages"][2]["content"]):
cm = cm.strip()
if cm and len(cm) <= 40 and not re.search(r"\d", cm):
c[cm] += 1
return [k for k, _ in c.most_common(40)]
# --------------------------------------------------------------------------- Generatoren
SYMS = "!#$%&*+-=?_.:;,@/|~^"
BRACKETS = "()[]{}<>"
def rand_alnum(r, n):
return "".join(r.choice(string.ascii_letters + string.digits) for _ in range(n))
def rand_sym(r, n):
return "".join(r.choice(string.ascii_letters + string.digits + SYMS + BRACKETS) for _ in range(n))
def compound(r, words, lo, hi):
for _ in range(200):
parts, total = [], 0
while total < lo:
w = r.choice(words)
if total + len(w) > hi:
break
parts.append(w if not parts else w[0].lower() + w[1:])
total += len(w)
if lo <= total <= hi:
return "".join(parts)
return None
def runs(r, lo, hi):
pool = string.ascii_letters + string.digits + SYMS + "()[]{}<>"
s, prev = "", None
target = r.randint(lo, hi)
while len(s) < target:
c = r.choice([x for x in pool if x != prev])
s += c * r.randint(2, 5)
prev = c
return s[:target] if r.random() < 0.5 else s[:target] + rand_alnum(r, 0)
def hexs(r, n):
return "".join(r.choice("0123456789abcdef") for _ in range(n))
def code_like(r, words):
w = lambda: r.choice(["count", "total", "value", "index", "result", "name", "data", "item", "size", "temp"])
n = lambda: str(r.randint(1, 999))
a, b, f = w(), w(), w()
kind = r.randrange(24)
return [
f"def {f}({a}): return {a} + {n()}", f"for {a} in range({n()}):", f'print("{r.choice(words)[:10]}")',
f"if {a} > {n()}: {b} = {a}", f"{a} = [{n()}, {n()}, {n()}]", f"import {r.choice(['os', 'sys', 'json', 'math', 'time'])}",
f"while {a} < {n()}:", f"return {a}[{r.randint(0, 9)}]", f"SELECT {a} FROM {b} WHERE id = {n()};",
f"UPDATE {a} SET {b} = {n()} WHERE id = {n()};", f"const {a} = {n()} * {n()};", f"console.log({a});",
f"function {f}({a}) {{ return {a}; }}", f'<div class="{a}">{r.choice(words)[:8]}</div>', f'<a href="/{a}">{b}</a>',
f"ls -la /home/{a}", f'grep -r "{a}" ./src', f"cd ../{a} && make", f"{a}.{b}({n()})", f"x = {n()} if {a} else {n()}",
f"git commit -m \"{a} {b}\"", f"{a}[{b}] = {a}[{f}] + {n()};", f"int {a} = {n()};", f"#include <{r.choice(['stdio', 'stdlib', 'string'])}.h>",
][kind]
def misc_string(r, words):
kind = r.randrange(10)
name = lambda: r.choice(["max", "anna", "tom", "lisa", "peter", "julia"])
dom = lambda: r.choice(["example", "mail", "firma", "test", "server"])
return [
f"/usr/local/bin/{r.choice(['python', 'node', 'gcc', 'tool'])}{r.randint(1, 9)}", f"https://www.{dom()}.de/{r.choice(['seite', 'blog', 'shop'])}/{r.randint(1, 999)}",
f"{name()}.{name()}@{dom()}.de", f"{r.randint(1, 255)}.{r.randint(0, 255)}.{r.randint(0, 255)}.{r.randint(0, 255)}",
":".join(hexs(r, 2).upper() for _ in range(6)), f"{hexs(r, 8)}-{hexs(r, 4)}-{hexs(r, 4)}-{hexs(r, 12)}"[:r.randint(30, 36)],
f"0x{hexs(r, r.randint(6, 16))}", f"2026-{r.randint(1, 12):02d}-{r.randint(1, 28):02d} {r.randint(0, 23):02d}:{r.randint(0, 59):02d}:{r.randint(0, 59):02d}",
f"v{r.randint(1, 9)}.{r.randint(0, 99)}.{r.randint(0, 999)}-{r.choice(['beta', 'rc1', 'alpha'])}",
json.dumps({r.choice(["id", "name", "wert"]): r.randint(1, 99), "ok": r.choice([True, False])}),
][kind]
# --------------------------------------------------------------------------- Prompts
Q_STR = ["Wie viele Zeichen hat der String {q}?", "Zähle die Zeichen in {q}.", "Wie lang ist {q} (in Zeichen)?",
"Bitte zähle alle Zeichen von {q}.", "How many characters are in {q}?", "Hey Graf, wie viele Zeichen hat {q}?",
"Wie viele Zeichen hat das Wort {q}?", "Zerlege und zähle: {q}"]
def quote(s):
for a, b in (("'", "'"), ('"', '"'), ("«", "»")):
if a not in s and b not in s:
return f"{a}{s}{b}"
return f"«{s}»"
def make_prompt(r, text):
tpl = r.choice(Q_STR)
if " " in text and r.random() < 0.5:
tpl += " Leerzeichen zählen mit." if not tpl.startswith("How") else " Count the spaces too."
return tpl.format(q=quote(text))
# --------------------------------------------------------------------------- Aufbau
def build_new(seed, counts, words, sentences, excluded_strings, taken):
r = random.Random(seed)
rows = []
def add(text, kat):
if text and 7 <= len(text) <= 80 and text not in excluded_strings and text not in taken and text == text.strip() and " " not in text:
taken.add(text)
rows.append((kat, text))
return True
return False
def fill(kat, n, fn):
c, tries = 0, 0
while c < n and tries < n * 50:
tries += 1
c += add(fn(), kat)
long_n, sc_n, run_n = counts
fill("lang", int(long_n * 0.30), lambda: rand_alnum(r, r.randint(46, 80)))
fill("lang", int(long_n * 0.20), lambda: rand_sym(r, r.randint(46, 80)))
fill("lang", int(long_n * 0.25), lambda: compound(r, words, 46, 80))
long_sent = [s for s in sentences if len(s) >= 46]
fill("lang", int(long_n * 0.25), lambda: r.choice(long_sent) if long_sent else None)
short_sent = [s for s in sentences if len(s) <= 60]
fill("satz", int(sc_n * 0.36), lambda: r.choice(short_sent))
fill("code", int(sc_n * 0.36), lambda: code_like(r, words))
fill("misc", int(sc_n * 0.28), lambda: misc_string(r, words))
fill("runs", run_n, lambda: runs(r, 8, 45))
return rows
def rewrite_old(variant, comments_pool):
rows = []
for i, line in enumerate(open(MIX, encoding="utf-8")):
ex = json.loads(line)
a = ex["messages"][2]["content"]
text = re.search(r"^Wort: (.+)$", a, re.M).group(1)
cms = [c.strip() for _, c in PERF_RE.findall(a.split("</think>")[-1])]
if len(cms) != len(text):
continue
ex["messages"][2]["content"] = build_assistant(text, cms, variant)
rows.append(("alt", text, ex))
return rows
def main():
OUTDIR.mkdir(parents=True, exist_ok=True)
ex_words, ex_strings = load_excluded()
words = [w for w in load_pool_words(ex_words) if len(w) <= 30]
sentences = [s for s in load_sentences(ex_words)]
comments = load_comments()
v2_system = json.loads(open(MIX, encoding="utf-8").readline())["messages"][0]["content"]
print(f"Woerter {len(words)}, Saetze {len(sentences)}, Kommentare {len(comments)}, ausgeschlossene Teststrings {len(ex_strings)}", flush=True)
taken = set()
new = build_new(SEED, (N_LONG, N_SPACE_CODE, N_RUNS), words, sentences, ex_strings, taken)
held = build_new(777, (0, 0, 0), words, sentences, ex_strings, taken) # Platzhalter, unten gezielt gefuellt
print("Neue Beispiele:", dict(Counter(k for k, _ in new)), "gesamt", len(new), flush=True)
# frisches Testset (nicht im Training): eigene Seeds, Texte nie in 'taken'
rh = random.Random(777)
hs = []
def add_h(kat, text, n):
if text and text not in taken and text not in ex_strings and text == text.strip() and " " not in text and 7 <= len(text) <= 80:
taken.add(text); hs.append({"kategorie": kat, "text": text, "prompt": make_prompt(rh, text)})
tries = 0
plan = [("H Satz (Leerzeichen)", 8, lambda: rh.choice(sentences)), ("H Code", 8, lambda: code_like(rh, words)),
("H Pfad/URL/Mail/IP", 6, lambda: misc_string(rh, words)), ("H Sonderzeichen-Gruppen", 6, lambda: runs(rh, 8, 45)),
("H Zufall 50-75", 6, lambda: rand_sym(rh, rh.randint(50, 75))), ("H Satz 55-75", 4, lambda: rh.choice([s for s in sentences if len(s) >= 55])),
("H Kompositum 50-75", 4, lambda: compound(rh, words, 50, 75))]
for kat, n, fn in plan:
have = 0
while have < n and tries < 5000:
tries += 1
before = len(hs); add_h(kat, fn(), n); have += len(hs) - before
json.dump(hs, open(OUTDIR / "heldout_v3.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("Testset:", dict(Counter(h["kategorie"] for h in hs)), "gesamt", len(hs), flush=True)
for variant in VARIANTS:
rng = random.Random(SEED)
allrows = rewrite_old(variant, comments)
for kat, text in new:
cms = [rng.choice(comments) for _ in text]
ex = {"messages": [{"role": "system", "content": v2_system},
{"role": "user", "content": make_prompt(rng, text)},
{"role": "assistant", "content": build_assistant(text, cms, variant)}]}
allrows.append((kat, text, ex))
bad = [(k, t[:30], validate(t, e["messages"][2]["content"], variant)) for k, t, e in allrows
if validate(t, e["messages"][2]["content"], variant)]
assert not bad, bad[:3]
seen_t, dedup = set(), []
for row in allrows:
if row[1] in seen_t:
continue
seen_t.add(row[1])
dedup.append(row)
print(f"[{variant}] {len(allrows) - len(dedup)} doppelte Texte entfernt", flush=True)
allrows = dedup
rng.shuffle(allrows)
out = OUTDIR / f"dataset_v3_{variant}.jsonl"
with open(out, "w", encoding="utf-8") as f:
for _, _, e in allrows:
f.write(json.dumps(e, ensure_ascii=False) + "\n")
print(f"[{variant}] {len(allrows)} Beispiele, alle validiert -> {out} ({out.stat().st_size / 1e6:.1f} MB)", flush=True)
def selftest():
for variant in VARIANTS:
for t in ("Kaffee", "Hallo Welt", "arr[i] = 1;", "@@@###$$$%%%"):
a = build_assistant(t, ["Donner"] * len(t), variant)
assert validate(t, a, variant) is None, (variant, t)
assert validate(t, a.replace(f"Ich zähle bis {len(t)}!", "Ich zähle bis 99!"), variant) is not None
assert validate(t + "x", a, variant) is not None
assert validate("ab cd", build_assistant("ab cd", ["Blitz"] * 5, "plain"), "plain") is None
assert SPACE in build_think("a b")
print("Selbsttest bestanden: Think-Block mit Leerzeichen-Symbol, beide Spektakel-Varianten, Fehlererkennung.")
if __name__ == "__main__":
selftest() if "--selftest" in sys.argv else main()
|