Package: data-selection
Data Selection for Language Models via Importance Resampling (DSIR)This repository contains theDSIRdata selection tool for selecting relevant language model training data from any raw data source given a target dataset, as well as pre-filtered datasets and some pretrained models.DSIR is built for:fast, large-scale (trillion-token scale) data selection from large raw text datasets (Pile, RefinedWeb, RedPajama, ...). There is almost no overhead to selecting more examples (unlike retrieval), other than the time it takes to write the extra examples to disk.selecting data that is distributed like a given target dataset (domain-specific data, Wikipedia, ...). Relevance and diversity are balanced automatically by matching the distribution of the target dataset on a feature space (e.g., n-gram frequencies).Compute needed:1 CPU nodea decent amount of RAM (at least 64GB for most large datasets - need to hold a few floats per example in memory)a high number of cores. The data selection speed scales linearly with the CPU cores.Code related to the DSIR paper's experiments are in theexperimental/directory.QuickstartInstall with pip:pip install data-selectionInstall from source by cloning this repo and installing via pip:git clone git@github.com:/p-lambda/dsir
pip install ./dsirTo select data, simply initialize aHashedNgramDSIRobject and call the following functions:fromdata_selectionimportHashedNgramDSIRraw_datasets=[<listofpaths>]target_datasets=[<listofpaths>]dsir=HashedNgramDSIR(raw_datasets,target_datasets,cache_dir='/path/to/dsir_cache')dsir.fit_importance_estimator(num_tokens_to_fit='auto')dsir.compute_importance_weights()dsir.resample(out_dir='resampled',num_to_sample=10000000,cache_dir='/path/to/resampled_cache')Running this would write 10M documents injsonlfiles inside an output directory namedresampled. The files will first be written tocache_dirand moved toout_dirupon completion (setcache_dirtoNoneto skip this step). For best performance, use uncompressedjsonlfiles stored on local file storage for all data paths and use as many CPU cores as possible, which allows each file to be virtually sharded across multiple cores. Custom functions for reading the data paths and extracting the text field from each example can be provided via the{raw,target}_load_dataset_fnand{raw,target}_parse_example_fnarguments to the constructor. The number of tokens to use for fitting the importance weight estimator can be tuned with thenum_tokens_to_fitargument (set toallto fit on full dataset). Top-k retrieval instead of sampling without replacement (the default) can be done by specifyingtop_k=Trueto theresamplemethod.Thedsirintermediate results (afterfit_importance_estimatorandcompute_importance_weights) can be saved and loaded for later use, for example to resample 100M documents instead:dsir.save('/path/to/dsir_params.pkl')# later ondsir.load('/path/to/dsir_params.pkl')dsir.resample(out_dir='/path/to/out_dir',num_to_sample=100000000,cache_dir='/path/to/resampled_cache')Thesavemethod can be called at any time to save partial results.SeeUsage documentationfor full details.Speed benchmark on The PileUsing 1 CPU node with 96GB RAM and 96 cores, we can select data from the full (decompressed) Pile dataset in less than4.5 hours.
The Pile dataset was first decompressed and placed onto the node's local file storage. The breakdown of timings for each step are:Fit importance estimator(withnum_tokens_to_fit="auto"): 59.28 secondsCompute importance weights: 4.36 hoursResample 10M documents(withcache_dir=Noneandout_diris a local storage location): 353.68 secondsTotal: 4.47 hoursSubsequent resampling with the same target data is very cheap, and the runtime does not scale with the number of documents to select (unlike retrieval). Resampling 100M documents takes the same amount of time (less than6 minutes) as resampling 10M documents:Resample 10M documents: 353.68 secondsResample 100M documents: 352.69 secondsExamplesTo select data from the Pile:fromdata_selectionimportHashedNgramDSIR# 2-digit integers up to 29subsets=[str(i).zfill(2)foriinrange(0,30)]raw_datasets=[f'/path/to/pile/{subset}.jsonl'forsubsetinsubsets]target_datasets=['/path/to/target.jsonl']dsir=HashedNgramDSIR(raw_datasets=raw_datasets,target_datasets=target_datasets,cache_dir='/path/to/dsir_cache')dsir.fit_importance_estimator(num_tokens_to_fit='auto')dsir.compute_importance_weights()dsir.resample(out_dir='/path/to/out_dir',num_to_sample=10000000,cache_dir='/path/to/resample_cache')HuggingFace datasets can also be used in eitherraw_datasetsortarget_datasets(note: streaming a large raw dataset directly will be very slow - we recommend this more for target datasets):fromdata_selectionimportHashedNgramDSIRfromdatasetsimportload_datasetsubsets=[str(i).zfill(2)foriinrange(0,30)]raw_datasets=[f'/path/to/pile/{subset}.jsonl'forsubsetinsubsets]target_datasets=['codeparrot/self-instruct-starcoder','SetFit/mnli']deftarget_load_dataset_fn(dataset):ifdataset=='codeparrot/self-instruct-starcoder':ds=load_dataset(dataset,streaming=True,split='raw')else:ds=load_dataset(dataset,streaming=True,split='train').take(10000)returndsdeftarget_parse_example_fn(ex):if'output'inex:returnex['output']else:returnex['text1']+' '+ex['text2']dsir=HashedNgramDSIR(raw_datasets=raw_datasets,target_datasets=target_datasets,cache_dir='/path/to/dsir_cache',target_parse_example_fn=target_parse_example_fn,target_load_dataset_fn=target_load_dataset_fn,separate_targets=True)dsir.fit_importance_estimator(num_tokens_to_fit='auto')dsir.compute_importance_weights()dsir.resample(out_dir='/path/to/out_dir',num_to_sample=10000000,cache_dir='/path/to/resample_cache')For use-cases where the target datasets are quite different (here, a mix of code and natural language), we recommend passing inseparate_targetsinto the constructor.separate_targetscontrols whether to select data separately for each target and then join them. For example, when including two target datasets, one natural language dataset and one code, the most heavily upweighted data whenseparate_targets=Falsemay skew towards documents with a mix of natural language and code, such as StackExchange. Whenseparate_targets=True, two separate DSIR runs will occur in parallel, selecting a mixture of documents from each target according totarget_proportions. Whentarget_proportionsis unspecified, the number of documents to select for each target is weighted according to the token sizes of each target dataset.Citation InformationPaper:https://arxiv.org/abs/2302.03169@article{xie2023data,
  author = {Sang Michael Xie and Shibani Santurkar and Tengyu Ma and Percy Liang},
  journal = {Advances in Neural Information Processing Systems (NeurIPS)},
  title = {Data Selection for Language Models via Importance Resampling},
  year = {2023},
}