File size: 4,973 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 | """Materialize one logical epoch from immutable references; train from separately packed phases."""
import argparse,collections,hashlib,json,os,tempfile
from pathlib import Path
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
def materialize(plans,epoch,out):
group=collections.defaultdict(dict)
for phase in range(2):
for r in pq.read_table(plans/f'e{epoch:02}-p{phase+1}.parquet').to_pylist():
loc=group[r['file']]
if r['ri'] in loc:raise ValueError(f'duplicate row location {r["file"]}:{r["ri"]}')
loc[r['ri']]=(phase,r['id'],r['loss'],r['ntok'])
out.mkdir(parents=True,exist_ok=True)
result=out/f'e{epoch:02}'
if result.exists():raise FileExistsError(result)
with tempfile.TemporaryDirectory(dir=out) as temp:
root=Path(temp);stats=[{'rows':0,'loss':0},{'rows':0,'loss':0}]
for p in range(2):(root/f'p{p+1}'/'train').mkdir(parents=True)
for j,(file,loc) in enumerate(sorted(group.items())):
# Physical order is efficient for I/O. The pack sampler later shuffles within each phase.
src=pq.ParquetFile(file);start=0;writers={}
try:
for b in src.iter_batches(batch_size=32,columns=['id','repeat','source','num_tokens','num_loss_tokens','input_ids','labels'],use_threads=False):
indices=[[],[]]
for i in range(b.num_rows):
r=loc.pop(start+i,None)
if r is None:continue
p,rid,loss,ntok=r
if (rid,loss,ntok)!=(b['id'][i].as_py(),b['num_loss_tokens'][i].as_py(),b['num_tokens'][i].as_py()):raise ValueError(f'drift at {file}:{start+i}')
indices[p].append(i);stats[p]['rows']+=1;stats[p]['loss']+=loss
for p,ix in enumerate(indices):
if not ix:continue
table=pa.Table.from_batches([b.take(pa.array(ix))])
if p not in writers:writers[p]=pq.ParquetWriter(root/f'p{p+1}'/'train'/f'part-{j:05}.parquet',table.schema,compression='zstd')
writers[p].write_table(table)
start+=b.num_rows
if not loc:break
finally:
for w in writers.values():w.close()
if loc:raise ValueError(f'missing positions in {file}')
for p in range(2):
retained=[pq.ParquetFile(f) for f in (root/f'p{p+1}'/'train').glob('*.parquet')]
assert sum(f.metadata.num_rows for f in retained)==stats[p]['rows']
assert sum(sum(f.read(columns=['num_loss_tokens']).column(0).to_pylist()) for f in retained)==stats[p]['loss']
(root/'receipt.json').write_text(json.dumps(stats,indent=2));os.rename(root,result)
return result
class PhaseOrderedSampler:
"""Shuffle all packs inside each phase without shuffling the phases. Works with Trainer's sampler hook."""
def __init__(self,lengths,seed):
self.lengths=tuple(lengths);self.seed=int(seed)
if not self.lengths or any(n<1 for n in self.lengths):raise ValueError('empty pack phase')
def __len__(self):return sum(self.lengths)
def __iter__(self):
start=0
for i,n in enumerate(self.lengths):
rng=np.random.default_rng(np.random.SeedSequence([self.seed,i]))
yield from (start+int(j) for j in rng.permutation(n));start+=n
def install(trainer_cls,pack_lengths,seed):
"""Apply instead of the old global random/balanced sampler. Dataset must be concatenated in manifest order."""
sampler=PhaseOrderedSampler(pack_lengths,seed)
def get_train_sampler(trainer,train_dataset=None):
if hasattr(trainer,'args') and float(trainer.args.num_train_epochs)!=1:
raise ValueError('the concatenated rotation stream is one physical training epoch')
data=trainer.train_dataset if train_dataset is None else train_dataset
if len(data)!=len(sampler):raise ValueError('physical dataset and phase receipt disagree')
return sampler
trainer_cls._get_train_sampler=get_train_sampler
def prepared_train_data(trainer_cls,phase_receipt,seed):
from datasets import concatenate_datasets,load_from_disk
phases=json.loads(Path(phase_receipt).read_text())
if [(r['epoch'],r['phase']) for r in phases]!=sorted((r['epoch'],r['phase']) for r in phases):
raise ValueError('unexpected physical phase order')
datasets=[load_from_disk(r['path']) for r in phases]
lengths=[len(d) for d in datasets]
assert lengths==[r['packs'] for r in phases]
install(trainer_cls,lengths,seed)
return concatenate_datasets(datasets)
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('plans',type=Path);parser.add_argument('epoch',type=int);parser.add_argument('out',type=Path)
args=parser.parse_args();print(materialize(args.plans,args.epoch,args.out))
|