calib-corpora / tools /pool_german.py
notforu777's picture
kolibri-1-moe: German pool, Kolibri-1 vocab sweep, recipe and build; eval/neutral-de, eval/longctx, eval/agentic-kolibri
272005d verified
Raw History Blame Contribute Delete
22.8 kB
"""German for the pool and the held-out German evals, for a model trained on 24% German.
python tools/pool_german.py --seed 20261006 # pool/german/*.jsonl, eval/neutral-de, eval/longctx
Kolibri-1 (Aleph Alpha) was trained on 62.5% English, 23.9% German and 13.6%
code, with a tokenizer cut for German word structure. The multilingual pool
had 19 German documents of 687, 0.62% of the Flash-Next MoE build: the experts
German routes to would be calibrated on almost nothing. This collects, from
sources with a licence that allows it and nothing written by a language model
here:
german wikipedia Wikipedia DE articles (CC BY-SA 4.0), text
oasst2 OpenAssistant conversations in German (Apache-2.0), the
best-ranked reply at every turn, chat
ultrachat_de multi-turn chats (MIT), chat
germanrag question + retrieved passages -> answer (CC BY 4.0), chat
agentic_de tool-calling dialogues in German from templates: weather,
trains, calendar, invoices, file and web search, single and
parallel calls, a failed call read and corrected; chat
german_longctx long Wikipedia DE articles (16k+ tokens), for calib_longctx
and the held-out sets, drawn from offsets the pool never reads:
eval/neutral-de/eval_neutral-de.txt German Wikipedia prose, ~350k tokens
eval/longctx/eval_longctx.txt long articles (12k+ tokens), German and English, ~280k tokens:
eight chunks at -c 32768
Records go through poollib.Record (stable ids, field order). Selection is
seeded: the same seed reads the same rows. The datasets-server API serves the
rows, so nothing is cloned.
"""
from __future__ import annotations
import argparse
import ast
import json
import os
import random
import sys
import time
import urllib.parse
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import poollib as P # noqa: E402
DS = "https://datasets-server.huggingface.co"
WIKI_DE = ("wikimedia/wikipedia", "20231101.de")
WIKI_EN = ("wikimedia/wikipedia", "20231101.en")
CHARS_PER_TOKEN = 4.4 # German prose on a German-cut tokenizer, measured on the 128k Kolibri vocabulary
def get(path, **q):
url = f"{DS}/{path}?" + urllib.parse.urlencode(q)
for i in range(6):
try:
with urllib.request.urlopen(url, timeout=120) as r:
return json.loads(r.read())
except Exception as e: # rate limits and the occasional 5xx: back off
if i == 5:
raise RuntimeError(f"{url}: {e}")
time.sleep(5 * (i + 1))
def rows(dataset, config, offset, length=100, split="train"):
return [r["row"] for r in get("rows", dataset=dataset, config=config, split=split, offset=offset, length=length)["rows"]]
def filtered(dataset, where, config="default", split="train", page=100):
out, off = [], 0
while True:
d = get("filter", dataset=dataset, config=config, split=split, where=where, offset=off, length=page)
got = [r["row"] for r in d["rows"]]
out += got
off += len(got)
if not got or off >= d.get("num_rows_total", 0):
return out
def maybe_list(v):
if isinstance(v, str):
try:
return json.loads(v)
except json.JSONDecodeError:
return ast.literal_eval(v)
return v
# ---------------------------------------------------------------- Wikipedia
def wiki_sample(config, offsets, seen):
for off in offsets:
for r in rows(*config, offset=off):
if r["id"] in seen:
continue
seen.add(r["id"])
yield r
def wiki_offsets(rng, n_total, n, avoid=()):
out = set()
while len(out) < n:
o = rng.randrange(0, n_total - 100) // 100 * 100
if all(abs(o - a) >= 100 for a in avoid):
out.add(o)
return sorted(out)
def wiki_text(r, cap=None):
"""Title and text; with cap, cut at the last paragraph break before cap characters."""
text = r["text"].strip()
if cap and len(text) > cap:
cut = text.rfind("\n", 0, cap)
text = text[:cut if cut > cap // 2 else cap].rstrip()
return f"{r['title']}\n\n{text}"
def wiki_record(r, config, category, cap=None):
return P.Record(category=category, domain="multilingual" if category == "german" else "longctx",
source=f"{config[0]}:{config[1]}", license="CC-BY-SA-4.0",
license_url="https://creativecommons.org/licenses/by-sa/4.0/", path=f"wiki/de/{r['id']}",
lang="de", origin="wikipedia", text=wiki_text(r, cap),
provenance={"url": r["url"], "collector": "tools/pool_german.py"})
# ---------------------------------------------------------------- chats
OASST2_FILE = "2023-11-05_oasst2_ready.messages.jsonl.gz"
def oasst2_messages(cache):
"""The German messages of the OASST2 release file (the datasets-server filter answers 500 on it)."""
import gzip
path = os.path.join(cache, OASST2_FILE)
if not os.path.exists(path):
os.makedirs(cache, exist_ok=True)
urllib.request.urlretrieve(f"https://huggingface.co/datasets/OpenAssistant/oasst2/resolve/main/{OASST2_FILE}", path)
with gzip.open(path, "rt", encoding="utf-8") as f:
for line in f:
m = json.loads(line)
if m.get("lang") == "de":
yield m
def oasst2_threads(cache):
msgs = [m for m in oasst2_messages(cache)
if str(m.get("deleted")) != "True" and str(m.get("review_result")) != "False"]
by_id = {m["message_id"]: m for m in msgs}
kids = {}
for m in msgs:
kids.setdefault(m["parent_id"], []).append(m)
def rank(m):
r = m.get("rank")
return int(r) if r not in (None, "None", "") else 99
for root in (m for m in msgs if m["parent_id"] in (None, "None") and m["role"] == "prompter"):
path, cur = [root], root
while kids.get(cur["message_id"]):
cur = sorted(kids[cur["message_id"]], key=rank)[0]
path.append(cur)
if len(path) < 2:
continue
if path[-1]["role"] == "prompter":
path = path[:-1]
yield root["message_tree_id"], [{"role": "user" if m["role"] == "prompter" else "assistant",
"content": m["text"]} for m in path if m["message_id"] in by_id]
def chat_record(source, lic, url, path, messages, origin, strength="none", tools=None):
return P.Record(category="german", domain="chat", source=source, license=lic, license_url=url, path=path,
lang="de", origin=origin, render="chat", messages=messages, tools=tools,
reasoning_strength=strength, provenance={"collector": "tools/pool_german.py"})
def ultrachat_records():
total = get("size", dataset="bjoernp/ultrachat_de")["size"]["dataset"]["num_rows"]
for off in range(0, total, 100):
for r in rows("bjoernp/ultrachat_de", "default", off):
conv = maybe_list(r["conversations"])
role = {"system": "system", "human": "user", "gpt": "assistant"}
msgs = [{"role": role[c["from"]], "content": c["value"]} for c in conv if c.get("from") in role]
if len(msgs) >= 2 and msgs[-1]["role"] == "assistant":
yield chat_record("bjoernp/ultrachat_de", "MIT", "https://opensource.org/licenses/MIT",
f"ultrachat_de/{r['prompt_id'][:16]}", msgs, "ultrachat_de")
def germanrag_records(rng):
total = get("size", dataset="DiscoResearch/germanrag")["size"]["dataset"]["num_rows"]
for off in range(0, total, 100):
for i, r in enumerate(rows("DiscoResearch/germanrag", "default", off)):
ctx = maybe_list(r["contexts"])
docs = "\n\n".join(f"Dokument {k + 1}:\n{c}" for k, c in enumerate(ctx))
msgs = [{"role": "system", "content": "Beantworte die Frage ausschließlich anhand der Dokumente. "
"Wenn sie die Antwort nicht enthalten, sag das."},
{"role": "user", "content": f"{docs}\n\nFrage: {r['question']}"},
{"role": "assistant", "content": r["answer"]}]
yield chat_record("DiscoResearch/germanrag", "CC-BY-4.0", "https://creativecommons.org/licenses/by/4.0/",
f"germanrag/{off + i}", msgs, "germanrag", strength=rng.choice(["none", "low", "medium"]))
# ---------------------------------------------------------------- agentic, from templates
CITIES = ["Berlin", "München", "Hamburg", "Köln", "Frankfurt am Main", "Stuttgart", "Leipzig", "Dresden", "Nürnberg",
"Hannover", "Bremen", "Düsseldorf", "Freiburg im Breisgau", "Heidelberg", "Wien", "Graz", "Zürich", "Basel"]
TOOLS = {
"wetter": {"type": "function", "function": {"name": "wetter_abfragen", "description": "Aktuelles Wetter und Vorhersage für einen Ort",
"parameters": {"type": "object", "properties": {"ort": {"type": "string"}, "tage": {"type": "integer", "description": "Vorhersage in Tagen, 0 = heute"},
"einheit": {"type": "string", "enum": ["celsius", "fahrenheit"]}}, "required": ["ort"]}}},
"bahn": {"type": "function", "function": {"name": "verbindung_suchen", "description": "Zugverbindungen zwischen zwei Bahnhöfen",
"parameters": {"type": "object", "properties": {"von": {"type": "string"}, "nach": {"type": "string"}, "datum": {"type": "string", "description": "JJJJ-MM-TT"},
"abfahrt_ab": {"type": "string", "description": "HH:MM"}, "nur_direkt": {"type": "boolean"}}, "required": ["von", "nach", "datum"]}}},
"termin": {"type": "function", "function": {"name": "termin_anlegen", "description": "Legt einen Termin im Kalender an",
"parameters": {"type": "object", "properties": {"titel": {"type": "string"}, "beginn": {"type": "string", "description": "ISO 8601"},
"dauer_minuten": {"type": "integer"}, "teilnehmer": {"type": "array", "items": {"type": "string"}},
"ort": {"type": "string"}}, "required": ["titel", "beginn"]}}},
"rechnung": {"type": "function", "function": {"name": "rechnung_berechnen", "description": "Summe, Mehrwertsteuer und Gesamtbetrag einer Rechnung",
"parameters": {"type": "object", "properties": {"positionen": {"type": "array", "items": {"type": "object", "properties": {
"bezeichnung": {"type": "string"}, "menge": {"type": "number"}, "einzelpreis": {"type": "number"}}}},
"mwst_satz": {"type": "number", "description": "z. B. 19 oder 7"}}, "required": ["positionen", "mwst_satz"]}}},
"dateien": {"type": "function", "function": {"name": "dateien_suchen", "description": "Sucht Dateien im Projektordner nach Name oder Inhalt",
"parameters": {"type": "object", "properties": {"muster": {"type": "string"}, "pfad": {"type": "string"}, "inhalt": {"type": "boolean"}}, "required": ["muster"]}}},
"suche": {"type": "function", "function": {"name": "websuche", "description": "Websuche, liefert Titel, Ausschnitt und Adresse",
"parameters": {"type": "object", "properties": {"anfrage": {"type": "string"}, "anzahl": {"type": "integer"}, "sprache": {"type": "string"}}, "required": ["anfrage"]}}},
}
def _call(i, name, args):
return {"id": f"call_{i:03d}", "type": "function", "function": {"name": name, "arguments": args}}
def agentic_de(rng, n):
for k in range(n):
kind = rng.choice(["wetter2", "bahn", "termin", "rechnung", "dateien_fehler", "suche"])
day = rng.randint(1, 28)
month = rng.randint(1, 12)
if kind == "wetter2":
a, b = rng.sample(CITIES, 2)
t = rng.choice([0, 1, 2])
calls = [_call(1, "wetter_abfragen", {"ort": a, "tage": t}), _call(2, "wetter_abfragen", {"ort": b, "tage": t})]
ta, tb = rng.randint(-3, 31), rng.randint(-3, 31)
res = [{"ort": a, "temperatur": ta, "lage": rng.choice(["sonnig", "bewölkt", "Regen", "Schauer"])},
{"ort": b, "temperatur": tb, "lage": rng.choice(["sonnig", "bewölkt", "Regen", "Nebel"])}]
ask = f"Wie wird das Wetter {['heute', 'morgen', 'übermorgen'][t]} in {a} und in {b}? Wo ist es wärmer?"
ans = f"In {a} werden {ta} °C erwartet ({res[0]['lage']}), in {b} {tb} °C ({res[1]['lage']}). " + \
(f"{a} ist wärmer." if ta > tb else f"{b} ist wärmer." if tb > ta else "Beide Orte sind gleich warm.")
tools = [TOOLS["wetter"]]
elif kind == "bahn":
a, b = rng.sample(CITIES[:14], 2)
hh = rng.randint(5, 21)
calls = [_call(1, "verbindung_suchen", {"von": a, "nach": b, "datum": f"2026-{month:02d}-{day:02d}",
"abfahrt_ab": f"{hh:02d}:00", "nur_direkt": rng.random() < 0.3})]
dur = rng.randint(60, 420)
res = [{"verbindungen": [{"abfahrt": f"{hh:02d}:{m:02d}", "dauer_minuten": dur + d, "umstiege": u}
for m, d, u in ((rng.randint(0, 59), 0, rng.randint(0, 2)), (rng.randint(0, 59), rng.randint(5, 40), 1))]}]
ask = f"Ich muss am {day}.{month}. von {a} nach {b}, frühestens um {hh} Uhr. Was gibt es?"
v = res[0]["verbindungen"][0]
ans = f"Die erste passende Verbindung fährt um {v['abfahrt']} und braucht {v['dauer_minuten'] // 60} Stunden " \
f"{v['dauer_minuten'] % 60} Minuten mit {v['umstiege']} Umstieg(en)."
tools = [TOOLS["bahn"], TOOLS["wetter"]]
elif kind == "termin":
who = rng.sample(["Anna", "Jonas", "Leonie", "Mehmet", "Sophie", "Lukas", "Fatima", "Paul"], rng.randint(1, 3))
hh = rng.randint(8, 17)
calls = [_call(1, "termin_anlegen", {"titel": rng.choice(["Projektbesprechung", "Quartalsplanung", "Arzttermin", "Kundengespräch"]),
"beginn": f"2026-{month:02d}-{day:02d}T{hh:02d}:30:00", "dauer_minuten": rng.choice([30, 45, 60, 90]),
"teilnehmer": who})]
res = [{"status": "angelegt", "id": f"evt-{rng.randint(1000, 9999)}"}]
ask = f"Trag mir bitte am {day}.{month}. um {hh}:30 einen Termin mit {', '.join(who)} ein, Titel {calls[0]['function']['arguments']['titel']}."
ans = f"Erledigt: Der Termin steht am {day}.{month}. um {hh}:30 im Kalender (ID {res[0]['id']})."
tools = [TOOLS["termin"]]
elif kind == "rechnung":
pos = [{"bezeichnung": rng.choice(["Beratung", "Lizenz", "Wartung", "Schulung", "Material"]),
"menge": rng.randint(1, 12), "einzelpreis": round(rng.uniform(20, 400), 2)} for _ in range(rng.randint(2, 4))]
satz = rng.choice([19, 7])
netto = round(sum(p["menge"] * p["einzelpreis"] for p in pos), 2)
calls = [_call(1, "rechnung_berechnen", {"positionen": pos, "mwst_satz": satz})]
res = [{"netto": netto, "mwst": round(netto * satz / 100, 2), "brutto": round(netto * (1 + satz / 100), 2)}]
ask = "Rechne mir bitte diese Rechnung aus: " + "; ".join(f"{p['menge']}× {p['bezeichnung']} zu {p['einzelpreis']:.2f} €" for p in pos) + f", {satz} % MwSt."
ans = f"Netto {netto:.2f} €, MwSt. {res[0]['mwst']:.2f} €, brutto {res[0]['brutto']:.2f} €."
tools = [TOOLS["rechnung"]]
elif kind == "dateien_fehler":
name = rng.choice(["konfiguration", "rechnung", "bericht", "export"])
calls = [_call(1, "dateien_suchen", {"muster": f"{name}*.yml", "pfad": "/projekt/einstellungen"})]
res = [{"fehler": "Pfad existiert nicht", "pfad": "/projekt/einstellungen"}]
calls2 = [_call(2, "dateien_suchen", {"muster": f"{name}*.yml", "pfad": "/projekt/config"})]
res2 = [{"treffer": [f"/projekt/config/{name}.yml", f"/projekt/config/{name}_alt.yml"]}]
ask = f"Wo liegt bei uns die {name}-Datei im YAML-Format?"
ans = f"Der Ordner /projekt/einstellungen existiert nicht; unter /projekt/config liegen {name}.yml und {name}_alt.yml."
tools = [TOOLS["dateien"]]
msgs = [{"role": "user", "content": ask},
{"role": "assistant", "content": "", "tool_calls": calls},
{"role": "tool", "tool_call_id": "call_001", "content": json.dumps(res[0], ensure_ascii=False)},
{"role": "assistant", "content": "", "tool_calls": calls2},
{"role": "tool", "tool_call_id": "call_002", "content": json.dumps(res2[0], ensure_ascii=False)},
{"role": "assistant", "content": ans}]
yield chat_record("synthetic/agentic_de", "CC0-1.0 (generated)", "", f"agentic_de/{kind}/{k}", msgs,
"synth_agentic_de", rng.choice(["none", "low", "medium"]), tools)
continue
else:
q = rng.choice(["Öffnungszeiten Pergamonmuseum", "Rentenerhöhung 2026", "Fahrradstraße Regeln", "Grundsteuerreform Frist"])
calls = [_call(1, "websuche", {"anfrage": q, "anzahl": 3, "sprache": "de"})]
res = [{"ergebnisse": [{"titel": f"{q} – Überblick", "ausschnitt": f"Aktuelle Informationen zu {q}.", "adresse": "https://example.org/a"}]}]
ask = f"Such mir bitte etwas zu: {q}."
ans = f"Ich habe einen Überblick gefunden: „{q} – Überblick“ (https://example.org/a)."
tools = [TOOLS["suche"]]
msgs = [{"role": "user", "content": ask}, {"role": "assistant", "content": "", "tool_calls": calls}]
msgs += [{"role": "tool", "tool_call_id": c["id"], "content": json.dumps(r, ensure_ascii=False)} for c, r in zip(calls, res)]
msgs.append({"role": "assistant", "content": ans})
yield chat_record("synthetic/agentic_de", "CC0-1.0 (generated)", "", f"agentic_de/{kind}/{k}", msgs,
"synth_agentic_de", rng.choice(["none", "low", "medium"]), tools)
# ---------------------------------------------------------------- main
def take(gen, chars):
out, got = [], 0
for rec in gen:
if got >= chars:
break
out.append(rec)
got += len(rec.text or json.dumps(rec.messages, ensure_ascii=False))
return out, got
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--seed", type=int, default=20261006)
ap.add_argument("--tokens", type=int, default=1_250_000, help="German tokens for the pool (category german)")
ap.add_argument("--eval-tokens", type=int, default=350_000)
ap.add_argument("--repo", default=P.REPO_ROOT)
a = ap.parse_args()
rng = random.Random(a.seed)
out = os.path.join(a.repo, "pool", "german")
os.makedirs(out, exist_ok=True)
budget = {"wikipedia": 0.36, "ultrachat_de": 0.26, "germanrag": 0.16, "oasst2": 0.12, "agentic_de": 0.10}
chars = {k: int(v * a.tokens * CHARS_PER_TOKEN) for k, v in budget.items()}
n_de = get("size", dataset=WIKI_DE[0], config=WIKI_DE[1])["size"]["config"]["num_rows"]
pool_off = wiki_offsets(rng, n_de, 120)
eval_off = wiki_offsets(random.Random(a.seed + 1), n_de, 60, avoid=pool_off)
seen = set()
# pool: Wikipedia DE, long articles to german_longctx
wiki, longs, got = [], [], 0
for r in wiki_sample(WIKI_DE, pool_off, seen):
n = len(r["text"])
if n >= 16000 * CHARS_PER_TOKEN and len(longs) < 24:
longs.append(wiki_record(r, WIKI_DE, "german_longctx"))
elif n >= 800 and got < chars["wikipedia"]:
# many articles, each cut at ~6000 characters: expert coverage wants breadth, not depth
rec = wiki_record(r, WIKI_DE, "german", cap=6000)
wiki.append(rec)
got += len(rec.text)
print(f"wikipedia: {len(wiki)} articles, {got:,} chars; long: {len(longs)}")
P.write_jsonl(os.path.join(out, "wikipedia.jsonl"), wiki)
P.write_jsonl(os.path.join(a.repo, "pool", "german", "longctx.jsonl"), longs)
for name, gen in (("ultrachat_de", ultrachat_records()), ("germanrag", germanrag_records(rng)),
("oasst2", (chat_record("OpenAssistant/oasst2", "Apache-2.0", "https://www.apache.org/licenses/LICENSE-2.0",
f"oasst2/{tid}", m, "oasst2") for tid, m in oasst2_threads(os.path.join(a.repo, ".cache")))),
("agentic_de", agentic_de(rng, 2000))):
recs, got = take(gen, chars[name])
P.write_jsonl(os.path.join(out, f"{name}.jsonl"), recs)
print(f"{name}: {len(recs)} records, {got:,} chars")
# eval: German prose from offsets the pool never read
ev, got = [], 0
for r in wiki_sample(WIKI_DE, eval_off, seen):
if 3000 <= len(r["text"]) <= 60000:
ev.append(wiki_text(r))
got += len(r["text"])
if got >= a.eval_tokens * CHARS_PER_TOKEN:
break
d = os.path.join(a.repo, "eval", "neutral-de")
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "eval_neutral-de.txt"), "w", encoding="utf-8", newline="") as f:
f.write("\n\n".join(ev) + "\n")
print(f"eval/neutral-de: {len(ev)} articles, {got:,} chars")
# eval: long articles, German then English, ~140k tokens each, from their own offsets
lo = []
for config, off_seed, cpt in ((WIKI_DE, a.seed + 2, CHARS_PER_TOKEN), (WIKI_EN, a.seed + 3, 4.0)):
n_total = get("size", dataset=config[0], config=config[1])["size"]["config"]["num_rows"]
got = 0
for r in wiki_sample(config, wiki_offsets(random.Random(off_seed), n_total, 300), seen):
if len(r["text"]) >= 12000 * cpt:
lo.append(wiki_text(r))
got += len(r["text"]) / cpt
if got >= 140_000:
break
print(f"eval/longctx {config[1]}: {got:,.0f} tokens")
d = os.path.join(a.repo, "eval", "longctx")
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "eval_longctx.txt"), "w", encoding="utf-8", newline="") as f:
f.write("\n\n".join(lo) + "\n")
print(f"eval/longctx: {len(lo)} documents")
return 0
if __name__ == "__main__":
sys.exit(main())