Datasets:
Download code/scripts/build_validation_tasks.py from kuramot6f/classical-ja-pretrain: direct link, hf CLI and curl.
- Browser
- Download file 7.81 kB
-
https://huggingface.co/datasets/kuramot6f/classical-ja-pretrain/resolve/main/code/scripts/build_validation_tasks.py
- Command line
-
hf download hf://datasets/kuramot6f/classical-ja-pretrain/code/scripts/build_validation_tasks.py
-
curl -L -o build_validation_tasks.py https://huggingface.co/datasets/kuramot6f/classical-ja-pretrain/resolve/main/code/scripts/build_validation_tasks.py
7.81 kB
| """Freeze screened split-specific raw-text episodes, cloze and continuation tasks.""" | |
| import argparse | |
| from collections import Counter,defaultdict | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import re | |
| import sqlite3 | |
| from sentencepiece_unigram import Tokenizer,read_json,sha,write_json,now | |
| def rank(value): | |
| return hashlib.sha256(('20261024:'+value).encode()).hexdigest() | |
| def clean_passage(text): | |
| return (len(text)>=192 and not re.search(r'[\ufffd□〓{}]|https?://|Wikisource|ウィキソース|<ref|</ref',text,re.I) | |
| and sum(c.isalpha() for c in text)>=len(text)*.5) | |
| def main(): | |
| p=argparse.ArgumentParser(description=__doc__) | |
| p.add_argument('--output',type=Path) | |
| p.add_argument('--split',choices=['validation','test'],default='validation') | |
| p.add_argument('--final-test',action='store_true') | |
| a=p.parse_args() | |
| if a.split=='test' and not a.final_test:p.error('Test fixtures require --final-test after model selection') | |
| out=a.output or Path('unified/evaluation-tasks-v1')/(a.split+'-001') | |
| config=read_json(Path('scripts/pretrain_hf_config.json'))['evaluation_tasks'] | |
| split=Path('unified/training-tokens-v1/build-006') | |
| manifest=read_json(split/'manifest.json') | |
| if not manifest['complete'] or sha(split/'splits.jsonl')!=manifest['files']['splits.jsonl']: | |
| raise ValueError('Split metadata mismatch') | |
| with (split/'splits.jsonl').open() as f: | |
| selected=[r for r in map(json.loads,f) if r['split']==a.split and r['source'] in config['fixture_sources']] | |
| dbpath=Path('unified/pretrain-v1/build-002/build.sqlite3') | |
| dm=read_json(dbpath.parent/'manifest.json') | |
| if sha(dbpath)!=dm['output_sha256'][dbpath.name]: | |
| raise ValueError('Text database changed') | |
| db=sqlite3.connect('file:'+str(dbpath.resolve())+'?mode=ro',uri=True) | |
| tokenizer=Tokenizer(split/'tokenizer.model') | |
| pool=[];rejected=Counter() | |
| for r in selected: | |
| # Only IDs already whitelisted as validation are ever queried for text. | |
| text,metadata=db.execute('SELECT text,metadata FROM units WHERE id=?',(r['id'],)).fetchone() | |
| if hashlib.sha256(text.encode()).hexdigest()!=r['text_sha256']: | |
| raise ValueError('Source text identity mismatch') | |
| q=json.loads(metadata).get('quality',{}) | |
| original=q.get('original_quality') or {} | |
| norm=original.get('normalization') or {} | |
| if original.get('problematic_pages',0) or norm.get('missing_characters_removed',0): | |
| rejected['quality_flag']+=1;continue | |
| if any(re.search('markup|problematic|residual',flag,re.I) for flag in q.get('review_flags',[])): | |
| rejected['review_flag']+=1;continue | |
| starts=sorted({0,len(text)//4,len(text)//2,3*len(text)//4}) | |
| for start in starts: | |
| episode=text[start:start+config['raw_episode_max_characters']] | |
| if not clean_passage(episode): | |
| rejected['passage_screen']+=1;continue | |
| encoded=tokenizer.encode(episode) | |
| if 0 in encoded or tokenizer.decode(encoded)!=episode or len(encoded)>2048: | |
| rejected['tokenizer_roundtrip_or_length']+=1;continue | |
| n=config['prefix_characters'];length=config['continuation_characters'] | |
| gold=episode[n:n+length] | |
| if sum(c.isalpha() for c in gold)<length//2: | |
| rejected['target_screen']+=1;continue | |
| pool.append(dict(id=f"{r['id']}@{start}",source_id=r['id'],source=r['source'],era=r['era'], | |
| era_basis=r['era_basis'],group=r['group'],title=r['title'], | |
| text_sha256=r['text_sha256'],span_start=start, | |
| span_end=start+len(episode),raw_episode=episode,raw_characters=len(episode), | |
| prefix=episode[:n],cloze_gold=gold[:config['cloze_gold_characters']], | |
| continuation_gold=gold,review_status='automatically_screened_pending_manual_review')) | |
| db.close() | |
| chosen=[];group_count=Counter() | |
| for source in config['fixture_sources']: | |
| buckets=defaultdict(list) | |
| for row in pool: | |
| if row['source']==source:buckets[row['era'],row['group']].append(row) | |
| for values in buckets.values():values.sort(key=lambda r:rank(r['id'])) | |
| source_count=0 | |
| while source_count<config['examples_per_source']: | |
| progress=False | |
| for key in sorted(buckets,key=lambda k:(k[0],rank(k[1]))): | |
| values=buckets[key] | |
| if not values or group_count[key[1]]>=config['maximum_examples_per_work_group']:continue | |
| row=values.pop(0);chosen.append(row);group_count[key[1]]+=1;source_count+=1;progress=True | |
| if source_count==config['examples_per_source']:break | |
| if not progress:break | |
| if source_count<config['examples_per_source']: | |
| raise ValueError(f'Insufficient screened validation fixtures for {source}: {source_count}') | |
| for row in chosen: | |
| donors=sorted((r for r in pool if r['source']==row['source'] and r['era']==row['era'] | |
| and r['group']!=row['group'] and r['continuation_gold']!=row['continuation_gold']), | |
| key=lambda r:rank(row['id']+':'+r['id'])) | |
| unique=[];groups=set();texts={row['continuation_gold']} | |
| for donor in donors: | |
| if donor['group'] in groups or donor['continuation_gold'] in texts:continue | |
| unique.append(donor);groups.add(donor['group']);texts.add(donor['continuation_gold']) | |
| if len(unique)==3:break | |
| n=4 if len(unique)>=3 else (2 if unique else 0) | |
| if n: | |
| candidates=[dict(text=row['continuation_gold'],donor_id=row['source_id'],gold=True)] | |
| candidates += [dict(text=d['continuation_gold'],donor_id=d['source_id'],gold=False) for d in unique[:n-1]] | |
| candidates.sort(key=lambda d:rank(row['id']+':option:'+d['text'])) | |
| row['continuation_options']=[dict(text=d['text'],donor_id=d['donor_id']) for d in candidates] | |
| row['correct_option']=next(i for i,d in enumerate(candidates) if d['gold']) | |
| else: | |
| row['continuation_options']=[];row['correct_option']=None | |
| row['choice_count']=n | |
| row['episode_sha256']=hashlib.sha256(row['raw_episode'].encode()).hexdigest() | |
| out.mkdir(parents=True,exist_ok=False) | |
| with (out/'cases.jsonl').open('w') as f: | |
| for r in chosen:f.write(json.dumps(r,ensure_ascii=False)+'\n') | |
| summary=dict(cases=len(chosen),by_source=dict(Counter(r['source'] for r in chosen)), | |
| source_era_counts=dict(Counter(r['source']+'/'+r['era'] for r in chosen)), | |
| independent_groups=len({r['group'] for r in chosen}), | |
| choice_counts=dict(Counter(r['choice_count'] for r in chosen)), | |
| raw_characters=sum(r['raw_characters'] for r in chosen),screen_rejections=dict(rejected), | |
| status='screened_'+a.split+'_fixtures_pending_manual_clean_text_review', | |
| test_examples_created=len(chosen) if a.split=='test' else 0) | |
| write_json(out/'report.json',summary) | |
| write_json(out/'manifest.json',dict(complete=True,created=now(),split=a.split, | |
| split_manifest_sha256=sha(split/'manifest.json'),source_database_sha256=dm['output_sha256'][dbpath.name], | |
| tokenizer_sha256=manifest['tokenizer_sha256'],script_sha256=sha(__file__),recipe=config, | |
| scoring='prefix-only cloze; force token boundary before continuation; sum conditional candidate NLL; same-length choices; BPC scores whole raw episode from BOS excluding EOS', | |
| files={p.name:sha(p) for p in out.iterdir() if p.name!='manifest.json'})) | |
| print(json.dumps(summary,ensure_ascii=False,indent=2)) | |
| if __name__=='__main__':main() | |