Package: wilds
OverviewWILDS is a benchmark of in-the-wild distribution shifts spanning diverse data modalities and applications, from tumor identification to wildlife monitoring to poverty mapping.The WILDS package contains:Data loaders that automatically handle data downloading, processing, and splitting, andDataset evaluators that standardize model evaluation for each dataset.In addition, the example scripts contain default models, optimizers, schedulers, and training/evaluation code.
New algorithms can be easily added and run on all of the WILDS datasets.For more information, please visitour websiteor read the main WILDS paper (1) and its follow-up integrating unlabeled data (2).
For questions and feedback, please post on thediscussion board.InstallationWe recommend using pip to install WILDS:pipinstallwildsIf you have already installed it, please check that you have the latest version:python-c"import wilds; print(wilds.__version__)"# This should print "2.0.0". If it doesn't, update by running:pipinstall-UwildsIf you plan to edit or contribute to WILDS, you should install from source:gitclonegit@github.com:p-lambda/wilds.gitcdwilds
pipinstall-e.Inexamples/, we provide a set of scripts that can be used to train models on the WILDS datasets. These scripts were also used to benchmark baselines in our papers [1,2].
These scripts are not part of the installed WILDS package. To use them, you should install from source, as described above.RequirementsThe WILDS package depends on the following requirements:numpy>=1.19.1ogb>=1.2.6outdated>=0.2.0pandas>=1.1.0pillow>=7.2.0pytz>=2020.4torch>=1.7.0torch-scatter>=2.0.5torch-geometric>=2.0.1torchvision>=0.8.2tqdm>=4.53.0scikit-learn>=0.20.0scipy>=1.5.4Runningpip install wildsorpip install -e .will automatically check for and install all of these requirementsexcept for thetorch-scatterandtorch-geometricpackages, which require aquick manual install.Example script requirementsTo run the example scripts, you will also need to install these additional dependencies:transformers>=3.5.0SwAV requiresApex.
To install Apex, please follow theREADME from the official SwAV repository.Our code supports the optional use ofWeights & Biasesto track and monitor experiments.
To install the Weights and Biases Python package, runpip install wandb.All baseline experiments in the paper were run on Python 3.8.5 and CUDA 10.1.DatasetsWILDS currently includes 10 datasets, which we've briefly listed below. For full dataset descriptions, please see our papers (1,2).DatasetModalityLabeled splitsUnlabeled splitsiwildcamImagetrain, val, test, id_val, id_testextra_unlabeledcamelyon17Imagetrain, val, test, id_valtrain_unlabeled, val_unlabeled, test_unlabeledrxrx1Imagetrain, val, test, id_test-ogb-molpcbaGraphtrain, val, testtrain_unlabeled, val_unlabeled, test_unlabeledglobalwheatImagetrain, val, test, id_val, id_testtrain_unlabeled, val_unlabeled, test_unlabeled, extra_unlabeledcivilcommentsTexttrain, val, testextra_unlabeledfmowImagetrain, val, test, id_val, id_testtrain_unlabeled, val_unlabeled, test_unlabeledpovertyImagetrain, val, test, id_val, id_testtrain_unlabeled, val_unlabeled, test_unlabeledamazonTexttrain, val, test, id_val, id_testval_unlabeled, test_unlabeled, extra_unlabeledpy150Texttrain, val, test, id_val, id_test-Using the WILDS packageDataThe WILDS package provides a simple, standardized interface for all datasets in the benchmark.
This short Python snippet covers all of the steps of getting started with a WILDS dataset, including dataset download and initialization, accessing various splits, and preparing a user-customizable data loader.
We discuss data loading in more detail in#Data loading.fromwildsimportget_datasetfromwilds.common.data_loadersimportget_train_loaderimporttorchvision.transformsastransforms# Load the full dataset, and download it if necessarydataset=get_dataset(dataset="iwildcam",download=True)# Get the training settrain_data=dataset.get_subset("train",transform=transforms.Compose([transforms.Resize((448,448)),transforms.ToTensor()]),)# Prepare the standard data loadertrain_loader=get_train_loader("standard",train_data,batch_size=16)# (Optional) Load unlabeled datadataset=get_dataset(dataset="iwildcam",download=True,unlabeled=True)unlabeled_data=dataset.get_subset("test_unlabeled",transform=transforms.Compose([transforms.Resize((448,448)),transforms.ToTensor()]),)unlabeled_loader=get_train_loader("standard",unlabeled_data,batch_size=16)# Train loopforlabeled_batch,unlabeled_batchinzip(train_loader,unlabeled_loader):x,y,metadata=labeled_batchunlabeled_x,unlabeled_metadata=unlabeled_batch...Themetadatacontains information like the domain identity, e.g., which camera a photo was taken from, or which hospital the patient's data came from, etc., as well as other metadata.Domain informationTo allow algorithms to leverage domain annotations as well as other groupings over the available metadata, the WILDS package providesGrouperobjects.
TheseGrouperobjects are helper objects that extract group annotations from metadata, allowing users to specify the grouping scheme in a flexible fashion.
They are used to initialize group-aware data loaders (as discussed in#Data loading) and to implement algorithms that rely on domain annotations (e.g., Group DRO).
In the following code snippet, we initialize and use aGrouperthat extracts the domain annotations on the iWildCam dataset, where the domain is location.fromwilds.common.grouperimportCombinatorialGrouper# Initialize grouper, which extracts domain information# In this example, we form domains based on locationgrouper=CombinatorialGrouper(dataset,['location'])# Train loopforx,y_true,metadataintrain_loader:z=grouper.metadata_to_group(metadata)...Data loadingFor training, the WILDS package provides two types of data loaders.
The standard data loader shuffles examples in the training set, and is used for the standard approach of empirical risk minimization (ERM), where we minimize the average loss.fromwilds.common.data_loadersimportget_train_loader# Prepare the standard data loadertrain_loader=get_train_loader('standard',train_data,batch_size=16)To support other algorithms that rely on specific data loading schemes, we also provide the group data loader.
In each minibatch, the group loader first samples a specified number of groups, and then samples a fixed number of examples from each of those groups.
(By default, the groups are sampled uniformly at random, which upweights minority groups as a result. This can be toggled by theuniform_over_groupsparameter.)
We initialize group loaders as follows, usingGrouperthat specifies the grouping scheme.# Prepare a group data loader that samples from user-specified groupstrain_loader=get_train_loader("group",train_data,grouper=grouper,n_groups_per_batch=2,batch_size=16)Lastly, we also provide a data loader for evaluation, which loads examples without shuffling (unlike the training loaders).fromwilds.common.data_loadersimportget_eval_loader# Get the test settest_data=dataset.get_subset("test",transform=transforms.Compose([transforms.Resize((224,224)),transforms.ToTensor()]),)# Prepare the evaluation data loadertest_loader=get_eval_loader("standard",test_data,batch_size=16)EvaluatorsThe WILDS package standardizes and automates evaluation for each dataset.
Invoking theevalmethod of each dataset yields all metrics reported in the paper and on the leaderboard.fromwilds.common.data_loadersimportget_eval_loader# Get the test settest_data=dataset.get_subset("test",transform=transforms.Compose([transforms.Resize((224,224)),transforms.ToTensor()]),)# Prepare the data loadertest_loader=get_eval_loader("standard",test_data,batch_size=16)# Get predictions for the full test setforx,y_true,metadataintest_loader:y_pred=model(x)# Accumulate y_true, y_pred, metadata# Evaluatedataset.eval(all_y_pred,all_y_true,all_metadata)# {'recall_macro_all': 0.66, ...}Mostevalmethods take in predicted labels forall_y_predby default, but the default inputs vary across datasets and are documented in theevaldocstrings of the corresponding dataset class.Using the example scriptsInexamples/, we provide a set of scripts that can be used to train models on the WILDS datasets.pythonexamples/run_expt.py--datasetiwildcam--algorithmERM--root_dirdata
pythonexamples/run_expt.py--datasetcivilcomments--algorithmgroupDRO--root_dirdata
pythonexamples/run_expt.py--datasetfmow--algorithmDANN--unlabeled_splittest_unlabeled--root_dirdataThe scripts are configured to use the default models and reasonable hyperparameters. For exact hyperparameter settings used in our papers, please seeour CodaLab executable paper.Downloading and training on the WILDS datasetsThe first time you run these scripts, you might need to download the datasets. You can do so with the--downloadargument, for example:# downloads (labeled) datasetpythonexamples/run_expt.py--datasetglobalwheat--algorithmgroupDRO--root_dirdata--download# additionally downloads all unlabeled datapythonexamples/run_expt.py--datasetglobalwheat--algorithmgroupDRO--root_dirdata--download--unlabeled_split[...]Note that downloading the large amount of unlabeled data is optional; unlabeled data will only be downloaded if some--unlabeled_splitis set. (It does not matter which--unlabeled_splitis set; all unlabeled data will be downloaded together.)Alternatively, you can use the standalonewilds/download_datasets.pyscript to download the datasets, for example:# downloads (labeled) datapythonwilds/download_datasets.py--root_dirdata# downloads (unlabeled) datapythonwilds/download_datasets.py--root_dirdata--unlabeledThis will download all datasets to the specifieddatafolder. You can also use the--datasetsargument to download particular datasets.These are the sizes of each of our datasets, as well as their approximate time taken to train and evaluate the default model for a single ERM run using a NVIDIA V100 GPU.Dataset commandModalityDownload size (GB)Size on disk (GB)Train+eval time (Hours)iwildcamImage11257camelyon17Image10152rxrx1Image7711ogb-molpcbaGraph0.04215globalwheatImage10102civilcommentsText0.10.34.5fmowImage50556povertyImage12145amazonText775py150Text0.10.89.5The following are the sizes of the unlabeled data bundles:Dataset commandModalityDownload size (GB)Size on disk (GB)iwildcamImage4141camelyon17Image69.496ogb-molpcbaGraph1.221globalwheatImage103108civilcommentsText0.30.6fmow*Image5055povertyImage172184amazon*Text77* These unlabeled datasets are downloaded simultaneously with the labeled data and do not need to be downloaded separately.While thecamelyon17dataset is small and fast to train on, we advise against using it as the only dataset to prototype methods on, as the test performance of models trained on this dataset tend to exhibit a large degree of variability over random seeds.The image datasets (iwildcam,camelyon17,rxrx1,globalwheat,fmow, andpoverty) tend to have high disk I/O usage. If training time is much slower for you than the approximate times listed above, consider checking if I/O is a bottleneck (e.g., by moving to a local disk if you are using a network drive, or by increasing the number of data loader workers). To speed up training, you could also disable evaluation at each epoch or for all splits by toggling--evaluate_all_splitsand related arguments.AlgorithmsIn theexamples/algorithmsfolder, we provide implementations of the adaptation algorithms benchmarked in our papers (1,2).
All algorithms train on labeled data from a WILDS dataset'strainsplit.
Some algorithms are designed to also leverage unlabeled data. To load unlabeled data, specify an--unlabeled_splitwhen running.In addition to shared hyperparameters such aslr,weight_decay,batch_size, andunlabeled_batch_size, the scripts also take in command line arguments for algorithm-specific hyperparameters.Algorithm commandHyperparametersNotesSee WILDS paperERM-Only uses labeled data(1,2)groupDROgroup_dro_step_sizeOnly uses labeled data(1)deepCORALcoral_penalty_weightCan optionally use unlabeled data(1,2)IRMirm_lambda,irm_penalty_anneal_itersOnly uses labeled data(1)DANNdann_penalty_weight,dann_classifier_lr,dann_featurizer_lr,dann_discriminator_lrCan use unlabeled data(2)AFNafn_penalty_weight,safn_delta_r,hafn_rDesigned to use unlabeled data(2)FixMatchself_training_lambda,self_training_thresholdDesigned to use unlabeled data(2)PseudoLabelself_training_lambda,self_training_threshold,pseudolabel_T2Designed to use unlabeled data(2)NoisyStudentsoft_pseudolabels,noisystudent_dropout_rateDesigned to use unlabeled data(2)The repository is set up to facilitate general-purpose algorithm development: new algorithms can be added toexamples/algorithmsand then run on all of the WILDS datasets using the default models.Evaluating trained modelsWe also provide an evaluation script that aggregates prediction CSV files for different replicates and reports on their combined evaluation. To use this, run:pythonexamples/evaluate.py<predictions_dir><output_dir>--root-dir<root_dir>where<predictions_dir>is the path to your predictions directory,<output_dir>is where the results JSON will be writte, and<root_dir>is the dataset root directory.
The predictions directory should have a subdirectory for each dataset
(e.g.iwildcam) containing prediction CSV files to evaluate; see oursubmission guidelinesfor the format.
The evaluation script will skip over any datasets that has missing prediction files.
Any dataset not in<root_dir>will be downloaded to<root_dir>.ReproducibilityWe have anexecutable versionof our paper on CodaLab that contains the exact commands, code, and data for the experiments reported in our paper, which rely on these scripts. Trained model weights for all datasets can also be found there.
All configurations and hyperparameters can also be found in theexamples/configsfolder of this repo, and dataset-specific parameters are inexamples/configs/datasets.py.LeaderboardIf you are developing new training algorithms and/or models on WILDS, please consider submitting them to ourpublic leaderboard.Citing WILDS (Bibtex)If you use WILDS datasets in your work, please cite our paper:WILDS: A Benchmark of in-the-Wild Distribution Shifts.Pang Wei Koh*, Shiori Sagawa*, Henrik Marklund, Sang Michael Xie, Marvin Zhang, Akshay Balsubramani, Weihua Hu, Michihiro Yasunaga, Richard Lanas Phillips, Irena Gao, Tony Lee, Etienne David, Ian Stavness, Wei Guo, Berton A. Earnshaw, Imran S. Haque, Sara Beery, Jure Leskovec, Anshul Kundaje, Emma Pierson, Sergey Levine, Chelsea Finn, and Percy Liang. ICML 2021.If you use unlabeled data from the WILDS datasets, please also cite:Extending the WILDS Benchmark for Unsupervised Adaptation.Shiori Sagawa*, Pang Wei Koh*, Tony Lee*, Irena Gao*, Sang Michael Xie, Kendrick Shen, Ananya Kumar, Weihua Hu, Michihiro Yasunaga, Henrik Marklund, Sara Beery, Etienne David, Ian Stavness, Wei Guo, Jure Leskovec, Kate Saenko, Tatsunori Hashimoto, Sergey Levine, Chelsea Finn, and Percy Liang. NeurIPS 2021 Workshop on Distribution Shifts.In addition, please cite the original papers that introduced the datasets, as listed on thedatasets page.AcknowledgementsThe design of the WILDS benchmark was inspired by theOpen Graph Benchmark, and we are grateful to the Open Graph Benchmark team for their advice and help in setting up WILDS.