Download five_source_train/tools/restore_native_cache.py from haowu11/Delta-Ngram: direct link, hf CLI and curl.
- Browser
- Download file 3.9 kB
-
https://huggingface.co/datasets/haowu11/Delta-Ngram/resolve/main/five_source_train/tools/restore_native_cache.py
- Command line
-
hf download hf://datasets/haowu11/Delta-Ngram/five_source_train/tools/restore_native_cache.py
-
curl -L -o restore_native_cache.py https://huggingface.co/datasets/haowu11/Delta-Ngram/resolve/main/five_source_train/tools/restore_native_cache.py
3.9 kB
| """Restore the byte-identical native training cache from the dataset release. | |
| Usage: python restore_native_cache.py DATASET_ROOT/five_source_train/native_cache NEW_DIRECTORY | |
| Only the Python standard library is required. No model, tokenizer, or GPU is loaded. | |
| """ | |
| from array import array | |
| import argparse | |
| import gzip | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import shutil | |
| import sys | |
| def sha(path): | |
| with Path(path).open('rb') as stream: | |
| result=hashlib.sha256() | |
| for chunk in iter(lambda:stream.read(4*1024*1024),b''):result.update(chunk) | |
| return result.hexdigest() | |
| def line(stream,value): | |
| stream.write(json.dumps(value,ensure_ascii=False,separators=(',',':'),allow_nan=False)+'\n') | |
| def main(): | |
| parser=argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('cache',type=Path);parser.add_argument('output',type=Path) | |
| args=parser.parse_args();root=args.cache.resolve();out=args.output.resolve() | |
| if out.exists():raise FileExistsError('choose a fresh output directory') | |
| manifest=json.loads((root/'CACHE_MANIFEST.json').read_text()) | |
| for item in manifest['compressed_files']: | |
| p=(root/item['path']).resolve() | |
| if not p.is_relative_to(root) or p.stat().st_size!=item['bytes'] or sha(p)!=item['sha256']: | |
| raise ValueError('compressed cache file identity mismatch') | |
| out.mkdir(parents=True) | |
| for item in manifest['compressed_files']: | |
| target=out/item['restored_file'] | |
| mode='ab' if item.get('append') else 'wb' | |
| with gzip.open(root/item['path'],'rb') as source,target.open(mode) as dest: | |
| shutil.copyfileobj(source,dest,length=4*1024*1024) | |
| for name in ['COMPLETE.json','data_manifest.json','calibration_selection.json']: | |
| shutil.copyfile(root/name,out/name) | |
| original=json.loads((out/'data_manifest.json').read_text()) | |
| token_stream=(out/'tokens.uint32').open('rb') | |
| def tokens(entry): | |
| token_stream.seek(entry['offset_tokens']*4) | |
| data=token_stream.read(entry['token_count']*4) | |
| if len(data)!=entry['token_count']*4 or hashlib.sha256(data).hexdigest()!=entry['token_bytes_sha256']: | |
| raise ValueError('per-record token bytes differ') | |
| values=array('I');values.frombytes(data) | |
| if sys.byteorder!='little':values.byteswap() | |
| return values.tolist() | |
| fingerprint=original['tokenizer']['fingerprint'] | |
| with (out/'document_index.jsonl').open(encoding='utf-8') as source,(out/'train_validation.jsonl').open('w',encoding='utf-8',newline='\n') as dest: | |
| for raw in source: | |
| entry=json.loads(raw) | |
| value={k:entry[k] for k in ['id','group_id','source','split']} | |
| value.update(tokenizer_identity=fingerprint,token_ids=tokens(entry),metadata=entry['metadata']) | |
| line(dest,value) | |
| with (out/'event_index.jsonl').open(encoding='utf-8') as source,(out/'train_validation_event_streams.jsonl').open('w',encoding='utf-8',newline='\n') as dest: | |
| for raw in source: | |
| entry=json.loads(raw) | |
| value={k:entry[k] for k in ['id','group_id','source','split','tokenizer_identity','metadata']} | |
| value['articles']=[{'id':a['id'],'token_ids':tokens(a),'metadata':a['metadata']} for a in entry['articles']] | |
| line(dest,value) | |
| token_stream.close() | |
| for name,expected in original['files'].items(): | |
| path=out/name | |
| if path.stat().st_size!=expected['bytes'] or sha(path)!=expected['sha256']: | |
| raise ValueError('restored historical cache differs: '+name) | |
| print(json.dumps({'status':'pass','restored_files':len(original['files'])+2, | |
| 'complete_sha256':sha(out/'COMPLETE.json'), | |
| 'data_manifest_sha256':sha(out/'data_manifest.json'), | |
| 'expanded_token_JSONL_reconstructed_byte_identically':True})) | |
| if __name__=='__main__':main() | |