Download scripts/phase_data.py from LingweiGu/v17_astra: direct link, hf CLI and curl.
- Browser
- Download file 4.97 kB
-
https://huggingface.co/datasets/LingweiGu/v17_astra/resolve/main/scripts/phase_data.py
- Command line
-
hf download hf://datasets/LingweiGu/v17_astra/scripts/phase_data.py
-
curl -L -o phase_data.py https://huggingface.co/datasets/LingweiGu/v17_astra/resolve/main/scripts/phase_data.py
4.97 kB
| """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)) | |