File size: 7,513 Bytes
3bd542a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""Restore v17_astra's exact, phase-ordered training rows from its keep lists and pinned public shards."""
import argparse
import hashlib
import json
import os
import struct
import tempfile
from collections import defaultdict
from pathlib import Path
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq

def sha(path):
    h=hashlib.sha256()
    with open(path,'rb') as stream:
        for chunk in iter(lambda:stream.read(4<<20),b''):h.update(chunk)
    return h.hexdigest()

def row_digests(batch):
    """Hash all seven native fields, including every int32 token and label."""
    arrays=[batch[n] for n in ['input_ids','labels']]
    views=[memoryview(a.values.to_numpy(zero_copy_only=False)).cast('B') for a in arrays]
    offsets=[a.offsets.to_pylist() for a in arrays]
    cols=[batch[n].to_pylist() for n in ['id','source','repeat','num_tokens','num_loss_tokens']]
    for i,(rid,source,repeat,n,loss) in enumerate(zip(*cols)):
        h=hashlib.sha256()
        for s in [rid,source]:
            x=s.encode();h.update(struct.pack('<I',len(x)));h.update(x)
        h.update(struct.pack('<qqq',repeat,n,loss))
        for buf,off,arr in zip(views,offsets,arrays):
            assert arr.type.value_type==pa.int32()
            h.update(buf[4*off[i]:4*off[i+1]])
        yield h.digest()

def resolve(root,upstream,manifest,item):
    name=item['path']
    if item['pool']=='v17':path=root/name
    elif upstream:path=upstream/name
    else:
        from huggingface_hub import hf_hub_download
        path=Path(hf_hub_download(repo_id=manifest['upstream']['repo'],repo_type='dataset',revision=manifest['upstream']['revision'],filename=name))
    if not path.is_file() or sha(path)!=item['sha256']:
        raise ValueError('Source checksum mismatch for '+name)
    return path

class Source:
    def __init__(self,path,cache):
        # File-backed Arrow allows random gathers with bounded resident memory.
        self.rows_per_batch=256
        with pa.OSFile(str(cache),'wb') as sink:
            pf=pq.ParquetFile(path)
            with pa.ipc.new_file(sink,pf.schema_arrow) as writer:
                self.starts=[]
                count=0
                for b in pf.iter_batches(batch_size=self.rows_per_batch,use_threads=False):
                    self.starts.append(count);writer.write_batch(b);count+=len(b)
        self.mapping=pa.memory_map(str(cache),'r');self.reader=pa.ipc.open_file(self.mapping)
    def close(self):self.mapping.close()

def materialize(root,out,epochs,upstream=None,scratch=None):
    from bisect import bisect_right
    manifest=json.loads((root/'manifest.json').read_text())
    out.mkdir(parents=True,exist_ok=True)
    if scratch:scratch.mkdir(parents=True,exist_ok=True)
    pa.set_cpu_count(1)
    for e in epochs:
        epoch=f'e{e:02}';rec=next(x for x in manifest['epochs'] if x['epoch']==epoch)
        dst=out/epoch
        if dst.exists():raise FileExistsError('Epoch output already exists at '+str(dst))
        with tempfile.TemporaryDirectory(dir=scratch) as temp, tempfile.TemporaryDirectory(dir=out) as stage:
            cache=Path(temp);staged=Path(stage)/epoch;staged.mkdir()
            opened={};totals=[]
            for phase in rec['phases']:
                keep_path=root/phase['keep']
                if sha(keep_path)!=phase['keep_sha256']:raise ValueError('Keep-list checksum mismatch')
                keep=pq.ParquetFile(keep_path)
                dest=staged/phase['phase']/'train';dest.mkdir(parents=True)
                n=0;loss=0;writer=None;current=0;in_shard=0
                try:
                    for plan in keep.iter_batches(batch_size=256,use_threads=False):
                        gather=defaultdict(list)
                        for pos,(file_id,idx) in enumerate(zip(plan['file'].to_pylist(),plan['row'].to_pylist())):
                            if file_id not in opened:
                                src=resolve(root,upstream,manifest,manifest['files'][file_id])
                                opened[file_id]=Source(src,cache/(str(file_id)+'.arrow'))
                            source=opened[file_id];part=bisect_right(source.starts,idx)-1
                            gather[(file_id,part)].append((pos,idx-source.starts[part]))
                        batches=[];positions=[]
                        for (file_id,part),entries in gather.items():
                            batch=opened[file_id].reader.get_batch(part)
                            batches.append(batch.take(pa.array([i for _,i in entries])))
                            positions.extend(p for p,_ in entries)
                        index=sorted(range(len(positions)),key=positions.__getitem__)
                        data=pa.Table.from_batches(batches).take(pa.array(index)).combine_chunks().to_batches()[0]
                        if list(row_digests(data))!=plan['sha256'].to_pylist() or data['id'].to_pylist()!=plan['id'].to_pylist():
                            raise ValueError('Native training-row mismatch in '+epoch+'/'+phase['phase'])
                        # The reference packer flushes each shard separately, so preserve its exact boundaries.
                        offset=0
                        while offset<len(data):
                            name,limit=phase['shards'][current]
                            if writer is None:
                                if Path(name).name!=name:raise ValueError('Invalid Parquet filename')
                                writer=pq.ParquetWriter(dest/name,data.schema,compression='zstd')
                            length=min(limit-in_shard,len(data)-offset)
                            if length<=0:raise ValueError('Invalid native shard size')
                            writer.write_batch(data.slice(offset,length))
                            offset+=length;in_shard+=length
                            if in_shard==limit:
                                writer.close();writer=None;current+=1;in_shard=0
                        n+=len(data);loss+=pc.sum(data['num_loss_tokens']).as_py()
                finally:
                    if writer:writer.close()
                assert n==phase['rows'] and loss==phase['loss'] and current==len(phase['shards']) and in_shard==0
                totals.append(dict(epoch=epoch,phase=phase['phase'],rows=n,loss=loss))
            for source in opened.values():source.close()
            (staged/'receipt.json').write_text(json.dumps(totals,indent=2)+'\n')
            staged.rename(dst)
        print('verified',epoch,sum(r['rows'] for r in totals),flush=True)
    v=manifest['validation']
    for item in v:
        import shutil
        source=resolve(root,upstream,manifest,item);dest=out/'validation'/Path(item['path']).name;dest.parent.mkdir(exist_ok=True)
        if not dest.exists():shutil.copyfile(source,dest)
        if sha(dest)!=item['sha256']:raise ValueError('Validation checksum mismatch')

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--release',type=Path,default=Path(__file__).resolve().parents[1]);p.add_argument('--out',type=Path,required=True);p.add_argument('--upstream-dir',type=Path);p.add_argument('--scratch',type=Path);p.add_argument('--epoch',type=int,action='append',help='Repeatable. Defaults to all published epochs.')
    args=p.parse_args();epochs=args.epoch or list(range(1,len(json.loads((args.release/'manifest.json').read_text())['epochs'])+1))
    materialize(args.release,args.out,epochs,args.upstream_dir,args.scratch)