hr-wiki-instruct / code /build.py
Shome's picture
Initial release
b8c56f2 verified
Raw History Blame Contribute Delete
24.2 kB
"""MiniMind mid-training set v1 (25 Nov 2026): question/answer, instruction and arithmetic documents for a short base
stage between base v7 and SFT (OLMo 3 "midtraining" idea, scaled to a 122M model). No API, no teacher model.
python build.py -> parts/<name>.jsonl.gz, build.json
Parts (each row: {"id", "messages"} rendered later with the SFT chat template, or {"id", "text"} plain):
hr-wiki-qa Croatian Wikipedia (v1 release *train* split only, minus v1-rescreen ids): definition questions from the
lead sentence ("Što je X?" / "Tko je bio X?"), "Ukratko opiši X." and section-listing over the article.
hr-wiktionary hr Wiktionary Croatian entries: meanings, declension forms and tables, synonyms, English translations.
hr-arith templated arithmetic word problems in Croatian (and 30% English) with computed answers; Croatian number
agreement uses Wiktionary declension tables (1 jabuka, 2 jabuke, 5 jabuka; 2 stola, 5 stolova).
chat-sft the existing SFT inputs (posttraining-v1 trainer-inputs/sft.jsonl + Hy4 train), unchanged.
en-dolmino-* English slices of allenai/dolma3_dolmino_mix-100B-1025 (ODC-BY): tinymath-mind, tulu-3-sft,
wiki_to_rcqa, flan, sampled.
Every row is screened against the evaluation automaton (curated-v2 reserved-v2.pkl + SFT dialogue/probe prompts);
rows with any 10-word hit are dropped.
"""
import bz2
import glob
import gzip
import io
import json
import random
import re
import sys
import unicodedata
from pathlib import Path
HERE = Path(__file__).resolve().parent
D = HERE.parent
V1 = D / 'minimind-pretrain-curated-v1'
V2 = D / 'minimind-pretrain-curated-v2'
P = D.parent / 'prepared'
sys.path.insert(0, str(V1 / 'deps'))
sys.path.insert(0, str(V1))
import pickle # noqa: E402
import ahocorasick # noqa: E402,F401
import subprocess # noqa: E402
from screen import normal, strings # noqa: E402
SEED = 251125
WIKT = Path('sources/wikimedia-hr-20261124/hrwiktionary-latest-pages-articles.xml.bz2')
DOLMINO = Path('sources/dolmino-slices/data')
EN_BUDGET_CHARS = {'tinymath-mind': 12e6, 'tulu-3-sft': 10e6, 'wiki_to_rcqa-part1': 8e6, 'dolmino_1-flan': 6e6} # ~9M tokens: Croatian stays the majority
# ---------------------------------------------------------------- screen
def load_screen():
auto = pickle.load(open(V2 / 'work/reserved-v2.pkl', 'rb'))
n = 0
for f in glob.glob(str(P / 'minimind-posttraining-v6/evaluation/sft/dialogues/*.json')) + \
glob.glob(str(P / 'minimind-posttraining-v6/evaluation/sft/probes/*.json')):
d = json.load(open(f))
texts = [t['user'] for t in d.get('turns', [])] + [m.get('content', '') for m in d.get('history', [])]
for t in texts:
w = normal(t).split()
for i in range(0, max(0, len(w) - 9), 2):
auto.add_word(' ' + ' '.join(w[i:i + 10]) + ' ', True)
n += 1
auto.make_automaton()
return auto, n
def clean_hit(auto, row):
text = ' ' + normal(' '.join(strings(row.get('messages') or row.get('text')))) + ' '
return next(auto.iter(text), None) is None
# ---------------------------------------------------------------- Wikipedia QA
SENT = re.compile(r'(?<=[a-zčćžšđ0-9\)])\.\s+(?=[A-ZČĆŽŠĐ])')
LEAD = re.compile(r'^(?P<s>[^.()]{2,70}?)\s*(?P<par>\([^)]{0,120}\))?\s*,?\s+(?P<v>je|su|bio je|bila je|bilo je|bili su)\s')
PERSON = re.compile(r'\(\s*(?:rođen|rođena|\d{1,2}\.\s*\w+\s*)?\d{3,4}\.?\s*[–-]|\(rođen|\(rođena|\(rođ\.')
HEADING = re.compile(r'^[A-ZČĆŽŠĐ][^.!?:;]{2,60}\.$')
def sentences(par, k):
out = SENT.split(par.strip())
return '. '.join(out[:k]).rstrip('.') + '.'
BAD_SUBJ = {'koji', 'koja', 'koje', 'kojeg', 'kojem', 'što', 'se', 'su', 'a', 'da', 'kao', 'od', 'na', 'u', 'iz', 'prema'}
def complete(text):
last = re.split(r'\.\s+', text.rstrip('.'))[-1]
return not text.rstrip('.').endswith(':') and len(last.split()) >= 4
def subject_form(s, body):
first = s.split()[0]
low = first[0].lower() + first[1:]
if first.isupper() or not first[0].isupper():
return s
if re.search(r'\b' + re.escape(low) + r'\b', body):
return low + s[len(first):]
return s
def wiki_qa(rng, skip):
rows = []
for line in gzip.open(V1 / 'release/train/hr-wikipedia.jsonl.gz', 'rt'):
d = json.loads(line)
if d['id'] in skip:
continue
lines = [l for l in d['text'].split('\n') if l.strip()]
lead = lines[0]
m = LEAD.match(lead)
if not m or len(m['s'].split()) > 8 or re.search(r'\d{3}', m['s']):
continue
sw = m['s'].split()
if set(w.lower() for w in sw) & BAD_SUBJ or (len(sw) >= 2 and sw[-1][0].islower() and any(w[0].isupper() for w in sw[1:-1])):
continue
body = d['text'][len(lead):]
s = subject_form(m['s'].strip(' ,'), body)
person = bool(PERSON.search(lead[:200]))
past = m['v'] in ('bio je', 'bila je', 'bilo je', 'bili su') or bool(re.search(r'[–-]\s*\d{1,2}?\.?\s*\w*\s*\d{3,4}', lead[:120]))
if person:
q = rng.choice([f'Tko je bio {s}?' if past else f'Tko je {s}?', f'Reci mi nešto o osobi: {s}.'])
else:
q = rng.choice([f'Što je {s}?', f'Što je to {s}?', f'Objasni ukratko što je {s}.'])
answer = sentences(lead, 2)
if len(answer.split()) < 6 or len(answer.split()) > 90 or not complete(answer):
continue
rows.append(dict(id=d['id'] + ':def', messages=[dict(role='user', content=q), dict(role='assistant', content=answer)]))
heads = [l.rstrip('.') for l in lines[1:] if HEADING.match(l) and len(l.split()) <= 6]
heads = [h for h in heads if h.lower() not in ('izvori', 'vanjske poveznice', 'literatura', 'bilješke', 'vidi još', 'galerija')]
art = '\n'.join(lines)
if len(heads) >= 3 and len(art.split()) <= 700 and rng.random() < 0.5:
rows.append(dict(id=d['id'] + ':sec', messages=[
dict(role='user', content=art + '\n\nKoja su glavna poglavlja ovog teksta? Navedi samo naslove.'),
dict(role='assistant', content='\n'.join(f'{i}. {h}' for i, h in enumerate(heads, 1)))]))
elif len(lead.split()) >= 25 and rng.random() < 0.4:
rows.append(dict(id=d['id'] + ':opis', messages=[
dict(role='user', content=rng.choice([f'Ukratko opiši: {s}.', f'Napiši kratak opis teme „{s}”.'])),
dict(role='assistant', content=sentences(lead, 4))]))
if not complete(rows[-1]['messages'][1]['content']):
rows.pop()
return rows
# ---------------------------------------------------------------- Wiktionary
LINK = re.compile(r'\[\[(?:[^\]|]*\|)?([^\]]*)\]\]')
CASES = [('N', 'nominativ'), ('G', 'genitiv'), ('D', 'dativ'), ('A', 'akuzativ'), ('V', 'vokativ'), ('L', 'lokativ'), ('I', 'instrumental')]
ROD = {'m': 'muški rod', 'ž': 'ženski rod', 's': 'srednji rod'}
def wtext(s):
s = LINK.sub(r'\1', s)
s = re.sub(r"'{2,}", '', s)
s = re.sub(r'\{\{[^{}]*\}\}', '', s)
s = re.sub(r'<[^>]+>|&lt;.*?&gt;', '', s)
return re.sub(r'\s+', ' ', s).strip(' ,;')
def strip_len(s):
return unicodedata.normalize('NFC', ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'
or c in '\u030c\u0301')).replace('ā', 'a')
def wiktionary_entries():
page, out = [], []
with bz2.open(WIKT, 'rt', encoding='utf-8') as f:
for line in f:
page.append(line)
if '</page>' in line:
p = ''.join(page)
page = []
if '<ns>0</ns>' not in p:
continue
title = re.search(r'<title>(.*?)</title>', p)[1]
m = re.search(r'== *' + re.escape(title) + r' *\(\{\{hrvatski jezik\}\}\) *==(.*?)(?:\n== |\Z)', p, re.S)
if not m or ' ' in title or len(title) < 2 or not re.fullmatch(r"[a-zčćžšđA-ZČĆŽŠĐ'-]+", title):
continue
sec = m[1].replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"').replace('&amp;', '&')
e = dict(word=title)
defs = re.search(r'\{\{definicija\}\}(.*?)(?:\n\{\{(?!imenica|glagol|pridjev|prilog)[a-zčćžš ]+\}\}|\Z)', sec, re.S)
if defs:
e['pos'] = re.search(r'\{\{(imenica|glagol|pridjev|prilog|zamjenica|broj|prijedlog|veznik|uzvik|čestica)', defs[1])
e['pos'] = e['pos'][1] if e['pos'] else None
r = re.search(r'rod=([mžs])', defs[1])
e['rod'] = r[1] if r else None
lab = re.sub(r'\{\{\s*(kajkavski|čakavski|regionalno|dijalektalno|dijalektalizam|arhaizam|zastarjelo)\s*\}\}', r'(\1)', defs[1])
e['defs'] = [wtext(x).rstrip('.') for x in re.findall(r'^:\s*\(\d+\.\d+\)\s*(.+)$', lab, re.M)]
e['defs'] = [x for x in e['defs'] if 3 <= len(x) <= 300 and 'ISO 639' not in x]
dec = re.search(r'\{\{deklinacija(.*?)\}\}', sec, re.S)
if dec:
forms = dict(re.findall(r'\|\s*([NGDAVLI](?:mn)?)\s*=\s*([^|}\n]+)', dec[1]))
e['forms'] = {k: strip_len(v.strip()) for k, v in forms.items() if v.strip() and '{' not in v}
syn = re.search(r'\{\{sinonimi\}\}\s*\n:\s*(?:\(\d[^)]*\)\s*)?(.+)', sec)
if syn:
e['syn'] = [w for w in (wtext(x) for x in re.split(r',', re.sub(r'\(.*?\)', '', syn[1]))) if w and len(w) < 30][:6]
e['en'] = [x for x in dict.fromkeys(re.findall(r'\{\{pr\|en\|([^|}]+)', p)) if x.lower() != title.lower()][:3]
out.append(e)
return out
def wiktionary_qa(rng, entries):
rows = []
for e in entries:
w = e['word']
if e.get('defs'):
kind = {'imenica': 'imenica', 'glagol': 'glagol', 'pridjev': 'pridjev', 'prilog': 'prilog'}.get(e.get('pos'))
head = f'Riječ „{w}”' + (f' ({kind}{", " + ROD[e["rod"]] if kind == "imenica" and e.get("rod") else ""})' if kind else '')
body = e['defs'][0] + '.' if len(e['defs']) == 1 else ' značenja:\n' + '\n'.join(f'{i}. {x}' for i, x in enumerate(e['defs'], 1))
ans = f'{head} znači: {body}' if len(e['defs']) == 1 else f'{head} ima ova{body}'
rows.append(dict(id=f'wikt:{w}:def', messages=[dict(role='user', content=rng.choice(
[f'Što znači riječ „{w}”?', f'Objasni značenje riječi „{w}”.', f'Što je „{w}”?'])), dict(role='assistant', content=ans)]))
f = e.get('forms') or {}
if e.get('pos') == 'imenica' and len(f) >= 10:
c, name = rng.choice(CASES[1:])
num, suf = rng.choice([('', 'jednine'), ('mn', 'množine')])
if f.get(c + num):
rows.append(dict(id=f'wikt:{w}:{c}{num}', messages=[
dict(role='user', content=f'Kako glasi {name} {suf} imenice „{w}”?'),
dict(role='assistant', content=f'{name.capitalize()} {suf} imenice „{w}” glasi „{f[c + num]}”.')]))
if rng.random() < 0.35 and all(f.get(k + num) for k, _ in CASES):
tbl = '\n'.join(f'{n}: {f[k + num]}' for k, n in CASES)
rows.append(dict(id=f'wikt:{w}:tbl{num}', messages=[
dict(role='user', content=f'Sklonidbu imenice „{w}” napiši u {"jednini" if not num else "množini"}.'),
dict(role='assistant', content=tbl)]))
if e.get('syn'):
rows.append(dict(id=f'wikt:{w}:syn', messages=[
dict(role='user', content=f'Navedi sinonime za riječ „{w}”.'),
dict(role='assistant', content=f'Sinonimi za „{w}” su: {", ".join(e["syn"])}.' if len(e['syn']) > 1
else f'Sinonim za „{w}” je „{e["syn"][0]}”.')]))
if e.get('en'):
en = ', '.join(e['en'])
if rng.random() < 0.5:
rows.append(dict(id=f'wikt:{w}:en', messages=[dict(role='user', content=f'Kako se na engleskom kaže „{w}”?'),
dict(role='assistant', content=f'„{w}” se na engleskom kaže: {en}.')]))
else:
rows.append(dict(id=f'wikt:{w}:en2', messages=[dict(role='user', content=f'What is the Croatian word for "{e["en"][0]}"?'),
dict(role='assistant', content=f'The Croatian word for "{e["en"][0]}" is "{w}".')]))
return rows
# ---------------------------------------------------------------- arithmetic
NAMES = [('Ana', 'ž'), ('Marko', 'm'), ('Iva', 'ž'), ('Luka', 'm'), ('Petra', 'ž'), ('Ivan', 'm'), ('Maja', 'ž'), ('Josip', 'm'),
('Lucija', 'ž'), ('Filip', 'm'), ('Ema', 'ž'), ('Karlo', 'm'), ('Nika', 'ž'), ('Davor', 'm'), ('Tena', 'ž'), ('Ante', 'm')]
EN_NAMES = ['Anna', 'Mark', 'Eva', 'Luke', 'Sara', 'John', 'Mia', 'Paul', 'Lucy', 'Philip', 'Emma', 'Carl']
NOUN_TABLE = """
jabuka ž jabuka jabuke jabuku jabuci jabuke jabuka jabuke
knjiga ž knjiga knjige knjigu knjizi knjige knjiga knjige
olovka ž olovka olovke olovku olovci olovke olovaka olovke
bilježnica ž bilježnica bilježnice bilježnicu bilježnici bilježnice bilježnica bilježnice
kruška ž kruška kruške krušku kruški kruške krušaka kruške
naranča ž naranča naranče naranču naranči naranče naranča naranče
boca ž boca boce bocu boci boce boca boce
čaša ž čaša čaše čašu čaši čaše čaša čaše
žlica ž žlica žlice žlicu žlici žlice žlica žlice
karta ž karta karte kartu karti karte karata karte
lopta ž lopta lopte loptu lopti lopte lopti lopte
kocka ž kocka kocke kocku kocki kocke kocaka kocke
stolica ž stolica stolice stolicu stolici stolice stolica stolice
bombon m bombon bombona bombon bombonu bomboni bombona bombone
kolač m kolač kolača kolač kolaču kolači kolača kolače
cvijet m cvijet cvijeta cvijet cvijetu cvjetovi cvjetova cvjetove
tanjur m tanjur tanjura tanjur tanjuru tanjuri tanjura tanjure
ključ m ključ ključa ključ ključu ključevi ključeva ključeve
balon m balon balona balon balonu baloni balona balone
kamen m kamen kamena kamen kamenu kamenovi kamenova kamenove
sapun m sapun sapuna sapun sapunu sapuni sapuna sapune
jaje s jaje jajeta jaje jajetu jaja jaja jaja
pismo s pismo pisma pismo pismu pisma pisama pisma
kutija ž kutija kutije kutiju kutiji kutije kutija kutije
vrećica ž vrećica vrećice vrećicu vrećici vrećice vrećica vrećice
košara ž košara košare košaru košari košare košara košare
ladica ž ladica ladice ladicu ladici ladice ladica ladice
posuda ž posuda posude posudu posudi posude posuda posude
"""
NOUNS = {}
for _l in NOUN_TABLE.strip().splitlines():
_w, _rod, *_f = _l.split()
NOUNS[_w] = dict(zip(('N', 'G', 'A', 'L', 'Nmn', 'Gmn', 'Amn'), _f), rod=_rod)
CONT = ['kutija', 'vrećica', 'košara', 'ladica', 'posuda']
FITS = { # object -> sensible containers (no chairs in bags)
**{w: ['košara', 'kutija', 'vrećica', 'posuda'] for w in ('jabuka', 'kruška', 'naranča', 'kolač', 'bombon', 'jaje')},
**{w: ['kutija', 'ladica', 'vrećica'] for w in ('olovka', 'bilježnica', 'karta', 'kocka', 'ključ', 'sapun', 'pismo', 'žlica', 'balon')},
**{w: ['kutija', 'ladica'] for w in ('knjiga', 'čaša', 'tanjur', 'boca')},
}
OBJ = list(FITS)
PRICE = (1, 9)
EN_OBJ = ['apples', 'books', 'pencils', 'notebooks', 'pears', 'bottles', 'cups', 'cards', 'balls', 'chairs', 'candies', 'cakes',
'flowers', 'plates', 'keys', 'balloons', 'stones', 'eggs', 'letters']
def agree(n, f, case='N'):
"""Form of a noun after the number n (digits). case 'N' subject, 'A' object."""
rod = f['rod']
if n % 10 == 1 and n % 100 != 11:
return f['A'] if case == 'A' else f['N']
if n % 10 in (2, 3, 4) and n % 100 not in (12, 13, 14):
return f['Nmn'] if rod == 'ž' else f['G']
return f['Gmn']
def eur(n):
return 'euro' if n % 10 == 1 and n % 100 != 11 else 'eura'
def verb(g, m, z):
return z if g == 'ž' else m
def hr_problem(rng, nouns):
name, g = rng.choice(NAMES)
ow = rng.choice(OBJ)
o, c = nouns[ow], nouns[rng.choice(FITS[ow])]
t = rng.randrange(7)
if t == 0:
a, b = rng.randint(2, 60), rng.randint(2, 40)
q = f'{name} ima {a} {agree(a, o)}. {verb(g, "Dobio", "Dobila")} je još {b} {agree(b, o, "A")}. Koliko {o["Gmn"]} {name} sada ima?'
return q, f'{a} + {b} = {a + b}', a + b, f'{name} sada ima {a + b} {agree(a + b, o, "A")}.'
if t == 1:
a = rng.randint(10, 90); b = rng.randint(1, a - 1)
q = f'U {c["L"]} ima {a} {agree(a, o, "A")}. {name} je {verb(g, "uzeo", "uzela")} {b} {agree(b, o, "A")}. Koliko {o["Gmn"]} sada ima u {c["L"]}?'
return q, f'{a} - {b} = {a - b}', a - b, f'U {c["L"]} sada ima {a - b} {agree(a - b, o, "A")}.'
if t == 2:
a, b = rng.randint(2, 12), rng.randint(2, 12)
q = f'U svakoj {c["L"]} ima {a} {agree(a, o, "A")}. Koliko {o["Gmn"]} ima u {b} {agree(b, c)}?'
return q, f'{b} * {a} = {a * b}', a * b, f'U {b} {agree(b, c)} ima {a * b} {agree(a * b, o, "A")}.'
if t == 3:
k, b = rng.randint(2, 9), rng.randint(2, 12)
a = k * b
q = f'{name} ima {a} {agree(a, o)} i {verb(g, "želi", "želi")} ih jednako rasporediti u {b} {agree(b, c, "A")}. Koliko će {o["Gmn"]} biti u svakoj {c["L"]}?'
return q, f'{a} / {b} = {k}', k, f'U svakoj {c["L"]} bit će {k} {agree(k, o)}.'
if t == 4:
k = rng.randint(3, 8); a = rng.randint(k + 1, 70); full, rest = divmod(a, k)
q = f'{name} pakira {a} {agree(a, o, "A")} u {c["Amn"]}, po {k} u svaku. Koliko punih {c["Gmn"]} dobije i koliki je višak?'
return q, f'{a} = {full} * {k} + {rest}', f'{full}, višak {rest}', \
f'{name} napuni {full} {agree(full, c, "A")}, a višak je {rest}.' if rest else f'{name} napuni {full} {agree(full, c, "A")}, bez viška.'
if t == 5:
p = rng.randint(*PRICE); n = rng.randint(2, 9); pay = (p * n // 10 + 1) * 10
q = f'{o["N"].capitalize()} stoji {p} {eur(p)}. {name} kupuje {n} {agree(n, o, "A")} i daje {pay} {eur(pay)}. Koliko eura dobiva natrag?'
return q, f'{n} * {p} = {n * p}; {pay} - {n * p} = {pay - n * p}', pay - n * p, f'{name} dobiva natrag {pay - n * p} {eur(pay - n * p)}.'
h, mi = rng.randint(7, 18), rng.choice([0, 10, 15, 20, 30, 40, 45, 50]); d = rng.choice([25, 35, 40, 45, 50, 70, 75, 90, 105, 120])
e = h * 60 + mi + d
q = f'Sastanak počinje u {h}:{mi:02d} i traje {d} minuta. U koliko sati završava?'
return q, f'{h}:{mi:02d} + {d} min = {e // 60}:{e % 60:02d}', f'{e // 60}:{e % 60:02d}', f'Sastanak završava u {e // 60}:{e % 60:02d}.'
def en_problem(rng):
n, o = rng.choice(EN_NAMES), rng.choice(EN_OBJ)
t = rng.randrange(5)
if t == 0:
a, b = rng.randint(2, 60), rng.randint(2, 40)
return f'{n} has {a} {o} and gets {b} more. How many {o} does {n} have now?', f'{a} + {b} = {a + b}', a + b, f'{n} now has {a + b} {o}.'
if t == 1:
a = rng.randint(10, 90); b = rng.randint(1, a - 1)
return f'There are {a} {o} in a box. {n} takes out {b}. How many are left?', f'{a} - {b} = {a - b}', a - b, f'{a - b} {o} are left.'
if t == 2:
a, b = rng.randint(2, 12), rng.randint(2, 12)
return f'Each bag holds {a} {o}. How many {o} are in {b} bags?', f'{b} * {a} = {a * b}', a * b, f'There are {a * b} {o} in {b} bags.'
if t == 3:
k = rng.randint(3, 8); a = rng.randint(k + 1, 70); full, rest = divmod(a, k)
return (f'{n} packs {a} {o} into boxes of {k}. How many full boxes are there, and how many {o} are left over?',
f'{a} = {full} * {k} + {rest}', f'{full}, remainder {rest}', f'There {"is" if full == 1 else "are"} {full} full box{"" if full == 1 else "es"} and {rest} left over.')
p = rng.randint(2, 30); m = rng.randint(2, 9); pay = (p * m // 10 + 1) * 10
return (f'One item costs {p} euros. {n} buys {m} and pays with {pay} euros. How much change does {n} get?',
f'{m} * {p} = {m * p}; {pay} - {m * p} = {pay - m * p}', pay - m * p, f'{n} gets {pay - m * p} euros back.')
def arith(rng, entries, count):
nouns = NOUNS
rows = []
for i in range(count):
q, calc, ans, prose = en_problem(rng) if rng.random() < 0.3 else hr_problem(rng, nouns)
style = rng.random()
if style < 0.4:
a = f'<think>{calc}</think>\n{ans}'
elif style < 0.8:
a = f'{calc}. {prose}'
else:
a = str(ans)
rows.append(dict(id=f'arith:{i}', messages=[dict(role='user', content=q), dict(role='assistant', content=a)]))
return rows, sorted(nouns)
# ---------------------------------------------------------------- chats and English
def chats():
rows = []
for f, tag in ((D / 'minimind-posttraining-v1/trainer-inputs/sft.jsonl', 'pt1'),
(P / 'minimind-posttraining-v6/inputs/hy4-train.jsonl', 'hy4')):
for i, line in enumerate(open(f)):
rows.append(dict(id=f'{tag}:{i}', messages=json.loads(line)['conversations']))
return rows
def dolmino(rng, sub, budget):
files = sorted((DOLMINO / sub).glob('*.jsonl.zst'))
rng.shuffle(files)
rows, chars = [], 0
for f in files:
proc = subprocess.Popen(['zstd', '-dc', str(f)], stdout=subprocess.PIPE)
with proc.stdout as fh:
for line in io.TextIOWrapper(fh, encoding='utf-8'):
d = json.loads(line)
t = d.get('text', '')
if not t or len(t) > 20000:
continue
rows.append(dict(id=f'{sub}:{d.get("id", len(rows))}', text=t))
chars += len(t)
if chars >= budget:
proc.kill()
return rows
proc.wait()
return rows
def main():
rng = random.Random(SEED)
auto, nscreen = load_screen()
skip = set(json.loads((V2 / 'work/v1-rescreen.json').read_text()).get('hr-wikipedia', []))
entries = wiktionary_entries()
arith_rows, nouns = arith(rng, entries, 60000)
parts = {'hr-wiki-qa': wiki_qa(rng, skip), 'hr-wiktionary': wiktionary_qa(rng, entries), 'hr-arith': arith_rows, 'chat-sft': chats()}
for sub, b in EN_BUDGET_CHARS.items():
parts['en-dolmino-' + sub.split('-part')[0]] = dolmino(rng, sub, b)
(HERE / 'parts').mkdir(exist_ok=True)
report = dict(seed=SEED, screen_extra_windows=nscreen, wiktionary_hr_entries=len(entries), arith_nouns=nouns, parts={})
for name, rows in parts.items():
kept = [r for r in rows if clean_hit(auto, r)]
with gzip.open(HERE / 'parts' / f'{name}.jsonl.gz', 'wt', encoding='utf-8') as f:
for r in kept:
f.write(json.dumps(r, ensure_ascii=False) + '\n')
report['parts'][name] = dict(rows=len(rows), kept=len(kept), screened_out=len(rows) - len(kept),
chars=sum(len(' '.join(strings(r.get('messages') or r.get('text')))) for r in kept))
print(name, report['parts'][name], flush=True)
for name in ('hr-bible-chapters', 'hr-bible-qa'): # written by bible.py (run it first)
rows = [json.loads(l) for l in gzip.open(HERE / 'parts' / f'{name}.jsonl.gz', 'rt')]
kept = [r for r in rows if clean_hit(auto, r)]
with gzip.open(HERE / 'parts' / f'{name}.jsonl.gz', 'wt', encoding='utf-8') as f:
for r in kept:
f.write(json.dumps(r, ensure_ascii=False) + '\n')
report['parts'][name] = dict(rows=len(rows), kept=len(kept), screened_out=len(rows) - len(kept),
chars=sum(len(' '.join(strings(r.get('messages') or r.get('text')))) for r in kept))
print(name, report['parts'][name], flush=True)
(HERE / 'build.json').write_text(json.dumps(report, indent=1, ensure_ascii=False))
if __name__ == '__main__':
main()