luxfer / runtime /datasets /prepare.py
mdxss's picture
Publish Luxfer early beta with runnable weights and language metadata
7b6f2cc verified
Raw History Blame Contribute Delete
4.79 kB
"""Deterministic, source-grouped splits with explicit provenance and exclusion input."""
import argparse,hashlib,json,unicodedata
from pathlib import Path
def normalized(s): return ' '.join(unicodedata.normalize('NFKC',s).casefold().split())
def source_key(row): return hashlib.sha256(normalized(row['source']).encode()).hexdigest()
def document_key(row):
document=row.get('document_id')
if document is None:return None
identity=[row.get('provenance',''),row.get('revision',''),str(document)]
return hashlib.sha256(json.dumps(identity,ensure_ascii=False).encode()).hexdigest()
def prepare(rows, excluded=()):
seen=set(); partitions={'train':[],'validation':[],'test':[]}
excluded=list(excluded); blocked={source_key(r) for r in excluded}
blocked_docs={document_key(r) for r in excluded if document_key(r) is not None}
accepted=[];parent={}
def find(key):
parent.setdefault(key,key)
root=key
while parent[root]!=root:root=parent[root]
while parent[key]!=key:
nxt=parent[key];parent[key]=root;key=nxt
return root
def union(a,b):
a,b=find(a),find(b)
if a!=b:parent[max(a,b)]=min(a,b)
for row in rows:
if row.get('usage')=='evaluation_only' or row.get('dataset')=='FLORES+':
raise ValueError('Evaluation-only benchmarks cannot enter training preparation')
required=('source','target','source_lang','target_lang','license','provenance','revision')
if any(not isinstance(row.get(k),str) or not row[k].strip() for k in required):continue
if any('<|plamo:' in row[k] or '\x00' in row[k] for k in ('source','target')):continue
key=source_key(row);source_node='source:'+key
find(source_node)
doc=document_key(row)
if doc is not None:union(source_node,'doc:'+doc)
pair=(key,normalized(row['target']),row['source_lang'],row['target_lang'])
ratio=len(row['target'])/max(len(row['source']),1)
if pair in seen or not 0.05<ratio<20:continue
seen.add(pair);accepted.append(row)
# Exclude entire connected document groups if any source/document matches evaluation.
blocked_groups={find('source:'+source_key(r)) for r in accepted
if source_key(r) in blocked or document_key(r) in blocked_docs}
for row in accepted:
group=find('source:'+source_key(row))
if group in blocked_groups:continue
bucket=int(group.split(':',1)[1][:8],16)%100
split='test' if bucket<5 else 'validation' if bucket<10 else 'train'
partitions[split].append(row)
return partitions
if __name__=='__main__':
p=argparse.ArgumentParser(); p.add_argument('input'); p.add_argument('output'); p.add_argument('--exclude',required=True)
a=p.parse_args(); rows=lambda f:[json.loads(x) for x in Path(f).read_text().splitlines() if x.strip()]
out=Path(a.output); out.mkdir(parents=True,exist_ok=False)
for split,data in prepare(rows(a.input),rows(a.exclude)).items():
(out/(split+'.jsonl')).write_text(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in data))
def validate_training_partitions(train, validation, heldout, excluded=()):
"""Fail closed for known source overlap before allocating GPU model memory."""
if not train or not validation or not heldout:
raise ValueError('Require nonempty training, validation and held-out partitions')
groups=[{source_key(r) for r in data} for data in (train,validation,heldout)]
if any(groups[i]&groups[j] for i,j in ((0,1),(0,2),(1,2))):
raise ValueError('Source overlap between training, validation or held-out partitions')
docs=[{document_key(r) for r in data if document_key(r) is not None} for data in (train,validation,heldout)]
if any(docs[i]&docs[j] for i,j in ((0,1),(0,2),(1,2))):
raise ValueError('Document overlap between training, validation or held-out partitions')
excluded=list(excluded)
blocked={source_key(r) for r in excluded}
blocked_docs={document_key(r) for r in excluded if document_key(r) is not None}
if (docs[0]|docs[1])&blocked_docs:raise ValueError('Evaluation document found in training or validation')
if (groups[0]|groups[1])&blocked:
raise ValueError('Known evaluation source found in training or validation')
for data in (train,validation):
for row in data:
if row.get('usage')=='evaluation_only' or row.get('dataset')=='FLORES+':
raise ValueError('Evaluation-only benchmark found in training or validation')
if any(not isinstance(row.get(k),str) or not row[k].strip() for k in ('license','provenance','revision')):
raise ValueError('Training data requires license, provenance and revision metadata')