diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/sagemaker.md b/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/sagemaker.md
new file mode 100644
index 0000000000000000000000000000000000000000..700811404667aa5074686604bac83949b40ee5a1
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/sagemaker.md
@@ -0,0 +1,204 @@
+
+
+# Amazon SageMaker
+
+Hugging Face and Amazon introduced new [Hugging Face Deep Learning Containers (DLCs)](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#huggingface-training-containers) to
+make it easier than ever to train Hugging Face Transformer models in [Amazon SageMaker](https://aws.amazon.com/sagemaker/).
+
+## Getting Started
+
+### Setup & Installation
+
+
+Before you can run your Accelerate scripts on Amazon SageMaker you need to sign up for an AWS account. If you do not
+have an AWS account yet learn more [here](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-set-up.html).
+
+After you have your AWS Account you need to install the `sagemaker` sdk for Accelerate with:
+
+```bash
+pip install "accelerate[sagemaker]" --upgrade
+```
+
+Accelerate currently uses the DLCs, with `transformers`, `datasets` and `tokenizers` pre-installed. Accelerate is not in the DLC yet (will soon be added!) so to use it within Amazon SageMaker you need to create a
+`requirements.txt` in the same directory where your training script is located and add it as dependency:
+
+```
+accelerate
+```
+
+You should also add any other dependencies you have to this `requirements.txt`.
+
+
+### Configure Accelerate
+
+You can configure the launch configuration for Amazon SageMaker the same as you do for non SageMaker training jobs with
+the Accelerate CLI:
+
+```bash
+accelerate config
+# In which compute environment are you running? ([0] This machine, [1] AWS (Amazon SageMaker)): 1
+```
+
+Accelerate will go through a questionnaire about your Amazon SageMaker setup and create a config file you can edit.
+
+
+
+ Accelerate is not saving any of your credentials.
+
+
+
+### Prepare a Accelerate fine-tuning script
+
+The training script is very similar to a training script you might run outside of SageMaker, but to save your model
+after training you need to specify either `/opt/ml/model` or use `os.environ["SM_MODEL_DIR"]` as your save
+directory. After training, artifacts in this directory are uploaded to S3:
+
+
+```diff
+- torch.save('/opt/ml/model`)
++ accelerator.save('/opt/ml/model')
+```
+
+
+
+ SageMaker doesn’t support argparse actions. If you want to use, for example, boolean hyperparameters, you need to
+ specify type as bool in your script and provide an explicit True or False value for this hyperparameter. [[REF]](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#prepare-a-pytorch-training-script).
+
+
+
+### Launch Training
+
+You can launch your training with Accelerate CLI with:
+
+```
+accelerate launch path_to_script.py --args_to_the_script
+```
+
+This will launch your training script using your configuration. The only thing you have to do is provide all the
+arguments needed by your training script as named arguments.
+
+**Examples**
+
+
+
+ If you run one of the example scripts, don't forget to add `accelerator.save('/opt/ml/model')` to it.
+
+
+
+```bash
+accelerate launch ./examples/sagemaker_example.py
+```
+
+Outputs:
+
+```
+Configuring Amazon SageMaker environment
+Converting Arguments to Hyperparameters
+Creating Estimator
+2021-04-08 11:56:50 Starting - Starting the training job...
+2021-04-08 11:57:13 Starting - Launching requested ML instancesProfilerReport-1617883008: InProgress
+.........
+2021-04-08 11:58:54 Starting - Preparing the instances for training.........
+2021-04-08 12:00:24 Downloading - Downloading input data
+2021-04-08 12:00:24 Training - Downloading the training image..................
+2021-04-08 12:03:39 Training - Training image download completed. Training in progress..
+........
+epoch 0: {'accuracy': 0.7598039215686274, 'f1': 0.8178438661710037}
+epoch 1: {'accuracy': 0.8357843137254902, 'f1': 0.882249560632689}
+epoch 2: {'accuracy': 0.8406862745098039, 'f1': 0.8869565217391304}
+........
+2021-04-08 12:05:40 Uploading - Uploading generated training model
+2021-04-08 12:05:40 Completed - Training job completed
+Training seconds: 331
+Billable seconds: 331
+You can find your model data at: s3://your-bucket/accelerate-sagemaker-1-2021-04-08-11-56-47-108/output/model.tar.gz
+```
+
+## Advanced Features
+
+### Distributed Training: Data Parallelism
+
+Set up the accelerate config by running `accelerate config` and answer the SageMaker questions and set it up.
+To use SageMaker DDP, select it when asked
+`What is the distributed mode? ([0] No distributed training, [1] data parallelism):`.
+Example config below:
+```yaml
+base_job_name: accelerate-sagemaker-1
+compute_environment: AMAZON_SAGEMAKER
+distributed_type: DATA_PARALLEL
+ec2_instance_type: ml.p3.16xlarge
+iam_role_name: xxxxx
+image_uri: null
+mixed_precision: fp16
+num_machines: 1
+profile: xxxxx
+py_version: py10
+pytorch_version: 2.5.0
+region: us-east-1
+transformers_version: 4.17.0
+use_cpu: false
+```
+
+### Distributed Training: Model Parallelism
+
+*currently in development, will be supported soon.*
+
+### Python packages and dependencies
+
+Accelerate currently uses the DLCs, with `transformers`, `datasets` and `tokenizers` pre-installed. If you
+want to use different/other Python packages you can do this by adding them to the `requirements.txt`. These packages
+will be installed before your training script is started.
+
+### Local Training: SageMaker Local mode
+
+The local mode in the SageMaker SDK allows you to run your training script locally inside the HuggingFace DLC (Deep Learning container)
+or using your custom container image. This is useful for debugging and testing your training script inside the final container environment.
+Local mode uses Docker compose (*Note: Docker Compose V2 is not supported yet*). The SDK will handle the authentication against ECR
+to pull the DLC to your local environment. You can emulate CPU (single and multi-instance) and GPU (single instance) SageMaker training jobs.
+
+To use local mode, you need to set your `ec2_instance_type` to `local`.
+
+```yaml
+ec2_instance_type: local
+```
+
+### Advanced configuration
+
+The configuration allows you to override parameters for the [Estimator](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html).
+These settings have to be applied in the config file and are not part of `accelerate config`. You can control many additional aspects of the training job, e.g. use Spot instances, enable network isolation and many more.
+
+```yaml
+additional_args:
+ # enable network isolation to restrict internet access for containers
+ enable_network_isolation: True
+```
+
+You can find all available configuration [here](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html).
+
+### Use Spot Instances
+
+You can use Spot Instances e.g. using (see [Advanced configuration](#advanced-configuration)):
+```yaml
+additional_args:
+ use_spot_instances: True
+ max_wait: 86400
+```
+
+*Note: Spot Instances are subject to be terminated and training to be continued from a checkpoint. This is not handled in Accelerate out of the box. Contact us if you would like this feature.*
+
+### Remote scripts: Use scripts located on Github
+
+*undecided if feature is needed. Contact us if you would like this feature.*
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/tracking.md b/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/tracking.md
new file mode 100644
index 0000000000000000000000000000000000000000..940da9e1be5831b16f387b4bd77474c31bdb1355
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/tracking.md
@@ -0,0 +1,233 @@
+
+
+# Experiment trackers
+
+There are a large number of experiment tracking APIs available, however getting them all to work in a multi-processing environment can oftentimes be complex.
+Accelerate provides a general tracking API that can be used to log useful items during your script through [`Accelerator.log`]
+
+## Integrated Trackers
+
+Currently `Accelerate` supports seven trackers out-of-the-box:
+
+- TensorBoard
+- WandB
+- CometML
+- Aim
+- MLFlow
+- ClearML
+- DVCLive
+
+To use any of them, pass in the selected type(s) to the `log_with` parameter in [`Accelerate`]:
+```python
+from accelerate import Accelerator
+from accelerate.utils import LoggerType
+
+accelerator = Accelerator(log_with="all") # For all available trackers in the environment
+accelerator = Accelerator(log_with="wandb")
+accelerator = Accelerator(log_with=["wandb", LoggerType.TENSORBOARD])
+```
+
+At the start of your experiment [`Accelerator.init_trackers`] should be used to setup your project, and potentially add any experiment hyperparameters to be logged:
+```python
+hps = {"num_iterations": 5, "learning_rate": 1e-2}
+accelerator.init_trackers("my_project", config=hps)
+```
+
+When you are ready to log any data, [`Accelerator.log`] should be used.
+A `step` can also be passed in to correlate the data with a particular step in the training loop.
+```python
+accelerator.log({"train_loss": 1.12, "valid_loss": 0.8}, step=1)
+```
+
+Once you've finished training, make sure to run [`Accelerator.end_training`] so that all the trackers can run their finish functionalities if they have any.
+```python
+accelerator.end_training()
+```
+
+
+A full example is below:
+```python
+from accelerate import Accelerator
+
+accelerator = Accelerator(log_with="all")
+config = {
+ "num_iterations": 5,
+ "learning_rate": 1e-2,
+ "loss_function": str(my_loss_function),
+}
+
+accelerator.init_trackers("example_project", config=config)
+
+my_model, my_optimizer, my_training_dataloader = accelerator.prepare(my_model, my_optimizer, my_training_dataloader)
+device = accelerator.device
+my_model.to(device)
+
+for iteration in range(config["num_iterations"]):
+ for step, batch in enumerate(my_training_dataloader):
+ my_optimizer.zero_grad()
+ inputs, targets = batch
+ inputs = inputs.to(device)
+ targets = targets.to(device)
+ outputs = my_model(inputs)
+ loss = my_loss_function(outputs, targets)
+ accelerator.backward(loss)
+ my_optimizer.step()
+ accelerator.log({"training_loss": loss}, step=step)
+accelerator.end_training()
+```
+
+If a tracker requires a directory to save data to, such as `TensorBoard`, then pass the directory path to `project_dir`. The `project_dir` parameter is useful
+when there are other configurations to be combined with in the [`~utils.ProjectConfiguration`] data class. For example, you can save the TensorBoard data to `project_dir` and everything else can be logged in the `logging_dir` parameter of [`~utils.ProjectConfiguration`:
+
+```python
+accelerator = Accelerator(log_with="tensorboard", project_dir=".")
+
+# use with ProjectConfiguration
+config = ProjectConfiguration(project_dir=".", logging_dir="another/directory")
+accelerator = Accelerator(log_with="tensorboard", project_config=config)
+```
+
+## Implementing Custom Trackers
+
+To implement a new tracker to be used in `Accelerator`, a new one can be made through implementing the [`GeneralTracker`] class.
+Every tracker must implement three functions and have three properties:
+ - `__init__`:
+ - Should store a `run_name` and initialize the tracker API of the integrated library.
+ - If a tracker stores their data locally (such as TensorBoard), a `logging_dir` parameter can be added.
+ - `store_init_configuration`:
+ - Should take in a `values` dictionary and store them as a one-time experiment configuration
+ - `log`:
+ - Should take in a `values` dictionary and a `step`, and should log them to the run
+
+ - `name` (`str`):
+ - A unique string name for the tracker, such as `"wandb"` for the wandb tracker.
+ - This will be used for interacting with this tracker specifically
+ - `requires_logging_directory` (`bool`):
+ - Whether a `logging_dir` is needed for this particular tracker and if it uses one.
+ - `tracker`:
+ - This should be implemented as a `@property` function
+ - Should return the internal tracking mechanism the library uses, such as the `run` object for `wandb`.
+
+Each method should also utilize the [`state.PartialState`] class if the logger should only be executed on the main process for instance.
+
+A brief example can be seen below with an integration with Weights and Biases, containing only the relevant information and logging just on
+the main process:
+```python
+from accelerate.tracking import GeneralTracker, on_main_process
+from typing import Optional
+
+import wandb
+
+
+class MyCustomTracker(GeneralTracker):
+ name = "wandb"
+ requires_logging_directory = False
+
+ @on_main_process
+ def __init__(self, run_name: str):
+ self.run_name = run_name
+ run = wandb.init(self.run_name)
+
+ @property
+ def tracker(self):
+ return self.run.run
+
+ @on_main_process
+ def store_init_configuration(self, values: dict):
+ wandb.config(values)
+
+ @on_main_process
+ def log(self, values: dict, step: Optional[int] = None):
+ wandb.log(values, step=step)
+```
+
+When you are ready to build your `Accelerator` object, pass in an **instance** of your tracker to [`Accelerator.log_with`] to have it automatically
+be used with the API:
+
+```python
+tracker = MyCustomTracker("some_run_name")
+accelerator = Accelerator(log_with=tracker)
+```
+
+These also can be mixed with existing trackers, including with `"all"`:
+
+```python
+tracker = MyCustomTracker("some_run_name")
+accelerator = Accelerator(log_with=[tracker, "all"])
+```
+
+## Accessing the internal tracker
+
+If some custom interactions with a tracker might be wanted directly, you can quickly access one using the
+[`Accelerator.get_tracker`] method. Just pass in the string corresponding to a tracker's `.name` attribute
+and it will return that tracker on the main process.
+
+This example shows doing so with wandb:
+
+```python
+wandb_tracker = accelerator.get_tracker("wandb")
+```
+
+From there you can interact with `wandb`'s `run` object like normal:
+
+```python
+wandb_tracker.log_artifact(some_artifact_to_log)
+```
+
+
+ Trackers built in Accelerate will automatically execute on the correct process,
+ so if a tracker is only meant to be ran on the main process it will do so
+ automatically.
+
+
+If you want to truly remove Accelerate's wrapping entirely, you can
+achieve the same outcome with:
+
+```python
+wandb_tracker = accelerator.get_tracker("wandb", unwrap=True)
+if accelerator.is_main_process:
+ wandb_tracker.log_artifact(some_artifact_to_log)
+```
+
+
+## When a wrapper cannot work
+
+If a library has an API that does not follow a strict `.log` with an overall dictionary such as Neptune.AI, logging can be done manually under an `if accelerator.is_main_process` statement:
+```diff
+ from accelerate import Accelerator
++ import neptune
+
+ accelerator = Accelerator()
++ run = neptune.init_run(...)
+
+ my_model, my_optimizer, my_training_dataloader = accelerate.prepare(my_model, my_optimizer, my_training_dataloader)
+ device = accelerator.device
+ my_model.to(device)
+
+ for iteration in config["num_iterations"]:
+ for batch in my_training_dataloader:
+ my_optimizer.zero_grad()
+ inputs, targets = batch
+ inputs = inputs.to(device)
+ targets = targets.to(device)
+ outputs = my_model(inputs)
+ loss = my_loss_function(outputs, targets)
+ total_loss += loss
+ accelerator.backward(loss)
+ my_optimizer.step()
++ if accelerator.is_main_process:
++ run["logs/training/batch/loss"].log(loss)
+```
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/training_zoo.md b/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/training_zoo.md
new file mode 100644
index 0000000000000000000000000000000000000000..3110af5786f81844d0c33dd7c3277e7377d15a26
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/docs/source/usage_guides/training_zoo.md
@@ -0,0 +1,180 @@
+
+
+# Example Zoo
+
+Below contains a non-exhaustive list of tutorials and scripts showcasing Accelerate.
+
+## Official Accelerate Examples:
+
+### Basic Examples
+
+These examples showcase the base features of Accelerate and are a great starting point
+
+- [Barebones NLP example](https://github.com/huggingface/accelerate/blob/main/examples/nlp_example.py)
+- [Barebones distributed NLP example in a Jupyter Notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb)
+- [Barebones computer vision example](https://github.com/huggingface/accelerate/blob/main/examples/cv_example.py)
+- [Barebones distributed computer vision example in a Jupyter Notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_cv_example.ipynb)
+- [Using Accelerate in Kaggle](https://www.kaggle.com/code/muellerzr/multi-gpu-and-accelerate)
+
+### Feature Specific Examples
+
+These examples showcase specific features that the Accelerate framework offers
+
+- [Automatic memory-aware gradient accumulation](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/automatic_gradient_accumulation.py)
+- [Checkpointing states](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/checkpointing.py)
+- [Cross validation](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/cross_validation.py)
+- [DeepSpeed](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/deepspeed_with_config_support.py)
+- [Fully Sharded Data Parallelism](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/fsdp_with_peak_mem_tracking.py)
+- [Gradient accumulation](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/gradient_accumulation.py)
+- [Memory-aware batch size finder](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/memory.py)
+- [Metric Computation](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/multi_process_metrics.py)
+- [Using Trackers](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/tracking.py)
+- [Using Megatron-LM](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/megatron_lm_gpt_pretraining.py)
+
+### Full Examples
+
+These examples showcase every feature in Accelerate at once that was shown in "Feature Specific Examples"
+
+- [Complete NLP example](https://github.com/huggingface/accelerate/blob/main/examples/complete_nlp_example.py)
+- [Complete computer vision example](https://github.com/huggingface/accelerate/blob/main/examples/complete_cv_example.py)
+- [Very complete and extensible vision example showcasing SLURM, hydra, and a very extensible usage of the framework](https://github.com/yuvalkirstain/PickScore)
+- [Causal language model fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_clm_no_trainer.py)
+- [Masked language model fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm_no_trainer.py)
+- [Speech pretraining example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py)
+- [Translation fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/translation/run_translation_no_trainer.py)
+- [Text classification fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue_no_trainer.py)
+- [Semantic segmentation fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py)
+- [Question answering fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/question-answering/run_qa_no_trainer.py)
+- [Beam search question answering fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/question-answering/run_qa_beam_search_no_trainer.py)
+- [Multiple choice question answering fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/multiple-choice/run_swag_no_trainer.py)
+- [Named entity recognition fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/token-classification/run_ner_no_trainer.py)
+- [Image classification fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/image-classification/run_image_classification_no_trainer.py)
+- [Summarization fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/summarization/run_summarization_no_trainer.py)
+- [End-to-end examples on how to use AWS SageMaker integration of Accelerate](https://github.com/huggingface/notebooks/blob/main/sagemaker/22_accelerate_sagemaker_examples/README.md)
+- [Megatron-LM examples for various NLp tasks](https://github.com/pacman100/accelerate-megatron-test)
+
+## Integration Examples
+
+These are tutorials from libraries that integrate with Accelerate:
+
+> Don't find your integration here? Make a PR to include it!
+
+### Amphion
+- [Training Text-to-Speech Models with Amphion](https://github.com/open-mmlab/Amphion/blob/main/egs/tts/README.md)
+- [Training Singing Voice Conversion Models with Amphion](https://github.com/open-mmlab/Amphion/blob/main/egs/svc/README.md)
+- [Training Vocoders with Amphion](https://github.com/open-mmlab/Amphion/blob/main/egs/vocoder/README.md)
+
+### Catalyst
+
+- [Distributed training tutorial with Catalyst](https://catalyst-team.github.io/catalyst/tutorials/ddp.html)
+
+### DALLE2-pytorch
+
+- [Fine-tuning DALLE2](https://github.com/lucidrains/DALLE2-pytorch#usage)
+
+### Diffusers
+
+- [Performing textual inversion with diffusers](https://github.com/huggingface/diffusers/tree/main/examples/textual_inversion)
+- [Training DreamBooth with diffusers](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth)
+
+### fastai
+
+- [Distributed training from Jupyter Notebooks with fastai](https://docs.fast.ai/tutorial.distributed.html)
+- [Basic distributed training examples with fastai](https://docs.fast.ai/examples/distributed_app_examples.html)
+
+### GradsFlow
+
+- [Auto Image Classification with GradsFlow](https://docs.gradsflow.com/en/latest/examples/nbs/01-ImageClassification/)
+
+### imagen-pytorch
+
+- [Fine-tuning Imagen](https://github.com/lucidrains/imagen-pytorch#usage)
+
+### Kornia
+
+- [Fine-tuning vision models with Kornia's Trainer](https://kornia.readthedocs.io/en/latest/get-started/training.html)
+
+### PyTorch Accelerated
+
+- [Quickstart distributed training tutorial with PyTorch Accelerated](https://pytorch-accelerated.readthedocs.io/en/latest/quickstart.html)
+
+### PyTorch3D
+
+- [Perform Deep Learning with 3D data](https://pytorch3d.org/tutorials/)
+
+### Stable-Dreamfusion
+
+- [Training with Stable-Dreamfusion to convert text to a 3D model](https://colab.research.google.com/drive/1MXT3yfOFvO0ooKEfiUUvTKwUkrrlCHpF?usp=sharing)
+
+### Tez
+
+- [Leaf disease detection with Tez and Accelerate](https://www.kaggle.com/code/abhishek/tez-faster-and-easier-training-for-leaf-detection/notebook)
+
+### trlx
+
+- [How to implement a sentiment learning task with trlx](https://github.com/CarperAI/trlx#example-how-to-add-a-task)
+
+### Comfy-UI
+
+- [Enabling using large Stable Diffusion Models in low-vram settings using Accelerate](https://github.com/comfyanonymous/ComfyUI/blob/master/comfy/model_management.py#L291-L296)
+
+
+## In Science
+
+Below contains a non-exhaustive list of papers utilizing Accelerate.
+
+> Don't find your paper here? Make a PR to include it!
+
+* Yuval Kirstain, Adam Polyak, Uriel Singer, Shahbuland Matiana, Joe Penna, Omer Levy: “Pick-a-Pic: An Open Dataset of User Preferences for Text-to-Image Generation”, 2023; [arXiv:2305.01569](http://arxiv.org/abs/2305.01569).
+* Lei Wang, Wanyu Xu, Yihuai Lan, Zhiqiang Hu, Yunshi Lan, Roy Ka-Wei Lee, Ee-Peng Lim: “Plan-and-Solve Prompting: Improving Zero-Shot Chain-of-Thought Reasoning by Large Language Models”, 2023; [arXiv:2305.04091](http://arxiv.org/abs/2305.04091).
+* Arthur Câmara, Claudia Hauff: “Moving Stuff Around: A study on efficiency of moving documents into memory for Neural IR models”, 2022; [arXiv:2205.08343](http://arxiv.org/abs/2205.08343).
+* Ying Sheng, Lianmin Zheng, Binhang Yuan, Zhuohan Li, Max Ryabinin, Daniel Y. Fu, Zhiqiang Xie, Beidi Chen, Clark Barrett, Joseph E. Gonzalez, Percy Liang, Christopher Ré, Ion Stoica, Ce Zhang: “High-throughput Generative Inference of Large Language Models with a Single GPU”, 2023; [arXiv:2303.06865](http://arxiv.org/abs/2303.06865).
+* Peter Melchior, Yan Liang, ChangHoon Hahn, Andy Goulding: “Autoencoding Galaxy Spectra I: Architecture”, 2022; [arXiv:2211.07890](http://arxiv.org/abs/2211.07890).
+* Jiaao Chen, Aston Zhang, Mu Li, Alex Smola, Diyi Yang: “A Cheaper and Better Diffusion Language Model with Soft-Masked Noise”, 2023; [arXiv:2304.04746](http://arxiv.org/abs/2304.04746).
+* Ayaan Haque, Matthew Tancik, Alexei A. Efros, Aleksander Holynski, Angjoo Kanazawa: “Instruct-NeRF2NeRF: Editing 3D Scenes with Instructions”, 2023; [arXiv:2303.12789](http://arxiv.org/abs/2303.12789).
+* Luke Melas-Kyriazi, Christian Rupprecht, Iro Laina, Andrea Vedaldi: “RealFusion: 360° Reconstruction of Any Object from a Single Image”, 2023; [arXiv:2302.10663](http://arxiv.org/abs/2302.10663).
+* Xiaoshi Wu, Keqiang Sun, Feng Zhu, Rui Zhao, Hongsheng Li: “Better Aligning Text-to-Image Models with Human Preference”, 2023; [arXiv:2303.14420](http://arxiv.org/abs/2303.14420).
+* Yongliang Shen, Kaitao Song, Xu Tan, Dongsheng Li, Weiming Lu, Yueting Zhuang: “HuggingGPT: Solving AI Tasks with ChatGPT and its Friends in HuggingFace”, 2023; [arXiv:2303.17580](http://arxiv.org/abs/2303.17580).
+* Yue Yang, Wenlin Yao, Hongming Zhang, Xiaoyang Wang, Dong Yu, Jianshu Chen: “Z-LaVI: Zero-Shot Language Solver Fueled by Visual Imagination”, 2022; [arXiv:2210.12261](http://arxiv.org/abs/2210.12261).
+* Sheng-Yen Chou, Pin-Yu Chen, Tsung-Yi Ho: “How to Backdoor Diffusion Models?”, 2022; [arXiv:2212.05400](http://arxiv.org/abs/2212.05400).
+* Junyoung Seo, Wooseok Jang, Min-Seop Kwak, Jaehoon Ko, Hyeonsu Kim, Junho Kim, Jin-Hwa Kim, Jiyoung Lee, Seungryong Kim: “Let 2D Diffusion Model Know 3D-Consistency for Robust Text-to-3D Generation”, 2023; [arXiv:2303.07937](http://arxiv.org/abs/2303.07937).
+* Or Patashnik, Daniel Garibi, Idan Azuri, Hadar Averbuch-Elor, Daniel Cohen-Or: “Localizing Object-level Shape Variations with Text-to-Image Diffusion Models”, 2023; [arXiv:2303.11306](http://arxiv.org/abs/2303.11306).
+* Dídac Surís, Sachit Menon, Carl Vondrick: “ViperGPT: Visual Inference via Python Execution for Reasoning”, 2023; [arXiv:2303.08128](http://arxiv.org/abs/2303.08128).
+* Chenyang Qi, Xiaodong Cun, Yong Zhang, Chenyang Lei, Xintao Wang, Ying Shan, Qifeng Chen: “FateZero: Fusing Attentions for Zero-shot Text-based Video Editing”, 2023; [arXiv:2303.09535](http://arxiv.org/abs/2303.09535).
+* Sean Welleck, Jiacheng Liu, Ximing Lu, Hannaneh Hajishirzi, Yejin Choi: “NaturalProver: Grounded Mathematical Proof Generation with Language Models”, 2022; [arXiv:2205.12910](http://arxiv.org/abs/2205.12910).
+* Elad Richardson, Gal Metzer, Yuval Alaluf, Raja Giryes, Daniel Cohen-Or: “TEXTure: Text-Guided Texturing of 3D Shapes”, 2023; [arXiv:2302.01721](http://arxiv.org/abs/2302.01721).
+* Puijin Cheng, Li Lin, Yijin Huang, Huaqing He, Wenhan Luo, Xiaoying Tang: “Learning Enhancement From Degradation: A Diffusion Model For Fundus Image Enhancement”, 2023; [arXiv:2303.04603](http://arxiv.org/abs/2303.04603).
+* Shun Shao, Yftah Ziser, Shay Cohen: “Erasure of Unaligned Attributes from Neural Representations”, 2023; [arXiv:2302.02997](http://arxiv.org/abs/2302.02997).
+* Seonghyeon Ye, Hyeonbin Hwang, Sohee Yang, Hyeongu Yun, Yireun Kim, Minjoon Seo: “In-Context Instruction Learning”, 2023; [arXiv:2302.14691](http://arxiv.org/abs/2302.14691).
+* Shikun Liu, Linxi Fan, Edward Johns, Zhiding Yu, Chaowei Xiao, Anima Anandkumar: “Prismer: A Vision-Language Model with An Ensemble of Experts”, 2023; [arXiv:2303.02506](http://arxiv.org/abs/2303.02506).
+* Haoyu Chen, Zhihua Wang, Yang Yang, Qilin Sun, Kede Ma: “Learning a Deep Color Difference Metric for Photographic Images”, 2023; [arXiv:2303.14964](http://arxiv.org/abs/2303.14964).
+* Van-Hoang Le, Hongyu Zhang: “Log Parsing with Prompt-based Few-shot Learning”, 2023; [arXiv:2302.07435](http://arxiv.org/abs/2302.07435).
+* Keito Kudo, Yoichi Aoki, Tatsuki Kuribayashi, Ana Brassard, Masashi Yoshikawa, Keisuke Sakaguchi, Kentaro Inui: “Do Deep Neural Networks Capture Compositionality in Arithmetic Reasoning?”, 2023; [arXiv:2302.07866](http://arxiv.org/abs/2302.07866).
+* Ruoyao Wang, Peter Jansen, Marc-Alexandre Côté, Prithviraj Ammanabrolu: “Behavior Cloned Transformers are Neurosymbolic Reasoners”, 2022; [arXiv:2210.07382](http://arxiv.org/abs/2210.07382).
+* Martin Wessel, Tomáš Horych, Terry Ruas, Akiko Aizawa, Bela Gipp, Timo Spinde: “Introducing MBIB -- the first Media Bias Identification Benchmark Task and Dataset Collection”, 2023; [arXiv:2304.13148](http://arxiv.org/abs/2304.13148). DOI: [https://dx.doi.org/10.1145/3539618.3591882 10.1145/3539618.3591882].
+* Hila Chefer, Yuval Alaluf, Yael Vinker, Lior Wolf, Daniel Cohen-Or: “Attend-and-Excite: Attention-Based Semantic Guidance for Text-to-Image Diffusion Models”, 2023; [arXiv:2301.13826](http://arxiv.org/abs/2301.13826).
+* Marcio Fonseca, Yftah Ziser, Shay B. Cohen: “Factorizing Content and Budget Decisions in Abstractive Summarization of Long Documents”, 2022; [arXiv:2205.12486](http://arxiv.org/abs/2205.12486).
+* Elad Richardson, Gal Metzer, Yuval Alaluf, Raja Giryes, Daniel Cohen-Or: “TEXTure: Text-Guided Texturing of 3D Shapes”, 2023; [arXiv:2302.01721](http://arxiv.org/abs/2302.01721).
+* Tianxing He, Jingyu Zhang, Tianle Wang, Sachin Kumar, Kyunghyun Cho, James Glass, Yulia Tsvetkov: “On the Blind Spots of Model-Based Evaluation Metrics for Text Generation”, 2022; [arXiv:2212.10020](http://arxiv.org/abs/2212.10020).
+* Ori Ram, Yoav Levine, Itay Dalmedigos, Dor Muhlgay, Amnon Shashua, Kevin Leyton-Brown, Yoav Shoham: “In-Context Retrieval-Augmented Language Models”, 2023; [arXiv:2302.00083](http://arxiv.org/abs/2302.00083).
+* Dacheng Li, Rulin Shao, Hongyi Wang, Han Guo, Eric P. Xing, Hao Zhang: “MPCFormer: fast, performant and private Transformer inference with MPC”, 2022; [arXiv:2211.01452](http://arxiv.org/abs/2211.01452).
+* Baolin Peng, Michel Galley, Pengcheng He, Chris Brockett, Lars Liden, Elnaz Nouri, Zhou Yu, Bill Dolan, Jianfeng Gao: “GODEL: Large-Scale Pre-Training for Goal-Directed Dialog”, 2022; [arXiv:2206.11309](http://arxiv.org/abs/2206.11309).
+* Egil Rønningstad, Erik Velldal, Lilja Øvrelid: “Entity-Level Sentiment Analysis (ELSA): An exploratory task survey”, 2023, Proceedings of the 29th International Conference on Computational Linguistics, 2022, pages 6773-6783; [arXiv:2304.14241](http://arxiv.org/abs/2304.14241).
+* Charlie Snell, Ilya Kostrikov, Yi Su, Mengjiao Yang, Sergey Levine: “Offline RL for Natural Language Generation with Implicit Language Q Learning”, 2022; [arXiv:2206.11871](http://arxiv.org/abs/2206.11871).
+* Zhiruo Wang, Shuyan Zhou, Daniel Fried, Graham Neubig: “Execution-Based Evaluation for Open-Domain Code Generation”, 2022; [arXiv:2212.10481](http://arxiv.org/abs/2212.10481).
+* Minh-Long Luu, Zeyi Huang, Eric P. Xing, Yong Jae Lee, Haohan Wang: “Expeditious Saliency-guided Mix-up through Random Gradient Thresholding”, 2022; [arXiv:2212.04875](http://arxiv.org/abs/2212.04875).
+* Jun Hao Liew, Hanshu Yan, Daquan Zhou, Jiashi Feng: “MagicMix: Semantic Mixing with Diffusion Models”, 2022; [arXiv:2210.16056](http://arxiv.org/abs/2210.16056).
+* Yaqing Wang, Subhabrata Mukherjee, Xiaodong Liu, Jing Gao, Ahmed Hassan Awadallah, Jianfeng Gao: “LiST: Lite Prompted Self-training Makes Parameter-Efficient Few-shot Learners”, 2021; [arXiv:2110.06274](http://arxiv.org/abs/2110.06274).
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/README.md b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..27938cd7f97debc26983a2dfb5044ab23cca8b3f
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/README.md
@@ -0,0 +1,276 @@
+
+
+# In this folder we showcase various full examples using 🤗 Accelerate
+
+## Simple NLP example
+
+The [nlp_example.py](./nlp_example.py) script is a simple example to train a Bert model on a classification task ([GLUE's MRPC](https://www.microsoft.com/en-us/download/details.aspx?id=52398)).
+
+Prior to running it you should install 🤗 Dataset and 🤗 Transformers:
+
+```bash
+pip install datasets evaluate transformers
+```
+
+The same script can be run in any of the following configurations:
+- single CPU or single GPU
+- multi CPUs
+- multi GPUs (using PyTorch distributed mode)
+- (multi) TPUs
+- fp16 (mixed-precision) or fp32 (normal precision)
+
+To run it in each of these various modes, use the following commands:
+- single CPU:
+ * from a server without GPU
+ ```bash
+ python ./nlp_example.py
+ ```
+ * from any server by passing `cpu=True` to the `Accelerator`.
+ ```bash
+ python ./nlp_example.py --cpu
+ ```
+ * from any server with Accelerate launcher
+ ```bash
+ accelerate launch --cpu ./nlp_example.py
+ ```
+- single GPU:
+ ```bash
+ python ./nlp_example.py # from a server with a GPU
+ ```
+- with fp16 (mixed-precision)
+ * from any server by passing `mixed_precison=fp16` to the `Accelerator`.
+ ```bash
+ python ./nlp_example.py --mixed_precision fp16
+ ```
+ * from any server with Accelerate launcher
+ ```bash
+ accelerate launch --mixed_precision fp16 ./nlp_example.py
+- multi CPUs (requires Open MPI, Intel MPI, or MVAPICH)
+ * With Accelerate config and launcher, execute the following from node 0:
+ ```bash
+ accelerate config # Select to have accelerate launch mpirun
+ accelerate launch ./nlp_example.py # This will run the script on each server
+ ```
+ * With Intel MPI:
+ ```bash
+ export CCL_WORKER_COUNT=1
+ export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip
+ mpirun -f hostfile -n 16 -ppn 4 python ./nlp_example.py
+ ```
+- multi GPUs (using PyTorch distributed mode)
+ * With Accelerate config and launcher
+ ```bash
+ accelerate config # This will create a config file on your server
+ accelerate launch ./nlp_example.py # This will run the script on your server
+ ```
+ * With traditional PyTorch launcher (`python -m torch.distributed.run` can be used instead of `torchrun`)
+ ```bash
+ torchrun --nproc_per_node 2 ./nlp_example.py
+ ```
+- multi GPUs, multi node (several machines, using PyTorch distributed mode)
+ * With Accelerate config and launcher, on each machine:
+ ```bash
+ accelerate config # This will create a config file on each server
+ accelerate launch ./nlp_example.py # This will run the script on each server
+ ```
+ * With PyTorch launcher only (`python -m torch.distributed.run` can be used instead of `torchrun`). Run this command on each node:
+ ```bash
+ torchrun \ # python -m torch.distributed.run
+ --nproc_per_node 2 \
+ --nnodes 2 \
+ --rdzv_id 2299 \ # A unique job id
+ --rdzv_backend c10d \
+ --rdzv_endpoint master_node_ip_address:29500 \
+ ./nlp_example.py
+ ```
+- (multi) TPUs
+ * With Accelerate config and launcher
+ ```bash
+ accelerate config # This will create a config file on your TPU server
+ accelerate launch ./nlp_example.py # This will run the script on each server
+ ```
+ * In PyTorch:
+ Add an `xmp.spawn` line in your script as you usually do.
+
+
+## Simple vision example
+
+The [cv_example.py](./cv_example.py) script is a simple example to fine-tune a ResNet-50 on a classification task ([Ofxord-IIT Pet Dataset](https://www.robots.ox.ac.uk/~vgg/data/pets/)).
+
+The same script can be run in any of the following configurations:
+- single CPU or single GPU
+- multi CPUs
+- multi GPUs (using PyTorch distributed mode)
+- (multi) TPUs
+- fp16 (mixed-precision) or fp32 (normal precision)
+
+Prior to running it you should install timm and torchvision:
+
+```bash
+pip install timm torchvision
+```
+
+and you should download the data with the following commands:
+
+```bash
+wget https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz
+tar -xzf images.tar.gz
+```
+
+To run it in each of these various modes, use the following commands:
+- single CPU:
+ * from a server without GPU
+ ```bash
+ python ./cv_example.py --data_dir path_to_data
+ ```
+ * from any server by passing `cpu=True` to the `Accelerator`.
+ ```bash
+ python ./cv_example.py --data_dir path_to_data --cpu
+ ```
+ * from any server with Accelerate launcher
+ ```bash
+ accelerate launch --cpu ./cv_example.py --data_dir path_to_data
+ ```
+- single GPU:
+ ```bash
+ python ./cv_example.py # from a server with a GPU
+ ```
+- with fp16 (mixed-precision)
+ * from any server by passing `mixed_precison=fp16` to the `Accelerator`.
+ ```bash
+ python ./cv_example.py --data_dir path_to_data --mixed_precison fp16
+ ```
+ * from any server with Accelerate launcher
+ ```bash
+ accelerate launch --mixed_precison fp16 ./cv_example.py --data_dir path_to_data
+- multi CPUs (requires Open MPI, Intel MPI, or MVAPICH)
+ * With Accelerate config and launcher, run the following from node 0:
+ ```bash
+ accelerate config --config_file config.yaml # Select to have accelerate launch mpirun
+ accelerate launch ./cv_example.py --data_dir path_to_data # This will run the script on each server
+ ```
+ * With Intel MPI, execute mpirun from node 0:
+ ```bash
+ export CCL_WORKER_COUNT=1
+ export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip
+ mpirun -f hostfile -n 16 -ppn 4 python ./cv_example.py --data_dir path_to_data
+ ```
+- multi GPUs (using PyTorch distributed mode)
+ * With Accelerate config and launcher
+ ```bash
+ accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml`
+ accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on your server
+ ```
+ * With traditional PyTorch launcher (`python -m torch.distributed.run` can be used instead of `torchrun`)
+ ```bash
+ torchrun --nproc_per_node 2 ./cv_example.py --data_dir path_to_data
+ ```
+- multi GPUs, multi node (several machines, using PyTorch distributed mode)
+ * With Accelerate config and launcher, on each machine:
+ ```bash
+ accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml`
+ accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on each server
+ ```
+ * With PyTorch launcher only (`python -m torch.distributed.run` can be used instead of `torchrun`). Run this command on each node:
+ ```bash
+ torchrun \ # python -m torch.distributed.run
+ --nproc_per_node 2 \
+ --nnodes 2 \
+ --rdzv_id 2299 \ # A unique job id
+ --rdzv_backend c10d \
+ --rdzv_endpoint master_node_ip_address:29500 \
+ ./cv_example.py --data_dir path_to_data
+ ```
+- (multi) TPUs
+ * With Accelerate config and launcher
+ ```bash
+ accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml`
+ accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on each server
+ ```
+ * In PyTorch:
+ Add an `xmp.spawn` line in your script as you usually do.
+
+### Simple vision example (GANs)
+
+- [huggan project](https://github.com/huggingface/community-events/tree/main/huggan)
+
+
+### Using AWS SageMaker integration
+- [Examples showcasing AWS SageMaker integration of 🤗 Accelerate.](https://github.com/pacman100/accelerate-aws-sagemaker)
+
+## Configuration zoo
+In [/config_yaml_templates](./config_yaml_templates/) we have a variety of *minimal* `config.yaml` templates and examples to help you learn
+how to create your own configuration files depending on the scenario.
+
+## SLURM Scripts
+In [/slurm/submit_multigpu.sh](./slurm/submit_multigpu.sh) and [/slurm/submit_multinode.sh](./slurm/submit_multinode.sh) we present two scripts for running the examples on a machine with [SLURM](https://slurm.schedmd.com/documentation.html) workload manager.
+
+In [/slurm/submit_multigpu.sh](./slurm/submit_multigpu.sh) the only parameter in the launcher that needs to be modified is `--num_processes`, which determines the number of GPUs we will use. In this case, using the environment variable `$SLURM_GPUS`, we indicate that we want to utilize all the GPUs available on the node we have requested.
+
+In [/slurm/submit_multinode.sh](./slurm/submit_multinode.sh) we must specify the number of nodes that will be part of the training (`--num_machines`), how many GPUs we will use in total (`--num_processes`), the [`backend`](https://pytorch.org/docs/stable/elastic/run.html#note-on-rendezvous-backend), `--main_process_ip` which will be the address the master node and the `--main_process_port`.
+
+In [/slurm/submit_multicpu.sh](./slurm/submit_multicpu.sh) we must specify the number of nodes that will be part of the training (`--num_machines`), how many CPU processes we will use in total (`--num_processes`), the [`backend`](https://pytorch.org/docs/stable/elastic/run.html#note-on-rendezvous-backend), `--main_process_ip` which will be the address the master node and the `--main_process_port`. `mpirun_hostfile` specifies to run the job using MPIRun.
+
+In both scripts, we run `activateEnviroment.sh` at the beginning. This script should contain the necessary instructions to initialize the environment for execution. Below, we show an example that loads the necessary libraries ([Environment modules](https://github.com/cea-hpc/modules)), activates the Python environment, and sets up various environment variables, most of them to run the scripts in offline mode in case we don't have internet connection from the cluster.
+
+```bash
+# activateEnvironment.sh
+module purge
+module load anaconda3/2020.02 cuda/10.2 cudnn/8.0.5 nccl/2.9.9 arrow/7.0.0 openmpi
+source activate /home/nct01/nct01328/pytorch_antoni_local
+
+export HF_HOME=/gpfs/projects/nct01/nct01328/
+export HF_LOCAL_HOME=/gpfs/projects/nct01/nct01328/HF_LOCAL
+export HF_DATASETS_OFFLINE=1
+export TRANSFORMERS_OFFLINE=1
+export PYTHONPATH=/home/nct01/nct01328/transformers-in-supercomputers:$PYTHONPATH
+export GPUS_PER_NODE=4
+```
+
+## Simple Multi-GPU Hardware Launcher (using an external platform)
+
+[multigpu_remote_launcher.py](./multigpu_remote_launcher.py) is a minimal script that demonstrates launching accelerate
+on multiple remote GPUs, and with automatic hardware environment and dependency setup for reproducibility. You can
+easily customize the training function used, training arguments, hyperparameters, and type of compute hardware, and then
+run the script to automatically launch multi GPU training on remote hardware.
+
+This script uses [Runhouse](https://github.com/run-house/runhouse) to launch on self-hosted hardware (e.g. in your own
+cloud account or on-premise cluster) but there are other options for running remotely as well. Runhouse can be installed
+with `pip install runhouse`, and you can refer to
+[hardware setup](https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup)
+for hardware setup instructions, or this
+[Colab tutorial](https://colab.research.google.com/drive/1qVwYyLTCPYPSdz9ZX7BZl9Qm0A3j7RJe) for a more in-depth walkthrough.
+
+## Finer Examples
+
+While the first two scripts are extremely barebones when it comes to what you can do with accelerate, more advanced features are documented in two other locations.
+
+### `by_feature` examples
+
+These scripts are *individual* examples highlighting one particular feature or use-case within Accelerate. They all stem from the [nlp_example.py](./nlp_example.py) script, and any changes or modifications is denoted with a `# New Code #` comment.
+
+Read the README.md file located in the `by_feature` folder for more information.
+
+### `complete_*` examples
+
+These two scripts contain *every* single feature currently available in Accelerate in one place, as one giant script.
+
+New arguments that can be passed include:
+
+- `checkpointing_steps`, whether the various states should be saved at the end of every `n` steps, or `"epoch"` for each epoch. States are then saved to folders named `step_{n}` or `epoch_{n}`
+- `resume_from_checkpoint`, should be used if you want to resume training off of a previous call to the script and passed a `checkpointing_steps` to it.
+- `with_tracking`, should be used if you want to log the training run using all available experiment trackers in your environment. Currently supported trackers include TensorBoard, Weights and Biases, and CometML.
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/README.md b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..7b825dd18b3594be13e818c7b895637c3e76b6d2
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/README.md
@@ -0,0 +1,121 @@
+# What are these scripts?
+
+All scripts in this folder originate from the `nlp_example.py` file, as it is a very simplistic NLP training example using Accelerate with zero extra features.
+
+From there, each further script adds in just **one** feature of Accelerate, showing how you can quickly modify your own scripts to implement these capabilities.
+
+A full example with all of these parts integrated together can be found in the `complete_nlp_example.py` script and `complete_cv_example.py` script.
+
+Adjustments to each script from the base `nlp_example.py` file can be found quickly by searching for "# New Code #"
+
+## Example Scripts by Feature and their Arguments
+
+### Base Example (`../nlp_example.py`)
+
+- Shows how to use `Accelerator` in an extremely simplistic PyTorch training loop
+- Arguments available:
+ - `mixed_precision`, whether to use mixed precision. ("no", "fp16", or "bf16")
+ - `cpu`, whether to train using only the CPU. (yes/no/1/0)
+
+All following scripts also accept these arguments in addition to their added ones.
+
+These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torch.distributed.run`), such as:
+
+```bash
+accelerate launch ../nlp_example.py --mixed_precision fp16 --cpu 0
+```
+
+### Checkpointing and Resuming Training (`checkpointing.py`)
+
+- Shows how to use `Accelerator.save_state` and `Accelerator.load_state` to save or continue training
+- **It is assumed you are continuing off the same training script**
+- Arguments available:
+ - `checkpointing_steps`, after how many steps the various states should be saved. ("epoch", 1, 2, ...)
+ - `output_dir`, where saved state folders should be saved to, default is current working directory
+ - `resume_from_checkpoint`, what checkpoint folder to resume from. ("epoch_0", "step_22", ...)
+
+These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
+
+(Note, `resume_from_checkpoint` assumes that we've ran the script for one epoch with the `--checkpointing_steps epoch` flag)
+
+```bash
+accelerate launch ./checkpointing.py --checkpointing_steps epoch output_dir "checkpointing_tutorial" --resume_from_checkpoint "checkpointing_tutorial/epoch_0"
+```
+
+### Cross Validation (`cross_validation.py`)
+
+- Shows how to use `Accelerator.free_memory` and run cross validation efficiently with `datasets`.
+- Arguments available:
+ - `num_folds`, the number of folds the training dataset should be split into.
+
+These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
+
+```bash
+accelerate launch ./cross_validation.py --num_folds 2
+```
+
+### Experiment Tracking (`tracking.py`)
+
+- Shows how to use `Accelerate.init_trackers` and `Accelerator.log`
+- Can be used with Weights and Biases, TensorBoard, or CometML.
+- Arguments available:
+ - `with_tracking`, whether to load in all available experiment trackers from the environment.
+
+These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
+
+```bash
+accelerate launch ./tracking.py --with_tracking
+```
+
+### Gradient Accumulation (`gradient_accumulation.py`)
+
+- Shows how to use `Accelerator.no_sync` to prevent gradient averaging in a distributed setup.
+- Arguments available:
+ - `gradient_accumulation_steps`, the number of steps to perform before the gradients are accumulated and the optimizer and scheduler are stepped + zero_grad
+
+These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
+
+```bash
+accelerate launch ./gradient_accumulation.py --gradient_accumulation_steps 5
+```
+
+### LocalSGD (`local_sgd.py`)
+- Shows how to use `Accelerator.no_sync` to prevent gradient averaging in a distributed setup. However, unlike gradient accumulation, this method does not change the effective batch size. Local SGD can be combined with gradient accumulation.
+
+These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
+
+```bash
+accelerate launch ./local_sgd.py --local_sgd_steps 4
+```
+
+### DDP Communication Hook (`ddp_comm_hook.py`)
+
+- Shows how to use DDP Communication Hooks to control and optimize gradient communication across workers in a DistributedDataParallel setup.
+- Arguments available:
+ - `ddp_comm_hook`, the type of DDP communication hook to use. Choose between `no`, `fp16`, `bf16`, `power_sgd`, and `batched_power_sgd`.
+
+These arguments should be added at the end of any method for starting the python script (such as `accelerate launch`, `python -m torch.distributed.run`), such as:
+
+```bash
+accelerate launch ./ddp_comm_hook.py --mixed_precision fp16 --ddp_comm_hook power_sgd
+```
+
+### Profiler (`profiler.py`)
+
+- Shows how to use the profiling capabilities of `Accelerate` to profile PyTorch models during training.
+- Uses the `ProfileKwargs` handler to customize profiling options, including activities, scheduling, and additional profiling options.
+- Can generate and save profiling traces in JSON format for visualization in Chrome's tracing tool.
+
+Arguments available:
+- `--record_shapes`: If passed, records shapes for profiling.
+- `--profile_memory`: If passed, profiles memory usage.
+- `--with_stack`: If passed, profiles stack traces.
+- `--with_flops`: If passed, profiles floating point operations (FLOPS).
+- `--output_trace_dir`: If specified, saves the profiling trace to the given dir in JSON format.
+- `--cpu`: If passed, trains on the CPU instead of GPU.
+
+These arguments should be added at the end of any method for starting the Python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
+
+```bash
+accelerate launch ./profiler.py --record_shapes --profile_memory --with_flops --output_trace_dir "profiler"
+```
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/automatic_gradient_accumulation.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/automatic_gradient_accumulation.py
new file mode 100644
index 0000000000000000000000000000000000000000..c610f7704c301d372074b5fcd289e9df4653cf9f
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/automatic_gradient_accumulation.py
@@ -0,0 +1,243 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+# New Code #
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator
+from accelerate.utils import find_executable_batch_size
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate,
+# specifically showcasing how to combine both the gradient accumulation
+# and automatic batch size finder utilities of Accelerate to perfrom
+# automatic gradient accumulation
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# New additions from the base script can be found quickly by
+# looking for the # New Code # tags
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ observed_batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ # New Code #
+ # We use the `find_executable_batch_size` decorator, passing in the desired observed batch size
+ # to train on. If a CUDA OOM error occurs, it will retry this loop cutting the batch size in
+ # half each time. From this, we can calculate the number of gradient accumulation steps needed
+ # and modify the Accelerator object as a result
+ @find_executable_batch_size(starting_batch_size=int(observed_batch_size))
+ def inner_training_loop(batch_size):
+ # Since we need to modify the outside accelerator object, we need to bring it
+ # to the local scope
+ nonlocal accelerator
+
+ # We can calculate the number of gradient accumulation steps based on the current
+ # batch size vs the starting batch size
+ num_gradient_accumulation_steps = observed_batch_size // batch_size
+
+ # And then set it in the Accelerator directly:
+ accelerator.gradient_accumulation_steps = num_gradient_accumulation_steps
+
+ # Next we need to free all of the stored model references in the Accelerator each time
+ accelerator.free_memory()
+
+ # And set the seed so our results are reproducable each reset
+ set_seed(seed)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs),
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ # And perform gradient accumulation
+ with accelerator.accumulate(model):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+
+ # New Code #
+ # And call it at the end with no arguments
+ # Note: You could also refactor this outside of your training loop function
+ inner_training_loop()
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ # New Code #
+ # We modify the starting batch size to be an observed batch size of 256, to guarentee an initial CUDA OOM
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 256}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/checkpointing.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/checkpointing.py
new file mode 100644
index 0000000000000000000000000000000000000000..218f4a50914b85d1d29ddfb6e1f0e33246b90be5
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/checkpointing.py
@@ -0,0 +1,326 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup
+
+from accelerate import Accelerator, DataLoaderConfiguration, DistributedType
+from accelerate.utils import set_seed
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate,
+# specifically showcasing the checkpointing capability,
+# and builds off the `nlp_example.py` script.
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To help focus on the differences in the code, building `DataLoaders`
+# was refactored into its own function.
+# New additions from the base script can be found quickly by
+# looking for the # New Code # tags
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # Initialize accelerator
+ dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader)
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config)
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ # New Code #
+ # Parse out whether we are saving every epoch or after a certain number of batches
+ if hasattr(args.checkpointing_steps, "isdigit"):
+ if args.checkpointing_steps == "epoch":
+ checkpointing_steps = args.checkpointing_steps
+ elif args.checkpointing_steps.isdigit():
+ checkpointing_steps = int(args.checkpointing_steps)
+ else:
+ raise ValueError(
+ f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
+ )
+ else:
+ checkpointing_steps = None
+
+ set_seed(seed)
+
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ metric = evaluate.load("glue", "mrpc")
+
+ # If the batch size is too big we use gradient accumulation
+ gradient_accumulation_steps = 1
+ if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
+ gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
+ batch_size = MAX_GPU_BATCH_SIZE
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # New Code #
+ # We need to keep track of how many total steps we have iterated over
+ overall_step = 0
+ # We also need to keep track of the stating epoch so files are named properly
+ starting_epoch = 0
+
+ # We need to load the checkpoint back in before training here with `load_state`
+ # The total number of epochs is adjusted based on where the state is being loaded from,
+ # as we assume continuation of the same training script
+ if args.resume_from_checkpoint:
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
+ accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
+ accelerator.load_state(args.resume_from_checkpoint)
+ path = os.path.basename(args.resume_from_checkpoint)
+ else:
+ # Get the most recent checkpoint
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
+ dirs.sort(key=os.path.getctime)
+ path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ # Extract `epoch_{i}` or `step_{i}`
+ training_difference = os.path.splitext(path)[0]
+
+ if "epoch" in training_difference:
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
+ resume_step = None
+ else:
+ resume_step = int(training_difference.replace("step_", ""))
+ starting_epoch = resume_step // len(train_dataloader)
+ resume_step -= starting_epoch * len(train_dataloader)
+
+ # Now we train the model
+ for epoch in range(starting_epoch, num_epochs):
+ model.train()
+ # New Code #
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We need to skip steps until we reach the resumed step only if we are not using a stateful dataloader
+ if not args.use_stateful_dataloader:
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ overall_step += resume_step
+ else:
+ # After the first iteration though, we need to go back to the original dataloader
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ # New Code #
+ overall_step += 1
+
+ # New Code #
+ # We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
+ # These are saved to folders named `step_{overall_step}`
+ # Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
+ # If mixed precision was used, will also save a "scalar.bin" file
+ if isinstance(checkpointing_steps, int):
+ output_dir = f"step_{overall_step}"
+ if overall_step % checkpointing_steps == 0:
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True` (the default).
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+
+ # New Code #
+ # We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
+ # These are saved to folders named `epoch_{epoch}`
+ # Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
+ # If mixed precision was used, will also save a "scalar.bin" file
+ if checkpointing_steps == "epoch":
+ output_dir = f"epoch_{epoch}"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ parser.add_argument(
+ "--checkpointing_steps",
+ type=str,
+ default=None,
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
+ )
+ parser.add_argument(
+ "--output_dir",
+ type=str,
+ default=".",
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
+ )
+ parser.add_argument(
+ "--resume_from_checkpoint",
+ type=str,
+ default=None,
+ help="If the training should continue from a checkpoint folder.",
+ )
+ parser.add_argument(
+ "--use_stateful_dataloader",
+ action="store_true",
+ help="If the dataloader should be a resumable stateful dataloader.",
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/cross_validation.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/cross_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..162034287c751291fdf6aa7b6e79b0a918ddcbd0
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/cross_validation.py
@@ -0,0 +1,280 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+
+import evaluate
+import numpy as np
+import torch
+from datasets import DatasetDict, load_dataset
+
+# New Code #
+# We'll be using StratifiedKFold for this example
+from sklearn.model_selection import StratifiedKFold
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate,
+# specifically showcasing how to perform Cross Validation,
+# and builds off the `nlp_example.py` script.
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To help focus on the differences in the code, building `DataLoaders`
+# was refactored into its own function.
+# New additions from the base script can be found quickly by
+# looking for the # New Code # tags
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+# New Code #
+# We need a different `get_dataloaders` function that will build dataloaders by index
+
+
+def get_fold_dataloaders(
+ accelerator: Accelerator, dataset: DatasetDict, train_idxs: list[int], valid_idxs: list[int], batch_size: int = 16
+):
+ """
+ Gets a set of train, valid, and test dataloaders for a particular fold
+
+ Args:
+ accelerator (`Accelerator`):
+ The main `Accelerator` object
+ train_idxs (list of `int`):
+ The split indices for the training dataset
+ valid_idxs (list of `int`):
+ The split indices for the validation dataset
+ batch_size (`int`):
+ The size of the minibatch. Default is 16
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = DatasetDict(
+ {
+ "train": dataset["train"].select(train_idxs),
+ "validation": dataset["train"].select(valid_idxs),
+ "test": dataset["validation"],
+ }
+ )
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ test_dataloader = DataLoader(
+ tokenized_datasets["test"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader, test_dataloader
+
+
+def training_function(config, args):
+ # New Code #
+ test_predictions = []
+ # Download the dataset
+ datasets = load_dataset("glue", "mrpc")
+ # Create our splits
+ kfold = StratifiedKFold(n_splits=int(args.num_folds))
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ # If the batch size is too big we use gradient accumulation
+ gradient_accumulation_steps = 1
+ if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
+ gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
+ batch_size = MAX_GPU_BATCH_SIZE
+
+ set_seed(seed)
+
+ # New Code #
+ # Create our folds:
+ folds = kfold.split(np.zeros(datasets["train"].num_rows), datasets["train"]["label"])
+ test_references = []
+ # Iterate over them
+ for i, (train_idxs, valid_idxs) in enumerate(folds):
+ train_dataloader, eval_dataloader, test_dataloader = get_fold_dataloaders(
+ accelerator,
+ datasets,
+ train_idxs,
+ valid_idxs,
+ )
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+
+ # New Code #
+ # We also run predictions on the test set at the very end
+ fold_predictions = []
+ for step, batch in enumerate(test_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ fold_predictions.append(predictions.cpu())
+ if i == 0:
+ # We need all of the test predictions
+ test_references.append(references.cpu())
+ # Use accelerator.print to print only on the main process.
+ test_predictions.append(torch.cat(fold_predictions, dim=0))
+ # We now need to release all our memory and get rid of the current model, optimizer, etc
+ model, optimizer = accelerator.free_memory(model, optimizer)
+ # New Code #
+ # Finally we check the accuracy of our folded results:
+ test_references = torch.cat(test_references, dim=0)
+ preds = torch.stack(test_predictions, dim=0).sum(dim=0).div(int(args.num_folds)).argmax(dim=-1)
+ test_metric = metric.compute(predictions=preds, references=test_references)
+ accelerator.print("Average test metrics from all folds:", test_metric)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ # New Code #
+ parser.add_argument("--num_folds", type=int, default=3, help="The number of splits to perform across the dataset")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/ddp_comm_hook.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/ddp_comm_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7028b597939a5e3d4bb2bc4a589de26f53a9da5
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/ddp_comm_hook.py
@@ -0,0 +1,232 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+from accelerate.utils import DDPCommunicationHookType, DistributedDataParallelKwargs
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+# and perform ddp communication hook
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # New Code #
+ ddp_comm_hook_type = DDPCommunicationHookType(args.ddp_comm_hook)
+ ddp_comm_wrapper = DDPCommunicationHookType(args.ddp_comm_wrapper)
+ ddp_kwargs = DistributedDataParallelKwargs(comm_hook=ddp_comm_hook_type, comm_wrapper=ddp_comm_wrapper)
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, kwargs_handlers=[ddp_kwargs])
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs),
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ # We use the new `accumulate` context manager to perform gradient accumulation
+ with accelerator.accumulate(model):
+ output = model(**batch)
+ loss = output.loss
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ # New Code #
+ parser.add_argument(
+ "--ddp_comm_hook",
+ type=str,
+ default="no",
+ choices=["no", "fp16", "bf16", "power_sgd", "batched_power_sgd"],
+ help="DDP Communication hook to use. Choose between `no`, `fp16`, `bf16`, `power_sgd`, and `batched_power_sgd`.",
+ )
+ # New Code #
+ parser.add_argument(
+ "--ddp_comm_wrapper",
+ type=str,
+ default="no",
+ choices=["no", "fp16", "bf16"],
+ help="DDP Communication wrapper to use. Choose between `no`, `fp16`, and `bf16`.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/deepspeed_with_config_support.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/deepspeed_with_config_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff7535761af689cfe1d83153f1226245f422c4cf
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/deepspeed_with_config_support.py
@@ -0,0 +1,723 @@
+#!/usr/bin/env python
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...)
+on a text file or a dataset without using HuggingFace Trainer.
+
+Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
+https://huggingface.co/models?filter=text-generation
+"""
+# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
+
+import argparse
+import json
+import logging
+import math
+import os
+import random
+from itertools import chain
+from pathlib import Path
+
+import datasets
+import torch
+import transformers
+from datasets import load_dataset
+from huggingface_hub import HfApi
+from torch.utils.data import DataLoader
+from tqdm.auto import tqdm
+from transformers import (
+ CONFIG_MAPPING,
+ MODEL_MAPPING,
+ AutoConfig,
+ AutoModelForCausalLM,
+ AutoTokenizer,
+ SchedulerType,
+ default_data_collator,
+ get_scheduler,
+)
+from transformers.utils.versions import require_version
+
+from accelerate import Accelerator, DistributedType
+from accelerate.logging import get_logger
+from accelerate.utils import DummyOptim, DummyScheduler, set_seed
+
+
+logger = get_logger(__name__)
+
+require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
+
+MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
+MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task")
+ parser.add_argument(
+ "--dataset_name",
+ type=str,
+ default=None,
+ help="The name of the dataset to use (via the datasets library).",
+ )
+ parser.add_argument(
+ "--dataset_config_name",
+ type=str,
+ default=None,
+ help="The configuration name of the dataset to use (via the datasets library).",
+ )
+ parser.add_argument(
+ "--train_file", type=str, default=None, help="A csv or a json file containing the training data."
+ )
+ parser.add_argument(
+ "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
+ )
+ parser.add_argument(
+ "--validation_split_percentage",
+ default=5,
+ help="The percentage of the train set used as validation set in case there's no validation split",
+ )
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
+ required=False,
+ )
+ parser.add_argument(
+ "--config_name",
+ type=str,
+ default=None,
+ help="Pretrained config name or path if not the same as model_name",
+ )
+ parser.add_argument(
+ "--tokenizer_name",
+ type=str,
+ default=None,
+ help="Pretrained tokenizer name or path if not the same as model_name",
+ )
+ parser.add_argument(
+ "--use_slow_tokenizer",
+ action="store_true",
+ help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
+ )
+ parser.add_argument(
+ "--per_device_train_batch_size",
+ type=int,
+ default=8,
+ help="Batch size (per device) for the training dataloader.",
+ )
+ parser.add_argument(
+ "--per_device_eval_batch_size",
+ type=int,
+ default=8,
+ help="Batch size (per device) for the evaluation dataloader.",
+ )
+ parser.add_argument(
+ "--learning_rate",
+ type=float,
+ default=5e-5,
+ help="Initial learning rate (after the potential warmup period) to use.",
+ )
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
+ parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
+ parser.add_argument(
+ "--max_train_steps",
+ type=int,
+ default=None,
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
+ )
+ parser.add_argument(
+ "--gradient_accumulation_steps",
+ type=int,
+ default=1,
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
+ )
+ parser.add_argument(
+ "--lr_scheduler_type",
+ type=SchedulerType,
+ default="linear",
+ help="The scheduler type to use.",
+ choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
+ )
+ parser.add_argument(
+ "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
+ )
+ parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
+ parser.add_argument(
+ "--model_type",
+ type=str,
+ default=None,
+ help="Model type to use if training from scratch.",
+ choices=MODEL_TYPES,
+ )
+ parser.add_argument(
+ "--block_size",
+ type=int,
+ default=None,
+ help=(
+ "Optional input sequence length after tokenization. The training dataset will be truncated in block of"
+ " this size for training. Default to the model max input length for single sentence inputs (take into"
+ " account special tokens)."
+ ),
+ )
+ parser.add_argument(
+ "--preprocessing_num_workers",
+ type=int,
+ default=None,
+ help="The number of processes to use for the preprocessing.",
+ )
+ parser.add_argument(
+ "--overwrite_cache", type=bool, default=False, help="Overwrite the cached training and evaluation sets"
+ )
+ parser.add_argument(
+ "--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files."
+ )
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
+ parser.add_argument(
+ "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
+ )
+ parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--checkpointing_steps",
+ type=str,
+ default=None,
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
+ )
+ parser.add_argument(
+ "--resume_from_checkpoint",
+ type=str,
+ default=None,
+ help="If the training should continue from a checkpoint folder.",
+ )
+ # New Code #
+ # Whether to load the best model at the end of training
+ parser.add_argument(
+ "--load_best_model",
+ action="store_true",
+ help="Whether to load the best model at the end of training",
+ )
+ parser.add_argument(
+ "--with_tracking",
+ action="store_true",
+ help="Whether to enable experiment trackers for logging.",
+ )
+ parser.add_argument(
+ "--report_to",
+ type=str,
+ default="all",
+ help=(
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
+ ' `"wandb"`, `"comet_ml"`, and `"dvclive"`. Use `"all"` (default) to report to all integrations.'
+ "Only applicable when `--with_tracking` is passed."
+ ),
+ )
+ args = parser.parse_args()
+
+ # Sanity checks
+ if args.dataset_name is None and args.train_file is None and args.validation_file is None:
+ raise ValueError("Need either a dataset name or a training/validation file.")
+ else:
+ if args.train_file is not None:
+ extension = args.train_file.split(".")[-1]
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
+ if args.validation_file is not None:
+ extension = args.validation_file.split(".")[-1]
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
+
+ if args.push_to_hub:
+ assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
+
+ return args
+
+
+# New Code #
+def evaluate(args, model, eval_dataloader, accelerator, eval_dataset):
+ model.eval()
+ losses = []
+ for step, batch in enumerate(eval_dataloader):
+ with torch.no_grad():
+ outputs = model(**batch)
+
+ loss = outputs.loss
+ losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size)))
+
+ losses = torch.cat(losses)
+ try:
+ eval_loss = torch.mean(losses)
+ perplexity = math.exp(eval_loss)
+ except OverflowError:
+ perplexity = float("inf")
+ return perplexity, eval_loss
+
+
+def main():
+ args = parse_args()
+
+ # Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
+ # If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
+ # in the environment
+
+ # when using DeepSpeed, the `gradient_accumulation_steps` is properly set from the DeepSpeed plugin/config
+ # or from `accelerate launch` via `--gradient_accumulation_steps` else
+ # defaulting to the passed `args.gradient_accumulation_steps`
+ accelerator = (
+ Accelerator(
+ log_with=args.report_to,
+ project_dir=args.output_dir,
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
+ )
+ if args.with_tracking
+ else Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps)
+ )
+
+ # Make one log on every process with the configuration for debugging.
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%m/%d/%Y %H:%M:%S",
+ level=logging.INFO,
+ )
+ logger.info(accelerator.state, main_process_only=False)
+ if accelerator.is_local_main_process:
+ datasets.utils.logging.set_verbosity_warning()
+ transformers.utils.logging.set_verbosity_info()
+ else:
+ datasets.utils.logging.set_verbosity_error()
+ transformers.utils.logging.set_verbosity_error()
+
+ # If passed along, set the training seed now.
+ if args.seed is not None:
+ set_seed(args.seed)
+
+ # Handle the repository creation
+ if accelerator.is_main_process:
+ if args.push_to_hub:
+ api = HfApi(token=args.hub_token)
+
+ # Create repo (repo_name from args or inferred)
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
+
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
+ if "step_*" not in gitignore:
+ gitignore.write("step_*\n")
+ if "epoch_*" not in gitignore:
+ gitignore.write("epoch_*\n")
+ elif args.output_dir is not None:
+ os.makedirs(args.output_dir, exist_ok=True)
+ accelerator.wait_for_everyone()
+
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
+ # (the dataset will be downloaded automatically from the datasets Hub).
+ #
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
+ # 'text' is found. You can easily tweak this behavior (see below).
+ #
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
+ # download the dataset.
+ if args.dataset_name is not None:
+ # Downloading and loading a dataset from the hub.
+ raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name)
+ if "validation" not in raw_datasets.keys():
+ raw_datasets["validation"] = load_dataset(
+ args.dataset_name,
+ args.dataset_config_name,
+ split=f"train[:{args.validation_split_percentage}%]",
+ )
+ raw_datasets["train"] = load_dataset(
+ args.dataset_name,
+ args.dataset_config_name,
+ split=f"train[{args.validation_split_percentage}%:]",
+ )
+ else:
+ data_files = {}
+ dataset_args = {}
+ if args.train_file is not None:
+ data_files["train"] = args.train_file
+ if args.validation_file is not None:
+ data_files["validation"] = args.validation_file
+ extension = args.train_file.split(".")[-1]
+ if extension == "txt":
+ extension = "text"
+ dataset_args["keep_linebreaks"] = not args.no_keep_linebreaks
+ raw_datasets = load_dataset(extension, data_files=data_files, **dataset_args)
+ # If no validation data is there, validation_split_percentage will be used to divide the dataset.
+ if "validation" not in raw_datasets.keys():
+ raw_datasets["validation"] = load_dataset(
+ extension,
+ data_files=data_files,
+ split=f"train[:{args.validation_split_percentage}%]",
+ **dataset_args,
+ )
+ raw_datasets["train"] = load_dataset(
+ extension,
+ data_files=data_files,
+ split=f"train[{args.validation_split_percentage}%:]",
+ **dataset_args,
+ )
+
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
+
+ # Load pretrained model and tokenizer
+ #
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
+ # download model & vocab.
+ if args.config_name:
+ config = AutoConfig.from_pretrained(args.config_name)
+ elif args.model_name_or_path:
+ config = AutoConfig.from_pretrained(args.model_name_or_path)
+ else:
+ config = CONFIG_MAPPING[args.model_type]()
+ logger.warning("You are instantiating a new config instance from scratch.")
+
+ if args.tokenizer_name:
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
+ elif args.model_name_or_path:
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ else:
+ raise ValueError(
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
+ )
+
+ if args.model_name_or_path:
+ model = AutoModelForCausalLM.from_pretrained(
+ args.model_name_or_path,
+ from_tf=bool(".ckpt" in args.model_name_or_path),
+ config=config,
+ )
+ else:
+ logger.info("Training new model from scratch")
+ model = AutoModelForCausalLM.from_config(config)
+
+ model.resize_token_embeddings(len(tokenizer))
+
+ # Preprocessing the datasets.
+ # First we tokenize all the texts.
+ column_names = raw_datasets["train"].column_names
+ text_column_name = "text" if "text" in column_names else column_names[0]
+
+ def tokenize_function(examples):
+ return tokenizer(examples[text_column_name])
+
+ with accelerator.main_process_first():
+ tokenized_datasets = raw_datasets.map(
+ tokenize_function,
+ batched=True,
+ num_proc=args.preprocessing_num_workers,
+ remove_columns=column_names,
+ load_from_cache_file=not args.overwrite_cache,
+ desc="Running tokenizer on dataset",
+ )
+
+ if args.block_size is None:
+ block_size = tokenizer.model_max_length
+ if block_size > 1024:
+ logger.warning(
+ f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
+ "Picking 1024 instead. You can change that default value by passing --block_size xxx."
+ )
+ block_size = 1024
+ else:
+ if args.block_size > tokenizer.model_max_length:
+ logger.warning(
+ f"The block_size passed ({args.block_size}) is larger than the maximum length for the model"
+ f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
+ )
+ block_size = min(args.block_size, tokenizer.model_max_length)
+
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
+ def group_texts(examples):
+ # Concatenate all texts.
+ concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
+ # customize this part to your needs.
+ if total_length >= block_size:
+ total_length = (total_length // block_size) * block_size
+ # Split by chunks of max_len.
+ result = {
+ k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
+ for k, t in concatenated_examples.items()
+ }
+ result["labels"] = result["input_ids"].copy()
+ return result
+
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
+ # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
+ # to preprocess.
+ #
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
+
+ with accelerator.main_process_first():
+ lm_datasets = tokenized_datasets.map(
+ group_texts,
+ batched=True,
+ num_proc=args.preprocessing_num_workers,
+ load_from_cache_file=not args.overwrite_cache,
+ desc=f"Grouping texts in chunks of {block_size}",
+ )
+
+ train_dataset = lm_datasets["train"]
+ eval_dataset = lm_datasets["validation"]
+
+ # Log a few random samples from the training set:
+ for index in random.sample(range(len(train_dataset)), 3):
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
+
+ # DataLoaders creation:
+ train_dataloader = DataLoader(
+ train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=args.per_device_train_batch_size
+ )
+ eval_dataloader = DataLoader(
+ eval_dataset, collate_fn=default_data_collator, batch_size=args.per_device_eval_batch_size
+ )
+
+ # Optimizer
+ # Split weights in two groups, one with weight decay and the other not.
+ no_decay = ["bias", "LayerNorm.weight"]
+ optimizer_grouped_parameters = [
+ {
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
+ "weight_decay": args.weight_decay,
+ },
+ {
+ "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
+ "weight_decay": 0.0,
+ },
+ ]
+ # New Code #
+ # Creates Dummy Optimizer if `optimizer` was specified in the config file else creates Adam Optimizer
+ optimizer_cls = (
+ torch.optim.AdamW
+ if accelerator.state.deepspeed_plugin is None
+ or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
+ else DummyOptim
+ )
+ optimizer = optimizer_cls(optimizer_grouped_parameters, lr=args.learning_rate)
+
+ # On TPU, the tie weights in our model have been disconnected, so we need to restore the ties.
+ if accelerator.distributed_type == DistributedType.XLA:
+ model.tie_weights()
+
+ # Scheduler and math around the number of training steps.
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / accelerator.gradient_accumulation_steps)
+ overrode_max_train_steps = False
+ if args.max_train_steps is None:
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
+ overrode_max_train_steps = True
+ else:
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
+
+ # New Code #
+ # Creates Dummy Scheduler if `scheduler` was specified in the config file else creates `args.lr_scheduler_type` Scheduler
+ if (
+ accelerator.state.deepspeed_plugin is None
+ or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
+ ):
+ lr_scheduler = get_scheduler(
+ name=args.lr_scheduler_type,
+ optimizer=optimizer,
+ num_warmup_steps=args.num_warmup_steps,
+ num_training_steps=args.max_train_steps,
+ )
+ else:
+ lr_scheduler = DummyScheduler(
+ optimizer, total_num_steps=args.max_train_steps, warmup_num_steps=args.num_warmup_steps
+ )
+
+ # Prepare everything with our `accelerator`.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / accelerator.gradient_accumulation_steps)
+ if overrode_max_train_steps:
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
+ # Afterwards we recalculate our number of training epochs
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
+
+ # Figure out how many steps we should save the Accelerator states
+ checkpointing_steps = args.checkpointing_steps
+ if checkpointing_steps is not None and checkpointing_steps.isdigit():
+ checkpointing_steps = int(checkpointing_steps)
+
+ # We need to initialize the trackers we use, and also store our configuration.
+ # The trackers initializes automatically on the main process.
+ if args.with_tracking:
+ experiment_config = vars(args)
+ # TensorBoard cannot log Enums, need the raw value
+ experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
+ accelerator.init_trackers("clm_no_trainer", experiment_config)
+
+ # Train!
+ total_batch_size = (
+ args.per_device_train_batch_size * accelerator.num_processes * accelerator.gradient_accumulation_steps
+ )
+
+ logger.info("***** Running training *****")
+ logger.info(f" Num examples = {len(train_dataset)}")
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
+ logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
+ logger.info(f" Gradient Accumulation steps = {accelerator.gradient_accumulation_steps}")
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
+ # Only show the progress bar once on each machine.
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
+ completed_steps = 0
+ starting_epoch = 0
+ best_metric = None
+ best_metric_checkpoint = None
+
+ # Potentially load in the weights and states from a previous save
+ if args.resume_from_checkpoint:
+ accelerator.load_state(args.resume_from_checkpoint)
+ accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
+ path = os.path.basename(args.resume_from_checkpoint)
+ training_difference = os.path.splitext(path)[0]
+
+ if "epoch" in training_difference:
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
+ resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
+ else:
+ resume_step = int(training_difference.replace("step_", ""))
+ starting_epoch = resume_step // num_update_steps_per_epoch
+ resume_step -= starting_epoch * num_update_steps_per_epoch
+ completed_steps = resume_step
+
+ # update progress bar if resumed from checkpoint
+ progress_bar.update(completed_steps)
+
+ for epoch in range(starting_epoch, args.num_train_epochs):
+ model.train()
+ if args.with_tracking:
+ total_loss = 0
+
+ # skip new `skip_first_batches` to skip the batches when resuming from ckpt
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We need to skip steps until we reach the resumed step
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ # After the first iteration though, we need to go back to the original dataloader
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
+ # In particular, DeepSpeed handles `gradient_accumulation` via `DeepSpeedEngine`.
+ # Below, we use `accelerator.accumulate` if the user
+ # wants to switch to other approaches such as plain DDP, PyTorch FSDP ...
+ # This avoids having to change any code as things are all handled across different distributed setups.
+ with accelerator.accumulate(model):
+ outputs = model(**batch)
+ loss = outputs.loss
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ if accelerator.sync_gradients:
+ progress_bar.update(1)
+ completed_steps += 1
+
+ # We keep track of the loss at each epoch
+ if args.with_tracking:
+ step_loss = accelerator.reduce(loss.detach().clone()).item()
+ total_loss += step_loss
+
+ if isinstance(checkpointing_steps, int):
+ if completed_steps % checkpointing_steps == 0:
+ output_dir = f"step_{completed_steps}"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+ if completed_steps >= args.max_train_steps:
+ break
+
+ perplexity, eval_loss = evaluate(args, model, eval_dataloader, accelerator, eval_dataset)
+ logger.info(f"epoch {epoch}: perplexity: {perplexity} eval_loss: {eval_loss}")
+
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "perplexity": perplexity,
+ "eval_loss": eval_loss,
+ "train_loss": total_loss / len(train_dataloader),
+ "epoch": epoch,
+ "step": completed_steps,
+ },
+ step=completed_steps,
+ )
+
+ if isinstance(checkpointing_steps, str) and checkpointing_steps == "epoch":
+ accelerator.save_state(os.path.join(args.output_dir, f"epoch_{epoch}"))
+
+ # New Code #
+ # Tracks the best checkpoint and best metric
+ if best_metric is None or best_metric > perplexity:
+ best_metric = perplexity
+ best_metric_checkpoint = os.path.join(args.output_dir, "best_checkpoint")
+ accelerator.save_state(best_metric_checkpoint)
+ accelerator.print(f"New best metric: {best_metric} at epoch {epoch}")
+ accelerator.print(f"best_metric_checkpoint: {best_metric_checkpoint}")
+
+ # New Code #
+ # Loads the best checkpoint after the training is finished
+ if args.load_best_model:
+ accelerator.load_state(best_metric_checkpoint)
+
+ # New Code #
+ # Evaluates using the best checkpoint
+ perplexity, eval_loss = evaluate(args, model, eval_dataloader, accelerator, eval_dataset)
+ logger.info(f"Best model metrics: perplexity: {perplexity} eval_loss: {eval_loss}")
+ if perplexity != best_metric:
+ raise AssertionError(
+ f"Best metric {best_metric} does not match the metric {perplexity} of the loaded best model."
+ )
+
+ if args.output_dir is not None:
+ accelerator.wait_for_everyone()
+ unwrapped_model = accelerator.unwrap_model(model)
+
+ # New Code #
+ # Saves the whole/unpartitioned fp16 model when in ZeRO Stage-3 to the output directory if
+ # `stage3_gather_16bit_weights_on_model_save` is True in DeepSpeed Config file or
+ # `zero3_save_16bit_model` is True in DeepSpeed Plugin.
+ # For Zero Stages 1 and 2, models are saved as usual in the output directory.
+ # The model name saved is `pytorch_model.bin`
+ unwrapped_model.save_pretrained(
+ args.output_dir,
+ is_main_process=accelerator.is_main_process,
+ save_function=accelerator.save,
+ state_dict=accelerator.get_state_dict(model),
+ )
+ if accelerator.is_main_process:
+ tokenizer.save_pretrained(args.output_dir)
+ if args.push_to_hub:
+ api.upload_folder(
+ repo_id=repo_id,
+ folder_path=args.output_dir,
+ commit_message="End of training",
+ )
+
+ with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
+ json.dump({"perplexity": perplexity, "eval_loss": eval_loss.item()}, f)
+ accelerator.end_training()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/early_stopping.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/early_stopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..12e087d891fad40d3ce0515e226c39e561d19f55
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/early_stopping.py
@@ -0,0 +1,246 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+# specifically showcasing how to perform early stopping,
+# and builds off the `nlp_example.py` script
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"],
+ shuffle=False,
+ collate_fn=collate_fn,
+ batch_size=EVAL_BATCH_SIZE,
+ drop_last=(accelerator.mixed_precision == "fp8"),
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# New code
+class EarlyStoppingCallback:
+ "A callback class that helps with early stopping"
+
+ def __init__(self, min_delta=0, patience=5):
+ self.min_delta = min_delta
+ self.patience = patience
+ self.counter = 0
+ self.lowest_loss = float("inf")
+
+ def check_early_stopping(self, eval_loss):
+ delta = self.lowest_loss - eval_loss
+ if delta >= self.min_delta:
+ self.lowest_loss = eval_loss
+ self.counter = 0
+ else:
+ self.counter += 1
+ if self.counter >= self.patience:
+ return True
+ return False
+
+
+callback = EarlyStoppingCallback()
+
+
+def training_function(config, args):
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ # If the batch size is too big we use gradient accumulation
+ gradient_accumulation_steps = 1
+ if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
+ gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
+ batch_size = MAX_GPU_BATCH_SIZE
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ # New code
+ # Check if we should stop the training on any processes
+ if callback.check_early_stopping(loss.item()):
+ accelerator.set_trigger()
+
+ # If so, we break the loop
+ if accelerator.check_trigger():
+ break
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/fsdp_with_peak_mem_tracking.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/fsdp_with_peak_mem_tracking.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cd3fec55d5a4ea77c16168329a3d29f769fe1ed
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/fsdp_with_peak_mem_tracking.py
@@ -0,0 +1,458 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import gc
+import os
+import threading
+
+import evaluate
+import psutil
+import torch
+from datasets import load_dataset
+from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig
+from torch.utils.data import DataLoader
+from transformers import (
+ AutoModelForSequenceClassification,
+ AutoTokenizer,
+ get_linear_schedule_with_warmup,
+ set_seed,
+)
+
+from accelerate import Accelerator, DistributedType, FullyShardedDataParallelPlugin
+from accelerate.utils import is_npu_available, is_xpu_available
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+# - FSDP
+#
+# This example also demonstrates the checkpointing and sharding capabilities
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+# New Code #
+# Converting Bytes to Megabytes
+def b2mb(x):
+ return int(x / 2**20)
+
+
+# New Code #
+# This context manager is used to track the peak memory usage of the process
+class TorchTracemalloc:
+ def __enter__(self):
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.cuda.memory_allocated()
+ elif is_xpu_available():
+ torch.xpu.empty_cache()
+ torch.xpu.reset_max_memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.xpu.memory_allocated()
+ elif is_npu_available():
+ torch.npu.empty_cache()
+ torch.npu.reset_max_memory_allocated() # reset the peak gauge to zero
+ self.begin = torch.npu.memory_allocated()
+ self.process = psutil.Process()
+
+ self.cpu_begin = self.cpu_mem_used()
+ self.peak_monitoring = True
+ peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
+ peak_monitor_thread.daemon = True
+ peak_monitor_thread.start()
+ return self
+
+ def cpu_mem_used(self):
+ """get resident set size memory for the current process"""
+ return self.process.memory_info().rss
+
+ def peak_monitor_func(self):
+ self.cpu_peak = -1
+
+ while True:
+ self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
+
+ # can't sleep or will not catch the peak right (this comment is here on purpose)
+ # time.sleep(0.001) # 1msec
+
+ if not self.peak_monitoring:
+ break
+
+ def __exit__(self, *exc):
+ self.peak_monitoring = False
+
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ self.end = torch.cuda.memory_allocated()
+ self.peak = torch.cuda.max_memory_allocated()
+ elif is_xpu_available():
+ torch.xpu.empty_cache()
+ self.end = torch.xpu.memory_allocated()
+ self.peak = torch.xpu.max_memory_allocated()
+ elif is_npu_available():
+ torch.npu.empty_cache()
+ self.end = torch.npu.memory_allocated()
+ self.peak = torch.npu.max_memory_allocated()
+ self.used = b2mb(self.end - self.begin)
+ self.peaked = b2mb(self.peak - self.begin)
+
+ self.cpu_end = self.cpu_mem_used()
+ self.cpu_used = b2mb(self.cpu_end - self.cpu_begin)
+ self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin)
+ # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+
+ # New Code #
+ # Pass the advanced FSDP settings not part of the accelerate config by creating fsdp_plugin
+ fsdp_plugin = FullyShardedDataParallelPlugin(
+ state_dict_config=FullStateDictConfig(offload_to_cpu=False, rank0_only=False),
+ optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=False, rank0_only=False),
+ )
+
+ # Initialize accelerator
+ if args.with_tracking:
+ accelerator = Accelerator(
+ cpu=args.cpu,
+ mixed_precision=args.mixed_precision,
+ log_with="wandb",
+ project_dir=args.logging_dir,
+ fsdp_plugin=fsdp_plugin,
+ )
+ else:
+ accelerator = Accelerator(fsdp_plugin=fsdp_plugin)
+ accelerator.print(accelerator.distributed_type)
+
+ if hasattr(args.checkpointing_steps, "isdigit"):
+ if args.checkpointing_steps == "epoch":
+ checkpointing_steps = args.checkpointing_steps
+ elif args.checkpointing_steps.isdigit():
+ checkpointing_steps = int(args.checkpointing_steps)
+ else:
+ raise ValueError(
+ f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
+ )
+ else:
+ checkpointing_steps = None
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ # We need to initialize the trackers we use, and also store our configuration
+ if args.with_tracking:
+ experiment_config = vars(args)
+ accelerator.init_trackers("fsdp_glue_no_trainer", experiment_config)
+
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
+ datasets = load_dataset("glue", "mrpc")
+ metric = evaluate.load("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ # If the batch size is too big we use gradient accumulation
+ gradient_accumulation_steps = 1
+ if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
+ gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
+ batch_size = MAX_GPU_BATCH_SIZE
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ set_seed(seed)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained(
+ args.model_name_or_path, return_dict=True, low_cpu_mem_usage=True
+ )
+
+ no_decay = ["bias", "LayerNorm.weight"]
+ optimizer_grouped_parameters = [
+ {
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
+ "weight_decay": 0.003,
+ },
+ {
+ "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
+ "weight_decay": 0.0,
+ },
+ ]
+
+ optimizer = torch.optim.AdamW(params=optimizer_grouped_parameters, lr=lr, weight_decay=2e-4)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=10,
+ num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
+ )
+
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ overall_step = 0
+
+ # Potentially load in the weights and states from a previous save
+ if args.resume_from_checkpoint:
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
+ accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
+ accelerator.load_state(args.resume_from_checkpoint)
+ path = os.path.basename(args.resume_from_checkpoint)
+ else:
+ # Get the most recent checkpoint
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
+ dirs.sort(key=os.path.getctime)
+ path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ # Extract `epoch_{i}` or `step_{i}`
+ training_difference = os.path.splitext(path)[0]
+
+ if "epoch" in training_difference:
+ num_epochs -= int(training_difference.replace("epoch_", ""))
+ resume_step = None
+ else:
+ resume_step = int(training_difference.replace("step_", ""))
+ num_epochs -= resume_step // len(train_dataloader)
+ # If resuming by step, we also need to know exactly how far into the DataLoader we went
+ resume_step = (num_epochs * len(train_dataloader)) - resume_step
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ # New Code #
+ # context manager to track the peak memory usage during the training epoch
+ with TorchTracemalloc() as tracemalloc:
+ model.train()
+ if args.with_tracking:
+ total_loss = 0
+ for step, batch in enumerate(train_dataloader):
+ # We need to skip steps until we reach the resumed step
+ if args.resume_from_checkpoint and epoch == 0:
+ if resume_step is not None and step < resume_step:
+ pass
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ # We keep track of the loss at each epoch
+ if args.with_tracking:
+ total_loss += loss.detach().float()
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ # accelerator.print(lr_scheduler.get_lr())
+
+ overall_step += 1
+
+ if isinstance(checkpointing_steps, int):
+ output_dir = f"step_{overall_step}"
+ if overall_step % checkpointing_steps == 0:
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+ # New Code #
+ # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
+ accelerator.print(f"Memory before entering the train : {b2mb(tracemalloc.begin)}")
+ accelerator.print(f"Memory consumed at the end of the train (end-begin): {tracemalloc.used}")
+ accelerator.print(f"Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}")
+ accelerator.print(
+ f"Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
+ )
+ # Logging the peak memory usage of the GPU to the tracker
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "train_total_peak_memory": tracemalloc.peaked + b2mb(tracemalloc.begin),
+ },
+ step=epoch,
+ )
+
+ # New Code #
+ # context manager to track the peak memory usage during the evaluation
+ with TorchTracemalloc() as tracemalloc:
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "accuracy": eval_metric["accuracy"],
+ "f1": eval_metric["f1"],
+ "train_loss": total_loss.item() / len(train_dataloader),
+ },
+ step=epoch,
+ )
+
+ if checkpointing_steps == "epoch":
+ output_dir = f"epoch_{epoch}"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+ # New Code #
+ # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
+ accelerator.print(f"Memory before entering the eval : {b2mb(tracemalloc.begin)}")
+ accelerator.print(f"Memory consumed at the end of the eval (end-begin): {tracemalloc.used}")
+ accelerator.print(f"Peak Memory consumed during the eval (max-begin): {tracemalloc.peaked}")
+ accelerator.print(
+ f"Total Peak Memory consumed during the eval (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
+ )
+ # Logging the peak memory usage of the GPU to the tracker
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "eval_total_peak_memory": tracemalloc.peaked + b2mb(tracemalloc.begin),
+ },
+ step=epoch,
+ )
+
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ parser.add_argument(
+ "--checkpointing_steps",
+ type=str,
+ default=None,
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
+ )
+ parser.add_argument(
+ "--resume_from_checkpoint",
+ type=str,
+ default=None,
+ help="If the training should continue from a checkpoint folder.",
+ )
+ parser.add_argument(
+ "--with_tracking",
+ action="store_true",
+ help="Whether to load in all available experiment trackers from the environment and use them for logging.",
+ )
+ parser.add_argument(
+ "--output_dir",
+ type=str,
+ default=".",
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
+ )
+ parser.add_argument(
+ "--logging_dir",
+ type=str,
+ default="logs",
+ help="Location on where to store experiment tracking logs`",
+ )
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
+ required=True,
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/gradient_accumulation.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/gradient_accumulation.py
new file mode 100644
index 0000000000000000000000000000000000000000..d277bd7d8bb7345a5024e044655ed2569ff6f174
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/gradient_accumulation.py
@@ -0,0 +1,228 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+# and perform gradient accumulation
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # New Code #
+ gradient_accumulation_steps = int(args.gradient_accumulation_steps)
+ # Initialize accelerator
+ accelerator = Accelerator(
+ cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps
+ )
+ if accelerator.distributed_type == DistributedType.XLA and gradient_accumulation_steps > 1:
+ raise NotImplementedError(
+ "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`"
+ )
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs),
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ # New code #
+ # We use the new `accumulate` context manager to perform gradient accumulation
+ # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
+ with accelerator.accumulate(model):
+ output = model(**batch)
+ loss = output.loss
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ # New Code #
+ parser.add_argument(
+ "--gradient_accumulation_steps",
+ type=int,
+ default=1,
+ help="The number of minibatches to be ran before gradients are accumulated.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/gradient_accumulation_for_autoregressive_models.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/gradient_accumulation_for_autoregressive_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..f21199bea8fc9d6269d948848085db322bebd15d
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/gradient_accumulation_for_autoregressive_models.py
@@ -0,0 +1,341 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import contextlib
+import math
+import os
+
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForCausalLM, AutoTokenizer, get_constant_schedule, set_seed
+
+from accelerate import Accelerator, DistributedType
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+# and perform gradient accumulation on samples of variable size
+#
+# This example trains a SmolLM base model on WikiText-2 v1
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, max_training_samples=500):
+ """
+ Creates a set of `DataLoader`s for the `Salesforce/wikitext` dataset,
+ using "HuggingFaceTB/SmolLM-360M" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-360M")
+ tokenizer.pad_token = tokenizer.eos_token
+ with accelerator.local_main_process_first():
+ datasets = load_dataset("Salesforce/wikitext", "wikitext-2-v1")
+ datasets["train"] = datasets["train"].select(range(max_training_samples))
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["text"], truncation=True, max_length=None, return_attention_mask=False)
+ return outputs
+
+ # Filter out empty texts
+ with accelerator.main_process_first():
+ datasets = datasets.filter(
+ lambda x: len(x) > 0,
+ input_columns="text",
+ )
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["text"],
+ )
+
+ # Filter out empty samples
+ with accelerator.main_process_first():
+ tokenized_datasets = tokenized_datasets.filter(
+ lambda x: len(x) > 0,
+ input_columns="input_ids",
+ )
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = (
+ 128
+ if accelerator.distributed_type == DistributedType.XLA
+ else max([len(e["input_ids"]) for e in examples])
+ )
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ batch = tokenizer.pad(
+ examples,
+ padding="max_length",
+ max_length=max_length + 1,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ batch["labels"] = batch["input_ids"][:, 1:]
+ batch["input_ids"] = batch["input_ids"][:, :-1]
+
+ batch["labels"] = torch.where(batch["labels"] == tokenizer.pad_token_id, -100, batch["labels"])
+
+ return batch
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=False, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders_for_autoregressive_models
+
+ get_dataloaders = mocked_dataloaders_for_autoregressive_models # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+
+ gradient_accumulation_steps = int(args.gradient_accumulation_steps)
+ # Initialize accelerator
+ if args.with_wandb_tracking:
+ accelerator = Accelerator(
+ cpu=args.cpu,
+ mixed_precision=args.mixed_precision,
+ gradient_accumulation_steps=gradient_accumulation_steps,
+ log_with="wandb",
+ )
+ else:
+ accelerator = Accelerator(
+ cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps
+ )
+ if accelerator.distributed_type == DistributedType.XLA and gradient_accumulation_steps > 1:
+ raise NotImplementedError(
+ "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`"
+ )
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+ max_grad_norm = config["max_grad_norm"]
+
+ # We need to initialize the trackers we use, and also store our configuration
+ if args.with_wandb_tracking:
+ run = os.path.split(__file__)[-1].split(".")[0]
+ run_name = f"{accelerator.num_processes}GPU-grad{gradient_accumulation_steps}-bs{batch_size}"
+ accelerator.init_trackers(
+ run,
+ config,
+ init_kwargs={"wandb": {"name": run_name}},
+ )
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-360M")
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_constant_schedule(
+ optimizer=optimizer,
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ num_samples_in_epoch = len(train_dataloader)
+ remainder = num_samples_in_epoch % gradient_accumulation_steps
+ remainder = remainder if remainder != 0 else gradient_accumulation_steps
+ total_gradient_updates = math.ceil(num_samples_in_epoch / gradient_accumulation_steps)
+
+ total_batched_samples = 0
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ training_iterator = iter(train_dataloader)
+ for update_step in range(total_gradient_updates):
+ # In order to correctly the total number of non-padded tokens on which we'll compute the cross-entropy loss
+ # we need to pre-load the full local batch - i.e the next per_device_batch_size * accumulation_steps samples
+ batch_samples = []
+ num_batches_in_step = (
+ gradient_accumulation_steps if update_step != (total_gradient_updates - 1) else remainder
+ )
+ for _ in range(num_batches_in_step):
+ batch_samples += [next(training_iterator)]
+ # get local num items in batch
+ local_num_items_in_batch = sum([(batch["labels"].ne(-100)).sum() for batch in batch_samples])
+
+ # to compute it correctly in a multi-device DDP training, we need to gather the total number of items in the full batch.
+ num_items_in_batch = accelerator.gather(local_num_items_in_batch).sum().item()
+ losses = []
+ for i, batch in enumerate(batch_samples):
+ # if we perform gradient accumulation in a multi-devices set-up, we want to avoid unecessary communications when accumulating
+ # cf: https://muellerzr.github.io/blog/gradient_accumulation.html
+ ctx = (
+ model.no_sync
+ if (i < len(batch_samples) - 1 and accelerator.num_processes > 1)
+ else contextlib.nullcontext
+ )
+ with ctx():
+ total_batched_samples += 1
+
+ outputs = model(**batch, use_cache=False, num_items_in_batch=num_items_in_batch)
+ loss = outputs.loss
+
+ # We multiply by num_processes because the DDP calculates the average gradient across all devices whereas dividing by num_items_in_batch already takes into account all devices
+ # Same reason for gradient_accumulation_steps, but this times it's Accelerate that calculate the average gradient across the accumulated steps
+ # Because the loss is already divided by `num_items_in_batch` in the `transformers` code, we don't need to do it again
+ loss = loss * gradient_accumulation_steps * accelerator.num_processes
+ accelerator.backward(loss)
+ losses.append(loss.detach())
+
+ # Sync gradients and perform optimization steps once every gradient_accumulation_steps
+ grad_norm = accelerator.clip_grad_norm_(model.parameters(), max_grad_norm)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ losses = accelerator.gather(sum(losses)).sum().item() / (
+ accelerator.num_processes * gradient_accumulation_steps
+ )
+
+ grad_norm = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm
+ accelerator.print(
+ f"epoch {epoch} - update step {update_step}:: grad norm: {grad_norm} ::train loss: {losses}"
+ )
+ if args.with_wandb_tracking:
+ accelerator.log(
+ {
+ "train/grad_norm": grad_norm,
+ "train/epoch": epoch,
+ "train/loss": losses,
+ },
+ step=update_step + total_gradient_updates * epoch,
+ )
+ model.eval()
+ losses = []
+ for step, batch in enumerate(eval_dataloader):
+ with torch.no_grad():
+ outputs = model(**batch, use_cache=False)
+ eval_loss = outputs.loss
+ losses.append(accelerator.gather_for_metrics(loss.repeat(EVAL_BATCH_SIZE)))
+
+ losses = torch.cat(losses)
+ try:
+ eval_loss = torch.mean(losses)
+ perplexity = math.exp(eval_loss)
+ except OverflowError:
+ perplexity = float("inf")
+
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:: eval perplexity: {perplexity} eval_loss: {eval_loss}")
+ if args.with_wandb_tracking:
+ accelerator.log(
+ {
+ "eval/perplexity": perplexity,
+ "eval/loss": eval_loss,
+ "eval/epoch": epoch,
+ },
+ step=update_step + total_gradient_updates * epoch,
+ )
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+
+ parser.add_argument(
+ "--gradient_accumulation_steps",
+ type=int,
+ default=1,
+ help="The number of minibatches to be ran before gradients are accumulated.",
+ )
+ parser.add_argument(
+ "--per_device_batch_size",
+ type=int,
+ default=2,
+ help="The size of each minibatch",
+ )
+
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ parser.add_argument(
+ "--with_wandb_tracking",
+ action="store_true",
+ help="Whether to load in wandb from the environment and use them for logging.",
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": args.per_device_batch_size, "max_grad_norm": 1.0}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/local_sgd.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/local_sgd.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdcf950af190fa71b403836f1a7ec2f0d6a8e3ec
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/local_sgd.py
@@ -0,0 +1,236 @@
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+from accelerate.local_sgd import LocalSGD
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+# with LocalSGD, which is a method to synchronize model
+# parameters every K batches. It is different, but complementary
+# to gradient accumulation.
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # New Code #
+ gradient_accumulation_steps = int(args.gradient_accumulation_steps)
+ local_sgd_steps = int(args.local_sgd_steps)
+ # Initialize accelerator
+ accelerator = Accelerator(
+ cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps
+ )
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs),
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ with LocalSGD(
+ accelerator=accelerator, model=model, local_sgd_steps=local_sgd_steps, enabled=local_sgd_steps is not None
+ ) as local_sgd:
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ # New code #
+ # We use the new `accumulate` context manager to perform gradient accumulation
+ # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
+ with accelerator.accumulate(model):
+ output = model(**batch)
+ loss = output.loss
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ # LocalSGD-specific line
+ local_sgd.step()
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ # New Code #
+ parser.add_argument(
+ "--gradient_accumulation_steps",
+ type=int,
+ default=1,
+ help="The number of minibatches to be ran before gradients are accumulated.",
+ )
+ parser.add_argument(
+ "--local_sgd_steps", type=int, default=8, help="Number of local SGD steps or None to disable local SGD"
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/megatron_lm_gpt_pretraining.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/megatron_lm_gpt_pretraining.py
new file mode 100644
index 0000000000000000000000000000000000000000..b357106e6d5024a2edc7aa04fc6f9e6154239ff6
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/megatron_lm_gpt_pretraining.py
@@ -0,0 +1,710 @@
+#!/usr/bin/env python
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...)
+on a text file or a dataset without using HuggingFace Trainer.
+
+Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
+https://huggingface.co/models?filter=text-generation
+"""
+# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
+
+import argparse
+import json
+import logging
+import math
+import os
+import random
+from itertools import chain
+from pathlib import Path
+
+import datasets
+import torch
+import transformers
+from datasets import load_dataset
+from huggingface_hub import HfApi
+from torch.utils.data import DataLoader
+from tqdm.auto import tqdm
+from transformers import (
+ CONFIG_MAPPING,
+ MODEL_MAPPING,
+ AutoConfig,
+ AutoModelForCausalLM,
+ AutoTokenizer,
+ SchedulerType,
+ default_data_collator,
+ get_scheduler,
+)
+from transformers.utils import check_min_version, send_example_telemetry
+from transformers.utils.versions import require_version
+
+from accelerate import Accelerator, DistributedType
+from accelerate.logging import get_logger
+from accelerate.utils import MegatronLMDummyScheduler, set_seed
+
+
+# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
+check_min_version("4.23.0.dev0")
+
+logger = get_logger(__name__)
+
+require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
+
+MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
+MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task")
+ parser.add_argument(
+ "--dataset_name",
+ type=str,
+ default=None,
+ help="The name of the dataset to use (via the datasets library).",
+ )
+ parser.add_argument(
+ "--dataset_config_name",
+ type=str,
+ default=None,
+ help="The configuration name of the dataset to use (via the datasets library).",
+ )
+ parser.add_argument(
+ "--train_file", type=str, default=None, help="A csv or a json file containing the training data."
+ )
+ parser.add_argument(
+ "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
+ )
+ parser.add_argument(
+ "--validation_split_percentage",
+ default=5,
+ help="The percentage of the train set used as validation set in case there's no validation split",
+ )
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
+ required=False,
+ )
+ parser.add_argument(
+ "--config_name",
+ type=str,
+ default=None,
+ help="Pretrained config name or path if not the same as model_name",
+ )
+ parser.add_argument(
+ "--tokenizer_name",
+ type=str,
+ default=None,
+ help="Pretrained tokenizer name or path if not the same as model_name",
+ )
+ parser.add_argument(
+ "--use_slow_tokenizer",
+ action="store_true",
+ help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
+ )
+ parser.add_argument(
+ "--per_device_train_batch_size",
+ type=int,
+ default=8,
+ help="Batch size (per device) for the training dataloader.",
+ )
+ parser.add_argument(
+ "--per_device_eval_batch_size",
+ type=int,
+ default=8,
+ help="Batch size (per device) for the evaluation dataloader.",
+ )
+ parser.add_argument(
+ "--learning_rate",
+ type=float,
+ default=5e-5,
+ help="Initial learning rate (after the potential warmup period) to use.",
+ )
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
+ parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
+ parser.add_argument(
+ "--max_train_steps",
+ type=int,
+ default=None,
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
+ )
+ parser.add_argument(
+ "--gradient_accumulation_steps",
+ type=int,
+ default=1,
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
+ )
+ parser.add_argument(
+ "--lr_scheduler_type",
+ type=SchedulerType,
+ default="linear",
+ help="The scheduler type to use.",
+ choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
+ )
+ parser.add_argument(
+ "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
+ )
+ parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
+ parser.add_argument(
+ "--model_type",
+ type=str,
+ default=None,
+ help="Model type to use if training from scratch.",
+ choices=MODEL_TYPES,
+ )
+ parser.add_argument(
+ "--block_size",
+ type=int,
+ default=None,
+ help=(
+ "Optional input sequence length after tokenization. The training dataset will be truncated in block of"
+ " this size for training. Default to the model max input length for single sentence inputs (take into"
+ " account special tokens)."
+ ),
+ )
+ parser.add_argument(
+ "--preprocessing_num_workers",
+ type=int,
+ default=None,
+ help="The number of processes to use for the preprocessing.",
+ )
+ parser.add_argument(
+ "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
+ )
+ parser.add_argument(
+ "--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files."
+ )
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
+ parser.add_argument(
+ "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
+ )
+ parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--checkpointing_steps",
+ type=str,
+ default=None,
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
+ )
+ parser.add_argument(
+ "--resume_from_checkpoint",
+ type=str,
+ default=None,
+ help="If the training should continue from a checkpoint folder.",
+ )
+ parser.add_argument(
+ "--with_tracking",
+ action="store_true",
+ help="Whether to enable experiment trackers for logging.",
+ )
+ parser.add_argument(
+ "--report_to",
+ type=str,
+ default="all",
+ help=(
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
+ ' `"wandb"`, `"comet_ml"`, and `"dvclive"`. Use `"all"` (default) to report to all integrations.'
+ "Only applicable when `--with_tracking` is passed."
+ ),
+ )
+ args = parser.parse_args()
+
+ # Sanity checks
+ if args.dataset_name is None and args.train_file is None and args.validation_file is None:
+ raise ValueError("Need either a dataset name or a training/validation file.")
+ else:
+ if args.train_file is not None:
+ extension = args.train_file.split(".")[-1]
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
+ if args.validation_file is not None:
+ extension = args.validation_file.split(".")[-1]
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
+
+ if args.push_to_hub:
+ assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
+
+ return args
+
+
+def main():
+ args = parse_args()
+
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
+ send_example_telemetry("run_clm_no_trainer", args)
+
+ # Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
+ # If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
+ # in the environment
+ accelerator_log_kwargs = {}
+
+ if args.with_tracking:
+ accelerator_log_kwargs["log_with"] = args.report_to
+ accelerator_log_kwargs["project_dir"] = args.output_dir
+
+ accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
+
+ # Make one log on every process with the configuration for debugging.
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%m/%d/%Y %H:%M:%S",
+ level=logging.INFO,
+ )
+ logger.info(accelerator.state, main_process_only=False)
+ if accelerator.is_local_main_process:
+ datasets.utils.logging.set_verbosity_warning()
+ transformers.utils.logging.set_verbosity_info()
+ else:
+ datasets.utils.logging.set_verbosity_error()
+ transformers.utils.logging.set_verbosity_error()
+
+ # If passed along, set the training seed now.
+ if args.seed is not None:
+ set_seed(args.seed)
+
+ # Handle the repository creation
+ if accelerator.is_main_process:
+ if args.push_to_hub:
+ api = HfApi(token=args.hub_token)
+
+ # Create repo (repo_name from args or inferred)
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
+
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
+ if "step_*" not in gitignore:
+ gitignore.write("step_*\n")
+ if "epoch_*" not in gitignore:
+ gitignore.write("epoch_*\n")
+ elif args.output_dir is not None:
+ os.makedirs(args.output_dir, exist_ok=True)
+ accelerator.wait_for_everyone()
+
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
+ # (the dataset will be downloaded automatically from the datasets Hub).
+ #
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
+ # 'text' is found. You can easily tweak this behavior (see below).
+ #
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
+ # download the dataset.
+ if args.dataset_name is not None:
+ # Downloading and loading a dataset from the hub.
+ raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name)
+ if "validation" not in raw_datasets.keys():
+ raw_datasets["validation"] = load_dataset(
+ args.dataset_name,
+ args.dataset_config_name,
+ split=f"train[:{args.validation_split_percentage}%]",
+ )
+ raw_datasets["train"] = load_dataset(
+ args.dataset_name,
+ args.dataset_config_name,
+ split=f"train[{args.validation_split_percentage}%:]",
+ )
+ else:
+ data_files = {}
+ dataset_args = {}
+ if args.train_file is not None:
+ data_files["train"] = args.train_file
+ if args.validation_file is not None:
+ data_files["validation"] = args.validation_file
+ extension = args.train_file.split(".")[-1]
+ if extension == "txt":
+ extension = "text"
+ dataset_args["keep_linebreaks"] = not args.no_keep_linebreaks
+ raw_datasets = load_dataset(extension, data_files=data_files, **dataset_args)
+ # If no validation data is there, validation_split_percentage will be used to divide the dataset.
+ if "validation" not in raw_datasets.keys():
+ raw_datasets["validation"] = load_dataset(
+ extension,
+ data_files=data_files,
+ split=f"train[:{args.validation_split_percentage}%]",
+ **dataset_args,
+ )
+ raw_datasets["train"] = load_dataset(
+ extension,
+ data_files=data_files,
+ split=f"train[{args.validation_split_percentage}%:]",
+ **dataset_args,
+ )
+
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
+
+ # Load pretrained model and tokenizer
+ #
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
+ # download model & vocab.
+ if args.config_name:
+ config = AutoConfig.from_pretrained(args.config_name)
+ elif args.model_name_or_path:
+ config = AutoConfig.from_pretrained(args.model_name_or_path)
+ else:
+ config = CONFIG_MAPPING[args.model_type]()
+ logger.warning("You are instantiating a new config instance from scratch.")
+
+ if args.tokenizer_name:
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
+ elif args.model_name_or_path:
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ else:
+ raise ValueError(
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
+ )
+
+ if args.model_name_or_path:
+ model = AutoModelForCausalLM.from_pretrained(
+ args.model_name_or_path,
+ from_tf=bool(".ckpt" in args.model_name_or_path),
+ config=config,
+ )
+ else:
+ logger.info("Training new model from scratch")
+ model = AutoModelForCausalLM.from_config(config)
+
+ model.resize_token_embeddings(len(tokenizer))
+
+ # Preprocessing the datasets.
+ # First we tokenize all the texts.
+ column_names = raw_datasets["train"].column_names
+ text_column_name = "text" if "text" in column_names else column_names[0]
+
+ def tokenize_function(examples):
+ return tokenizer(examples[text_column_name])
+
+ with accelerator.main_process_first():
+ tokenized_datasets = raw_datasets.map(
+ tokenize_function,
+ batched=True,
+ num_proc=args.preprocessing_num_workers,
+ remove_columns=column_names,
+ load_from_cache_file=not args.overwrite_cache,
+ desc="Running tokenizer on dataset",
+ )
+
+ if args.block_size is None:
+ block_size = tokenizer.model_max_length
+ if block_size > 1024:
+ logger.warning(
+ f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
+ "Picking 1024 instead. You can change that default value by passing --block_size xxx."
+ )
+ block_size = 1024
+ else:
+ if args.block_size > tokenizer.model_max_length:
+ logger.warning(
+ f"The block_size passed ({args.block_size}) is larger than the maximum length for the model"
+ f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
+ )
+ block_size = min(args.block_size, tokenizer.model_max_length)
+
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
+ def group_texts(examples):
+ # Concatenate all texts.
+ concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
+ # customize this part to your needs.
+ if total_length >= block_size:
+ total_length = (total_length // block_size) * block_size
+ # Split by chunks of max_len.
+ result = {
+ k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
+ for k, t in concatenated_examples.items()
+ }
+ result["labels"] = result["input_ids"].copy()
+ return result
+
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
+ # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
+ # to preprocess.
+ #
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
+
+ with accelerator.main_process_first():
+ lm_datasets = tokenized_datasets.map(
+ group_texts,
+ batched=True,
+ num_proc=args.preprocessing_num_workers,
+ load_from_cache_file=not args.overwrite_cache,
+ desc=f"Grouping texts in chunks of {block_size}",
+ )
+
+ train_dataset = lm_datasets["train"]
+ eval_dataset = lm_datasets["validation"]
+
+ # Log a few random samples from the training set:
+ for index in random.sample(range(len(train_dataset)), 3):
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
+
+ # DataLoaders creation:
+ train_dataloader = DataLoader(
+ train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=args.per_device_train_batch_size
+ )
+ eval_dataloader = DataLoader(
+ eval_dataset, collate_fn=default_data_collator, batch_size=args.per_device_eval_batch_size
+ )
+
+ # Optimizer
+ # Split weights in two groups, one with weight decay and the other not.
+ no_decay = ["bias", "layer_norm.weight"]
+ optimizer_grouped_parameters = [
+ {
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
+ "weight_decay": args.weight_decay,
+ },
+ {
+ "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
+ "weight_decay": 0.0,
+ },
+ ]
+ optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
+
+ # Scheduler and math around the number of training steps.
+ overrode_max_train_steps = False
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
+ if args.max_train_steps is None:
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
+ overrode_max_train_steps = True
+
+ # New Code
+ # For Megatron-LM, we need to use `MegatronLMDummyScheduler` instead of regular schedulers
+ if accelerator.distributed_type == DistributedType.MEGATRON_LM:
+ lr_scheduler = MegatronLMDummyScheduler(
+ optimizer=optimizer,
+ total_num_steps=args.max_train_steps,
+ warmup_num_steps=args.num_warmup_steps,
+ )
+ else:
+ lr_scheduler = get_scheduler(
+ name=args.lr_scheduler_type,
+ optimizer=optimizer,
+ num_warmup_steps=args.num_warmup_steps * args.gradient_accumulation_steps,
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
+ )
+
+ # Prepare everything with our `accelerator`.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # On TPU, the tie weights in our model have been disconnected, so we need to restore the ties.
+ if accelerator.distributed_type == DistributedType.XLA:
+ model.tie_weights()
+
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
+ if overrode_max_train_steps:
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
+ # Afterwards we recalculate our number of training epochs
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
+
+ # Figure out how many steps we should save the Accelerator states
+ checkpointing_steps = args.checkpointing_steps
+ if checkpointing_steps is not None and checkpointing_steps.isdigit():
+ checkpointing_steps = int(checkpointing_steps)
+
+ # We need to initialize the trackers we use, and also store our configuration.
+ # The trackers initializes automatically on the main process.
+ if args.with_tracking:
+ experiment_config = vars(args)
+ # TensorBoard cannot log Enums, need the raw value
+ experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
+ accelerator.init_trackers("clm_no_trainer", experiment_config)
+
+ # Train!
+ # New Code
+ # For Megatron-LM, we need to get `global_batch_size` from megatron_lm_plugin
+ # as it handles the specifics related to data parallelism, tensor model parallelism and pipeline parallelism
+ if accelerator.distributed_type == DistributedType.MEGATRON_LM:
+ total_batch_size = accelerator.state.megatron_lm_plugin.global_batch_size
+ else:
+ total_batch_size = (
+ args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
+ )
+
+ logger.info("***** Running training *****")
+ logger.info(f" Num examples = {len(train_dataset)}")
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
+ logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
+ # Only show the progress bar once on each machine.
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
+ completed_steps = 0
+ starting_epoch = 0
+
+ # Potentially load in the weights and states from a previous save
+ if args.resume_from_checkpoint:
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
+ accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
+ accelerator.load_state(args.resume_from_checkpoint)
+ path = os.path.basename(args.resume_from_checkpoint)
+ else:
+ # Get the most recent checkpoint
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
+ dirs.sort(key=os.path.getctime)
+ path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ # Extract `epoch_{i}` or `step_{i}`
+ training_difference = os.path.splitext(path)[0]
+
+ if "epoch" in training_difference:
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
+ resume_step = None
+ else:
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
+ starting_epoch = resume_step // len(train_dataloader)
+ resume_step -= starting_epoch * len(train_dataloader)
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(starting_epoch * num_update_steps_per_epoch)
+ completed_steps = starting_epoch * num_update_steps_per_epoch
+
+ for epoch in range(starting_epoch, args.num_train_epochs):
+ model.train()
+ if args.with_tracking:
+ total_loss = 0
+ for step, batch in enumerate(train_dataloader):
+ # We need to skip steps until we reach the resumed step
+ if args.resume_from_checkpoint and epoch == starting_epoch:
+ if resume_step is not None and step < resume_step:
+ if step % args.gradient_accumulation_steps == 0:
+ progress_bar.update(1)
+ completed_steps += 1
+ continue
+
+ with accelerator.accumulate(model):
+ outputs = model(**batch)
+ loss = outputs.loss
+ # We keep track of the loss at each epoch
+ if args.with_tracking:
+ total_loss += loss.detach().float()
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ # Checks if the accelerator has performed an optimization step behind the scenes
+ if accelerator.sync_gradients:
+ progress_bar.update(1)
+ completed_steps += 1
+
+ if isinstance(checkpointing_steps, int):
+ if completed_steps % checkpointing_steps == 0:
+ output_dir = f"step_{completed_steps}"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+ if completed_steps >= args.max_train_steps:
+ break
+
+ model.eval()
+ losses = []
+ for step, batch in enumerate(eval_dataloader):
+ with torch.no_grad():
+ outputs = model(**batch)
+
+ loss = outputs.loss
+ # New Code
+ # For Megatron-LM, the losses are already averaged across the data parallel group
+ if accelerator.distributed_type == DistributedType.MEGATRON_LM:
+ losses.append(loss)
+ else:
+ losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size)))
+ try:
+ if accelerator.distributed_type == DistributedType.MEGATRON_LM:
+ losses = torch.tensor(losses)
+ else:
+ losses = torch.cat(losses)
+ eval_loss = torch.mean(losses)
+ perplexity = math.exp(eval_loss)
+ except OverflowError:
+ perplexity = float("inf")
+
+ logger.info(f"epoch {epoch}: perplexity: {perplexity} eval_loss: {eval_loss}")
+
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "perplexity": perplexity,
+ "eval_loss": eval_loss,
+ "train_loss": total_loss.item() / len(train_dataloader),
+ "epoch": epoch,
+ "step": completed_steps,
+ },
+ step=completed_steps,
+ )
+
+ if args.push_to_hub and epoch < args.num_train_epochs - 1:
+ accelerator.wait_for_everyone()
+ unwrapped_model = accelerator.unwrap_model(model)
+ unwrapped_model.save_pretrained(
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
+ )
+ if accelerator.is_main_process:
+ tokenizer.save_pretrained(args.output_dir)
+ api.upload_folder(
+ repo_id=repo_id,
+ folder_path=args.output_dir,
+ commit_message=f"Training in progress epoch {epoch}",
+ run_as_future=True,
+ )
+
+ if args.checkpointing_steps == "epoch":
+ output_dir = f"epoch_{epoch}"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+
+ # this is causing some issue with Megatron-LM when using `wandb` at the end of the main function.
+ # Everything works fine inspite of commenting this out. (wandb finishes/closes the run without error)
+ # if args.with_tracking:
+ # accelerator.end_training()
+
+ if args.output_dir is not None:
+ accelerator.wait_for_everyone()
+ # New Code
+ # For Megatron-LM, we need to save the model using `accelerator.save_state`
+ if accelerator.distributed_type == DistributedType.MEGATRON_LM:
+ accelerator.save_state(args.output_dir)
+ else:
+ unwrapped_model = accelerator.unwrap_model(model)
+ unwrapped_model.save_pretrained(
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
+ )
+ if accelerator.is_main_process:
+ tokenizer.save_pretrained(args.output_dir)
+ if args.push_to_hub:
+ api.upload_folder(
+ repo_id=repo_id,
+ folder_path=args.output_dir,
+ commit_message="End of training",
+ )
+
+ with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
+ json.dump({"perplexity": perplexity}, f)
+ accelerator.end_training()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/memory.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..847135e426eed5f87d5bc853cc80a98c255a3984
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/memory.py
@@ -0,0 +1,234 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+# New Code #
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+from accelerate.utils import find_executable_batch_size
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate,
+# specifically showcasing how to ensure out-of-memory errors never
+# interrupt training, and builds off the `nlp_example.py` script.
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# New additions from the base script can be found quickly by
+# looking for the # New Code # tags
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ # New Code #
+ # We now can define an inner training loop function. It should take a batch size as the only parameter,
+ # and build the dataloaders in there.
+ # It also gets our decorator
+ @find_executable_batch_size(starting_batch_size=batch_size)
+ def inner_training_loop(batch_size):
+ # And now just move everything below under this function
+ # We need to bring in the Accelerator object from earlier
+ nonlocal accelerator
+ # And reset all of its attributes that could hold onto any memory:
+ accelerator.free_memory()
+
+ # Then we can declare the model, optimizer, and everything else:
+ set_seed(seed)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs),
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+
+ # New Code #
+ # And call it at the end with no arguments
+ # Note: You could also refactor this outside of your training loop function
+ inner_training_loop()
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/multi_process_metrics.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/multi_process_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..626781ac81184ffe42ed9d2f7fd952fe1207a4f7
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/multi_process_metrics.py
@@ -0,0 +1,238 @@
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate,
+# specifically showcasing how to properly calculate the metrics on the
+# validation dataset when in a distributed system, and builds off the
+# `nlp_example.py` script.
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To help focus on the differences in the code, building `DataLoaders`
+# was refactored into its own function.
+# New additions from the base script can be found quickly by
+# looking for the # New Code # tags
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ # If the batch size is too big we use gradient accumulation
+ gradient_accumulation_steps = 1
+ if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
+ gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
+ batch_size = MAX_GPU_BATCH_SIZE
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ samples_seen = 0
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather((predictions, batch["labels"]))
+ # New Code #
+ # First we check if it's a distributed system
+ if accelerator.use_distributed:
+ # Then see if we're on the last batch of our eval dataloader
+ if step == len(eval_dataloader) - 1:
+ # Last batch needs to be truncated on distributed systems as it contains additional samples
+ predictions = predictions[: len(eval_dataloader.dataset) - samples_seen]
+ references = references[: len(eval_dataloader.dataset) - samples_seen]
+ else:
+ # Otherwise we add the number of samples seen
+ samples_seen += references.shape[0]
+ # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
+ # accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/profiler.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/profiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc1843acdd3a0b81f9a90488c662268bff5c969b
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/profiler.py
@@ -0,0 +1,255 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+from accelerate.utils import ProfileKwargs
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+# and perform profiling
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # New Code #
+ profile_kwargs = ProfileKwargs(
+ record_shapes=args.record_shapes,
+ profile_memory=args.profile_memory,
+ with_flops=args.with_flops,
+ output_trace_dir=args.output_trace_dir,
+ )
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, kwargs_handlers=[profile_kwargs])
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs),
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ # New Code #
+ with accelerator.profile() as prof:
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ # We use the new `accumulate` context manager to perform gradient accumulation
+ with accelerator.accumulate(model):
+ output = model(**batch)
+ loss = output.loss
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ # New Code #
+ accelerator.print(
+ prof.key_averages().table(
+ sort_by="self_cpu_time_total" if args.cpu else "self_cuda_time_total", row_limit=-1
+ )
+ )
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ # New Code #
+ parser.add_argument(
+ "--record_shapes",
+ action="store_true",
+ default=False,
+ help="If passed, will record shapes for profiling.",
+ )
+ # New Code #
+ parser.add_argument(
+ "--profile_memory",
+ action="store_true",
+ default=False,
+ help="If passed, will profile memory.",
+ )
+ # New Code #
+ parser.add_argument(
+ "--with_flops",
+ action="store_true",
+ default=False,
+ help="If passed, will profile flops.",
+ )
+ # New Code #
+ parser.add_argument(
+ "--output_trace_dir",
+ type=str,
+ default=None,
+ help="If passed, will save a json trace to the specified path.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/schedule_free.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/schedule_free.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9cf11702c8bd6b668ee40c307259099e3ca4f76
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/schedule_free.py
@@ -0,0 +1,226 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, set_seed
+
+from accelerate import Accelerator, DistributedType
+from accelerate.utils import is_schedulefree_available
+
+
+if is_schedulefree_available():
+ import schedulefree
+else:
+ raise ImportError(
+ "This example requires the `schedulefree` library. Please install it with `pip install schedulefree`"
+ )
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate and Facebook's
+# scheduler-free optimizer: https://github.com/facebookresearch/schedule_free/
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # For Torchxla, it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"],
+ shuffle=False,
+ collate_fn=collate_fn,
+ batch_size=EVAL_BATCH_SIZE,
+ drop_last=(accelerator.mixed_precision == "fp8"),
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+
+
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ metric = evaluate.load("glue", "mrpc")
+
+ # If the batch size is too big we use gradient accumulation
+ gradient_accumulation_steps = 1
+ if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
+ gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
+ batch_size = MAX_GPU_BATCH_SIZE
+
+ set_seed(seed)
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+ # Instantiate optimizer with warmup steps
+ optimizer = schedulefree.AdamWScheduleFree(
+ model.parameters(),
+ lr=lr,
+ warmup_steps=100,
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+
+ model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ optimizer.train()
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ optimizer.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/tracking.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/tracking.py
new file mode 100644
index 0000000000000000000000000000000000000000..c97c5517b3527b994111d498cd4c81a30ec3e763
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/by_feature/tracking.py
@@ -0,0 +1,271 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DistributedType
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate,
+# specifically showcasing the experiment tracking capability,
+# and builds off the `nlp_example.py` script.
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To help focus on the differences in the code, building `DataLoaders`
+# was refactored into its own function.
+# New additions from the base script can be found quickly by
+# looking for the # New Code # tags
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
+ """
+ Creates a set of `DataLoader`s for the `glue` dataset,
+ using "bert-base-cased" as the tokenizer.
+
+ Args:
+ accelerator (`Accelerator`):
+ An `Accelerator` object
+ batch_size (`int`, *optional*):
+ The batch size for the train and validation DataLoaders.
+ """
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ return train_dataloader, eval_dataloader
+
+
+# For testing only
+if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ from accelerate.test_utils.training import mocked_dataloaders
+
+ get_dataloaders = mocked_dataloaders # noqa: F811
+
+
+def training_function(config, args):
+ # For testing only
+ if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
+ config["num_epochs"] = 2
+ # Initialize Accelerator
+
+ # New Code #
+ # We pass in "all" to `log_with` to grab all available trackers in the environment
+ # Note: If using a custom `Tracker` class, should be passed in here such as:
+ # >>> log_with = ["all", MyCustomTrackerClassInstance()]
+ if args.with_tracking:
+ accelerator = Accelerator(
+ cpu=args.cpu, mixed_precision=args.mixed_precision, log_with="all", project_dir=args.project_dir
+ )
+ else:
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+ set_seed(seed)
+
+ train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
+ metric = evaluate.load("glue", "mrpc")
+
+ # If the batch size is too big we use gradient accumulation
+ gradient_accumulation_steps = 1
+ if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
+ gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
+ batch_size = MAX_GPU_BATCH_SIZE
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # New Code #
+ # We need to initialize the trackers we use. Overall configurations can also be stored
+ if args.with_tracking:
+ run = os.path.split(__file__)[-1].split(".")[0]
+ accelerator.init_trackers(run, config)
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ # New Code #
+ # For our tracking example, we will log the total loss of each epoch
+ if args.with_tracking:
+ total_loss = 0
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ # New Code #
+ if args.with_tracking:
+ total_loss += loss.detach().float()
+ loss = loss / gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True` (the default).
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+
+ # New Code #
+ # To actually log, we call `Accelerator.log`
+ # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int`
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "accuracy": eval_metric["accuracy"],
+ "f1": eval_metric["f1"],
+ "train_loss": total_loss.item() / len(train_dataloader),
+ "epoch": epoch,
+ },
+ step=epoch,
+ )
+
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ parser.add_argument(
+ "--with_tracking",
+ action="store_true",
+ help="Whether to load in all available experiment trackers from the environment and use them for logging.",
+ )
+ parser.add_argument(
+ "--project_dir",
+ type=str,
+ default="logs",
+ help="Location on where to store experiment tracking logs` and relevent project information",
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/complete_cv_example.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/complete_cv_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fa9fceb853fb08ccc567fb6be434f69e95375ee
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/complete_cv_example.py
@@ -0,0 +1,329 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+import re
+
+import numpy as np
+import PIL
+import torch
+from timm import create_model
+from torch.optim.lr_scheduler import OneCycleLR
+from torch.utils.data import DataLoader, Dataset
+from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
+
+from accelerate import Accelerator, DataLoaderConfiguration
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+#
+# This example trains a ResNet50 on the Oxford-IIT Pet Dataset
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+# Function to get the label from the filename
+def extract_label(fname):
+ stem = fname.split(os.path.sep)[-1]
+ return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0]
+
+
+class PetsDataset(Dataset):
+ def __init__(self, file_names, image_transform=None, label_to_id=None):
+ self.file_names = file_names
+ self.image_transform = image_transform
+ self.label_to_id = label_to_id
+
+ def __len__(self):
+ return len(self.file_names)
+
+ def __getitem__(self, idx):
+ fname = self.file_names[idx]
+ raw_image = PIL.Image.open(fname)
+ image = raw_image.convert("RGB")
+ if self.image_transform is not None:
+ image = self.image_transform(image)
+ label = extract_label(fname)
+ if self.label_to_id is not None:
+ label = self.label_to_id[label]
+ return {"image": image, "label": label}
+
+
+def training_function(config, args):
+ # Initialize accelerator
+ dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader)
+ if args.with_tracking:
+ accelerator = Accelerator(
+ cpu=args.cpu,
+ mixed_precision=args.mixed_precision,
+ log_with="all",
+ project_dir=args.project_dir,
+ dataloader_config=dataloader_config,
+ )
+ else:
+ accelerator = Accelerator(
+ cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config
+ )
+
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+ image_size = config["image_size"]
+ if not isinstance(image_size, (list, tuple)):
+ image_size = (image_size, image_size)
+
+ # Parse out whether we are saving every epoch or after a certain number of batches
+ if hasattr(args.checkpointing_steps, "isdigit"):
+ if args.checkpointing_steps == "epoch":
+ checkpointing_steps = args.checkpointing_steps
+ elif args.checkpointing_steps.isdigit():
+ checkpointing_steps = int(args.checkpointing_steps)
+ else:
+ raise ValueError(
+ f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
+ )
+ else:
+ checkpointing_steps = None
+
+ # We need to initialize the trackers we use, and also store our configuration
+ if args.with_tracking:
+ run = os.path.split(__file__)[-1].split(".")[0]
+ accelerator.init_trackers(run, config)
+
+ # Grab all the image filenames
+ file_names = [os.path.join(args.data_dir, fname) for fname in os.listdir(args.data_dir) if fname.endswith(".jpg")]
+
+ # Build the label correspondences
+ all_labels = [extract_label(fname) for fname in file_names]
+ id_to_label = list(set(all_labels))
+ id_to_label.sort()
+ label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)}
+
+ # Set the seed before splitting the data.
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+
+ # Split our filenames between train and validation
+ random_perm = np.random.permutation(len(file_names))
+ cut = int(0.8 * len(file_names))
+ train_split = random_perm[:cut]
+ eval_split = random_perm[cut:]
+
+ # For training we use a simple RandomResizedCrop
+ train_tfm = Compose([RandomResizedCrop(image_size, scale=(0.5, 1.0)), ToTensor()])
+ train_dataset = PetsDataset(
+ [file_names[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id
+ )
+
+ # For evaluation, we use a deterministic Resize
+ eval_tfm = Compose([Resize(image_size), ToTensor()])
+ eval_dataset = PetsDataset([file_names[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id)
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4)
+ eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size, num_workers=4)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id))
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Freezing the base model
+ for param in model.parameters():
+ param.requires_grad = False
+ for param in model.get_classifier().parameters():
+ param.requires_grad = True
+
+ # We normalize the batches of images to be a bit faster.
+ mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None].to(accelerator.device)
+ std = torch.tensor(model.default_cfg["std"])[None, :, None, None].to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=lr / 25)
+
+ # Instantiate learning rate scheduler
+ lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=lr, epochs=num_epochs, steps_per_epoch=len(train_dataloader))
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+ # We need to keep track of how many total steps we have iterated over
+ overall_step = 0
+ # We also need to keep track of the starting epoch so files are named properly
+ starting_epoch = 0
+
+ # Potentially load in the weights and states from a previous save
+ if args.resume_from_checkpoint:
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
+ accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
+ accelerator.load_state(args.resume_from_checkpoint)
+ path = os.path.basename(args.resume_from_checkpoint)
+ else:
+ # Get the most recent checkpoint
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
+ dirs.sort(key=os.path.getctime)
+ path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ # Extract `epoch_{i}` or `step_{i}`
+ training_difference = os.path.splitext(path)[0]
+
+ if "epoch" in training_difference:
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
+ resume_step = None
+ else:
+ resume_step = int(training_difference.replace("step_", ""))
+ starting_epoch = resume_step // len(train_dataloader)
+ resume_step -= starting_epoch * len(train_dataloader)
+
+ # Now we train the model
+ for epoch in range(starting_epoch, num_epochs):
+ model.train()
+ if args.with_tracking:
+ total_loss = 0
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We need to skip steps until we reach the resumed step
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ overall_step += resume_step
+ else:
+ # After the first iteration though, we need to go back to the original dataloader
+ active_dataloader = train_dataloader
+ for batch in active_dataloader:
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch = {k: v.to(accelerator.device) for k, v in batch.items()}
+ inputs = (batch["image"] - mean) / std
+ outputs = model(inputs)
+ loss = torch.nn.functional.cross_entropy(outputs, batch["label"])
+ # We keep track of the loss at each epoch
+ if args.with_tracking:
+ total_loss += loss.detach().float()
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ overall_step += 1
+ if isinstance(checkpointing_steps, int):
+ output_dir = f"step_{overall_step}"
+ if overall_step % checkpointing_steps == 0:
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+ model.eval()
+ accurate = 0
+ num_elems = 0
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch = {k: v.to(accelerator.device) for k, v in batch.items()}
+ inputs = (batch["image"] - mean) / std
+ with torch.no_grad():
+ outputs = model(inputs)
+ predictions = outputs.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["label"]))
+ accurate_preds = predictions == references
+ num_elems += accurate_preds.shape[0]
+ accurate += accurate_preds.long().sum()
+
+ eval_metric = accurate.item() / num_elems
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}")
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "accuracy": 100 * eval_metric,
+ "train_loss": total_loss.item() / len(train_dataloader),
+ "epoch": epoch,
+ },
+ step=overall_step,
+ )
+ if checkpointing_steps == "epoch":
+ output_dir = f"epoch_{epoch}"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument("--data_dir", required=True, help="The data folder on disk.")
+ parser.add_argument("--fp16", action="store_true", help="If passed, will use FP16 training.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ parser.add_argument(
+ "--checkpointing_steps",
+ type=str,
+ default=None,
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
+ )
+ parser.add_argument(
+ "--output_dir",
+ type=str,
+ default=".",
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
+ )
+ parser.add_argument(
+ "--resume_from_checkpoint",
+ type=str,
+ default=None,
+ help="If the training should continue from a checkpoint folder.",
+ )
+ parser.add_argument(
+ "--use_stateful_dataloader",
+ action="store_true",
+ help="If the dataloader should be a resumable stateful dataloader.",
+ )
+ parser.add_argument(
+ "--with_tracking",
+ action="store_true",
+ help="Whether to load in all available experiment trackers from the environment and use them for logging.",
+ )
+ parser.add_argument(
+ "--project_dir",
+ type=str,
+ default="logs",
+ help="Location on where to store experiment tracking logs` and relevent project information",
+ )
+ args = parser.parse_args()
+ config = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/complete_nlp_example.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/complete_nlp_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..a692cb7b773bcedb06d1e70707a55898ffb43c03
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/complete_nlp_example.py
@@ -0,0 +1,324 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+
+import evaluate
+import torch
+from datasets import load_dataset
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
+
+from accelerate import Accelerator, DataLoaderConfiguration, DistributedType
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+#
+# This example trains a Bert base model on GLUE MRPC
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# This example also demonstrates the checkpointing and sharding capabilities
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+MAX_GPU_BATCH_SIZE = 16
+EVAL_BATCH_SIZE = 32
+
+
+def training_function(config, args):
+ # Initialize accelerator
+ dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader)
+ if args.with_tracking:
+ accelerator = Accelerator(
+ cpu=args.cpu,
+ mixed_precision=args.mixed_precision,
+ dataloader_config=dataloader_config,
+ log_with="all",
+ project_dir=args.project_dir,
+ )
+ else:
+ accelerator = Accelerator(
+ cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config
+ )
+
+ if hasattr(args.checkpointing_steps, "isdigit"):
+ if args.checkpointing_steps == "epoch":
+ checkpointing_steps = args.checkpointing_steps
+ elif args.checkpointing_steps.isdigit():
+ checkpointing_steps = int(args.checkpointing_steps)
+ else:
+ raise ValueError(
+ f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
+ )
+ else:
+ checkpointing_steps = None
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+
+ # We need to initialize the trackers we use, and also store our configuration
+ if args.with_tracking:
+ run = os.path.split(__file__)[-1].split(".")[0]
+ accelerator.init_trackers(run, config)
+
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+ datasets = load_dataset("glue", "mrpc")
+ metric = evaluate.load("glue", "mrpc")
+
+ def tokenize_function(examples):
+ # max_length=None => use the model max length (it's actually the default)
+ outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
+ return outputs
+
+ # Apply the method we just defined to all the examples in all the splits of the dataset
+ # starting with the main process first:
+ with accelerator.main_process_first():
+ tokenized_datasets = datasets.map(
+ tokenize_function,
+ batched=True,
+ remove_columns=["idx", "sentence1", "sentence2"],
+ )
+
+ # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
+ # transformers library
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+
+ # If the batch size is too big we use gradient accumulation
+ gradient_accumulation_steps = 1
+ if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
+ gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
+ batch_size = MAX_GPU_BATCH_SIZE
+
+ def collate_fn(examples):
+ # On TPU it's best to pad everything to the same length or training will be very slow.
+ max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
+ # When using mixed precision we want round multiples of 8/16
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+
+ return tokenizer.pad(
+ examples,
+ padding="longest",
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(
+ tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
+ )
+ eval_dataloader = DataLoader(
+ tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
+ )
+
+ set_seed(seed)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = AdamW(params=model.parameters(), lr=lr)
+
+ # Instantiate scheduler
+ lr_scheduler = get_linear_schedule_with_warmup(
+ optimizer=optimizer,
+ num_warmup_steps=100,
+ num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
+ )
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # We need to keep track of how many total steps we have iterated over
+ overall_step = 0
+ # We also need to keep track of the stating epoch so files are named properly
+ starting_epoch = 0
+
+ # Potentially load in the weights and states from a previous save
+ if args.resume_from_checkpoint:
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
+ accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
+ accelerator.load_state(args.resume_from_checkpoint)
+ path = os.path.basename(args.resume_from_checkpoint)
+ else:
+ # Get the most recent checkpoint
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
+ dirs.sort(key=os.path.getctime)
+ path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ # Extract `epoch_{i}` or `step_{i}`
+ training_difference = os.path.splitext(path)[0]
+
+ if "epoch" in training_difference:
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
+ resume_step = None
+ else:
+ resume_step = int(training_difference.replace("step_", ""))
+ starting_epoch = resume_step // len(train_dataloader)
+ resume_step -= starting_epoch * len(train_dataloader)
+
+ # Now we train the model
+ for epoch in range(starting_epoch, num_epochs):
+ model.train()
+ if args.with_tracking:
+ total_loss = 0
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We need to skip steps until we reach the resumed step
+ if not args.use_stateful_dataloader:
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ overall_step += resume_step
+ else:
+ # After the first iteration though, we need to go back to the original dataloader
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / gradient_accumulation_steps
+ # We keep track of the loss at each epoch
+ if args.with_tracking:
+ total_loss += loss.detach().float()
+ accelerator.backward(loss)
+ if step % gradient_accumulation_steps == 0:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ overall_step += 1
+
+ if isinstance(checkpointing_steps, int):
+ output_dir = f"step_{overall_step}"
+ if overall_step % checkpointing_steps == 0:
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch.to(accelerator.device)
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
+ metric.add_batch(
+ predictions=predictions,
+ references=references,
+ )
+
+ eval_metric = metric.compute()
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}:", eval_metric)
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "accuracy": eval_metric["accuracy"],
+ "f1": eval_metric["f1"],
+ "train_loss": total_loss.item() / len(train_dataloader),
+ "epoch": epoch,
+ },
+ step=epoch,
+ )
+
+ if checkpointing_steps == "epoch":
+ output_dir = f"epoch_{epoch}"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ parser.add_argument(
+ "--checkpointing_steps",
+ type=str,
+ default=None,
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
+ )
+ parser.add_argument(
+ "--resume_from_checkpoint",
+ type=str,
+ default=None,
+ help="If the training should continue from a checkpoint folder.",
+ )
+ parser.add_argument(
+ "--use_stateful_dataloader",
+ action="store_true",
+ help="If the dataloader should be a resumable stateful dataloader.",
+ )
+ parser.add_argument(
+ "--with_tracking",
+ action="store_true",
+ help="Whether to load in all available experiment trackers from the environment and use them for logging.",
+ )
+ parser.add_argument(
+ "--output_dir",
+ type=str,
+ default=".",
+ help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
+ )
+ parser.add_argument(
+ "--project_dir",
+ type=str,
+ default="logs",
+ help="Location on where to store experiment tracking logs` and relevent project information",
+ )
+ args = parser.parse_args()
+ config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/README.md b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..4cfd56f2ac5e2b6bc3579acfe29ef332d3d59e7e
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/README.md
@@ -0,0 +1,10 @@
+# Config Zoo
+
+This folder contains a variety of minimal configurations for `Accelerate` achieving certain goals. You can use these
+direct config YAML's, or build off of them for your own YAML's.
+
+These are highly annoted versions, aiming to teach you what each section does.
+
+Each config can be run via `accelerate launch --config_file {file} run_me.py`
+
+`run_me.py` will then print out how the current environment is setup (the contents of the `AcceleratorState`)
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/deepspeed.yaml b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/deepspeed.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5efddd05245a18105e5934f217b9b0cdd8fe7834
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/deepspeed.yaml
@@ -0,0 +1,15 @@
+# Similar to FSDP, we set the distributed type as DEEPSPEED
+distributed_type: DEEPSPEED
+# With DeepSpeed, we utilize a deepspeed config file for the entire configuration
+deepspeed_config:
+ # Can also be any of the config json's in accelerate/examples/deepspeed_config_templates
+ deepspeed_config_file: ../deepspeed_config_templates/zero_stage1_config.json
+ # If using ZeRO-3 and wanting to load big models in, this should be set to `true` so
+ # `transformers` uses the right `init` function
+ zero3_init_flag: false # true
+
+# Finally we need to specify the number of GPUs to use
+num_processes: 2
+# Optionally we can set the mixed precision now instead of in the deepspeed config file,
+# however this requires the `fp16` and `bf16` options to be set to `auto` in the deepspeed config file
+# mixed_precision: "bf16"
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/fp8.yaml b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/fp8.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..256bca970d28966863b886ca42523d4ad2bbb4cb
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/fp8.yaml
@@ -0,0 +1,18 @@
+# This config template simply setups up the TransformersEngine config (and a config for a single GPU),
+# this can interop with the other configs in this folder
+distributed_type: "NO"
+mixed_precision: "fp8"
+# Then we specify the fp8 configuration:
+fp8_config:
+ backend: TE # Can be TE | MS-AMP
+ # The following are TE specific arguments.
+ # See https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html#common-api for more details
+ amax_history_len: 1024
+ fp8_format: E4M3
+ interval: 1
+ margin: 0
+ override_linear_precision: (false, false, false)
+ # Generally this should always be set to `false` to have the most realistic fp8 eval performance
+ use_autocast_during_eval: false
+ # If using MS-AMP, we ignore all of the prior and set a opt_level
+ #opt_level: O1
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/fsdp.yaml b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/fsdp.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..07c3e1b83e085011f4ccdd6811ebd91938aa7d41
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/fsdp.yaml
@@ -0,0 +1,18 @@
+# Since we are doing FSDP (even though it's multi-GPU), we need to specify the distributed type as FSDP
+distributed_type: FSDP
+# Can be one of "no", "fp16", or "bf16" (see `transformer_engine.yaml` for `fp8`, but it works for FSDP as well)
+mixed_precision: 'bf16'
+# Specify the number of GPUs to use
+num_processes: 2
+# Then we can specify the FSDP config
+fsdp_config:
+ fsdp_activation_checkpointing: false
+ fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
+ fsdp_backward_prefetch: BACKWARD_PRE
+ fsdp_cpu_ram_efficient_loading: true
+ fsdp_forward_prefetch: false
+ fsdp_offload_params: false
+ fsdp_sharding_strategy: FULL_SHARD
+ fsdp_state_dict_type: SHARDED_STATE_DICT
+ fsdp_sync_module_states: true
+ fsdp_use_orig_params: true
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/multi_gpu.yaml b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/multi_gpu.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9d6c12bf667960e3849231b26ebcf1ae9e5432f5
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/multi_gpu.yaml
@@ -0,0 +1,6 @@
+# Specify distributed_type as `MULTI_GPU` for DDP
+distributed_type: "MULTI_GPU"
+# Can be one of "no", "fp16", or "bf16" (see `transformer_engine.yaml` for `fp8`)
+mixed_precision: "bf16"
+# Specify the number of GPUs to use
+num_processes: 2
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/multi_node.yaml b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/multi_node.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b76699f849c815b6956eb5643ae0ea865f44ecf2
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/multi_node.yaml
@@ -0,0 +1,16 @@
+# This config template is for a multi-node setup. This assumes DDP, but can be interop'd with the other configs in this folder
+# Generally it's recommended to look at the SLURM config template for a more robust multi-node setup
+distributed_type: MULTI_GPU
+# We need to specify the current machine's rank
+machine_rank: 0
+# We then need to specify the IP address and port of the main process
+main_process_ip: '1234'
+main_process_port: 9999
+# We need to specify the number of machines
+num_machines: 2
+# We need to specify the *total* number of processes
+num_processes: 8
+# And then we need to specify how rdvz comms will be handled
+rdzv_backend: static # or c10d
+# If the compute nodes are on the same network (cloud will more than likely be false)
+same_network: false
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/run_me.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/run_me.py
new file mode 100644
index 0000000000000000000000000000000000000000..f016bc2bf5da86f6f4b628efcdfdcbf3c4ed6143
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/run_me.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+A base script which outputs the accelerate config for the given environment
+"""
+
+from accelerate import Accelerator
+
+
+accelerator = Accelerator()
+
+accelerator.print(f"Accelerator state from the current environment:\n{accelerator.state}")
+if accelerator.fp8_recipe_handler is not None:
+ accelerator.print(f"FP8 config:\n{accelerator.fp8_recipe_handler}")
+accelerator.end_training()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/single_gpu.yaml b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/single_gpu.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..3d1a81cedaf0b057f91401b7532874bcab75779c
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/config_yaml_templates/single_gpu.yaml
@@ -0,0 +1,4 @@
+# Since this is single GPU, we don't need distributed training
+distributed_type: "NO"
+# Can be one of "no", "fp16", or "bf16" (see `transformer_engine.yaml` for `fp8`)
+mixed_precision: "bf16"
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/cv_example.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/cv_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7e268ee661ccb5b89aa31f60e3b593d18b6294d
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/cv_example.py
@@ -0,0 +1,209 @@
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import os
+import re
+
+import numpy as np
+import PIL
+import torch
+from timm import create_model
+from torch.optim.lr_scheduler import OneCycleLR
+from torch.utils.data import DataLoader, Dataset
+from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
+
+from accelerate import Accelerator
+from accelerate.utils import set_seed
+
+
+########################################################################
+# This is a fully working simple example to use Accelerate
+#
+# This example trains a ResNet50 on the Oxford-IIT Pet Dataset
+# in any of the following settings (with the same script):
+# - single CPU or single GPU
+# - multi GPUS (using PyTorch distributed mode)
+# - (multi) TPUs
+# - fp16 (mixed-precision) or fp32 (normal precision)
+#
+# To run it in each of these various modes, follow the instructions
+# in the readme for examples:
+# https://github.com/huggingface/accelerate/tree/main/examples
+#
+########################################################################
+
+
+# Function to get the label from the filename
+def extract_label(fname):
+ stem = fname.split(os.path.sep)[-1]
+ return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0]
+
+
+class PetsDataset(Dataset):
+ def __init__(self, file_names, image_transform=None, label_to_id=None):
+ self.file_names = file_names
+ self.image_transform = image_transform
+ self.label_to_id = label_to_id
+
+ def __len__(self):
+ return len(self.file_names)
+
+ def __getitem__(self, idx):
+ fname = self.file_names[idx]
+ raw_image = PIL.Image.open(fname)
+ image = raw_image.convert("RGB")
+ if self.image_transform is not None:
+ image = self.image_transform(image)
+ label = extract_label(fname)
+ if self.label_to_id is not None:
+ label = self.label_to_id[label]
+ return {"image": image, "label": label}
+
+
+def training_function(config, args):
+ # Initialize accelerator
+ accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
+
+ # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
+ lr = config["lr"]
+ num_epochs = int(config["num_epochs"])
+ seed = int(config["seed"])
+ batch_size = int(config["batch_size"])
+ image_size = config["image_size"]
+ if not isinstance(image_size, (list, tuple)):
+ image_size = (image_size, image_size)
+
+ # Grab all the image filenames
+ file_names = [os.path.join(args.data_dir, fname) for fname in os.listdir(args.data_dir) if fname.endswith(".jpg")]
+
+ # Build the label correspondences
+ all_labels = [extract_label(fname) for fname in file_names]
+ id_to_label = list(set(all_labels))
+ id_to_label.sort()
+ label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)}
+
+ # Set the seed before splitting the data.
+ set_seed(seed)
+ # Split our filenames between train and validation
+ random_perm = np.random.permutation(len(file_names))
+ cut = int(0.8 * len(file_names))
+ train_split = random_perm[:cut]
+ eval_split = random_perm[cut:]
+
+ # For training we use a simple RandomResizedCrop
+ train_tfm = Compose([RandomResizedCrop(image_size, scale=(0.5, 1.0)), ToTensor()])
+ train_dataset = PetsDataset(
+ [file_names[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id
+ )
+
+ # For evaluation, we use a deterministic Resize
+ eval_tfm = Compose([Resize(image_size), ToTensor()])
+ eval_dataset = PetsDataset([file_names[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id)
+
+ # Instantiate dataloaders.
+ train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4)
+ eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size, num_workers=4)
+
+ # Instantiate the model (we build the model here so that the seed also control new weights initialization)
+ model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id))
+
+ # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
+ # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
+ # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
+ model = model.to(accelerator.device)
+
+ # Freezing the base model
+ for param in model.parameters():
+ param.requires_grad = False
+ for param in model.get_classifier().parameters():
+ param.requires_grad = True
+
+ # We normalize the batches of images to be a bit faster.
+ mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None].to(accelerator.device)
+ std = torch.tensor(model.default_cfg["std"])[None, :, None, None].to(accelerator.device)
+
+ # Instantiate optimizer
+ optimizer = torch.optim.Adam(params=model.parameters(), lr=lr / 25)
+
+ # Instantiate learning rate scheduler
+ lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=lr, epochs=num_epochs, steps_per_epoch=len(train_dataloader))
+
+ # Prepare everything
+ # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
+ # prepare method.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
+ )
+
+ # Now we train the model
+ for epoch in range(num_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch = {k: v.to(accelerator.device) for k, v in batch.items()}
+ inputs = (batch["image"] - mean) / std
+ outputs = model(inputs)
+ loss = torch.nn.functional.cross_entropy(outputs, batch["label"])
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ model.eval()
+ accurate = 0
+ num_elems = 0
+ for _, batch in enumerate(eval_dataloader):
+ # We could avoid this line since we set the accelerator with `device_placement=True`.
+ batch = {k: v.to(accelerator.device) for k, v in batch.items()}
+ inputs = (batch["image"] - mean) / std
+ with torch.no_grad():
+ outputs = model(inputs)
+ predictions = outputs.argmax(dim=-1)
+ predictions, references = accelerator.gather_for_metrics((predictions, batch["label"]))
+ accurate_preds = predictions == references
+ num_elems += accurate_preds.shape[0]
+ accurate += accurate_preds.long().sum()
+
+ eval_metric = accurate.item() / num_elems
+ # Use accelerator.print to print only on the main process.
+ accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}")
+ accelerator.end_training()
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Simple example of training script.")
+ parser.add_argument("--data_dir", required=True, help="The data folder on disk.")
+ parser.add_argument(
+ "--mixed_precision",
+ type=str,
+ default=None,
+ choices=["no", "fp16", "bf16", "fp8"],
+ help="Whether to use mixed precision. Choose"
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
+ "and an Nvidia Ampere GPU.",
+ )
+ parser.add_argument(
+ "--checkpointing_steps",
+ type=str,
+ default=None,
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
+ )
+ parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
+ args = parser.parse_args()
+ config = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224}
+ training_function(config, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage1_config.json b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage1_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..674420e57fc21329cd466dc2a2e68f981c621bce
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage1_config.json
@@ -0,0 +1,43 @@
+{
+ "fp16": {
+ "enabled": true,
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "optimizer": {
+ "type": "AdamW",
+ "params": {
+ "lr": "auto",
+ "weight_decay": "auto",
+ "torch_adam": true,
+ "adam_w_mode": true
+ }
+ },
+ "scheduler": {
+ "type": "WarmupDecayLR",
+ "params": {
+ "warmup_min_lr": "auto",
+ "warmup_max_lr": "auto",
+ "warmup_num_steps": "auto",
+ "total_num_steps": "auto"
+ }
+ },
+ "zero_optimization": {
+ "stage": 1,
+ "allgather_partitions": true,
+ "allgather_bucket_size": 2e8,
+ "overlap_comm": true,
+ "reduce_scatter": true,
+ "reduce_bucket_size": "auto",
+ "contiguous_gradients": true
+ },
+ "gradient_accumulation_steps": 1,
+ "gradient_clipping": "auto",
+ "steps_per_print": 2000,
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "wall_clock_breakdown": false
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage2_config.json b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage2_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..9597f8485c1a96424ff91f88ab9d934c4ac07bb9
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage2_config.json
@@ -0,0 +1,43 @@
+{
+ "fp16": {
+ "enabled": true,
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "optimizer": {
+ "type": "AdamW",
+ "params": {
+ "lr": "auto",
+ "weight_decay": "auto",
+ "torch_adam": true,
+ "adam_w_mode": true
+ }
+ },
+ "scheduler": {
+ "type": "WarmupDecayLR",
+ "params": {
+ "warmup_min_lr": "auto",
+ "warmup_max_lr": "auto",
+ "warmup_num_steps": "auto",
+ "total_num_steps": "auto"
+ }
+ },
+ "zero_optimization": {
+ "stage": 2,
+ "allgather_partitions": true,
+ "allgather_bucket_size": 2e8,
+ "overlap_comm": true,
+ "reduce_scatter": true,
+ "reduce_bucket_size": "auto",
+ "contiguous_gradients": true
+ },
+ "gradient_accumulation_steps": 1,
+ "gradient_clipping": "auto",
+ "steps_per_print": 2000,
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "wall_clock_breakdown": false
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage2_offload_config.json b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage2_offload_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..98baedef38a86fe1cef3d5e1a8659b6b08eb275b
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage2_offload_config.json
@@ -0,0 +1,47 @@
+{
+ "fp16": {
+ "enabled": true,
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "optimizer": {
+ "type": "AdamW",
+ "params": {
+ "lr": "auto",
+ "weight_decay": "auto",
+ "torch_adam": true,
+ "adam_w_mode": true
+ }
+ },
+ "scheduler": {
+ "type": "WarmupDecayLR",
+ "params": {
+ "warmup_min_lr": "auto",
+ "warmup_max_lr": "auto",
+ "warmup_num_steps": "auto",
+ "total_num_steps": "auto"
+ }
+ },
+ "zero_optimization": {
+ "stage": 2,
+ "offload_optimizer": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "allgather_partitions": true,
+ "allgather_bucket_size": 2e8,
+ "overlap_comm": true,
+ "reduce_scatter": true,
+ "reduce_bucket_size": "auto",
+ "contiguous_gradients": true
+ },
+ "gradient_accumulation_steps": 1,
+ "gradient_clipping": "auto",
+ "steps_per_print": 2000,
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "wall_clock_breakdown": false
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage3_config.json b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage3_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..2ec6fff41a79b4f1ad0d1849cbba640de67b113d
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage3_config.json
@@ -0,0 +1,44 @@
+{
+ "fp16": {
+ "enabled": true,
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "optimizer": {
+ "type": "AdamW",
+ "params": {
+ "lr": "auto",
+ "weight_decay": "auto"
+ }
+ },
+ "scheduler": {
+ "type": "WarmupDecayLR",
+ "params": {
+ "warmup_min_lr": "auto",
+ "warmup_max_lr": "auto",
+ "warmup_num_steps": "auto",
+ "total_num_steps": "auto"
+ }
+ },
+ "zero_optimization": {
+ "stage": 3,
+ "overlap_comm": true,
+ "contiguous_gradients": true,
+ "reduce_bucket_size": "auto",
+ "stage3_prefetch_bucket_size": "auto",
+ "stage3_param_persistence_threshold": "auto",
+ "sub_group_size": 1e9,
+ "stage3_max_live_parameters": 1e9,
+ "stage3_max_reuse_distance": 1e9,
+ "stage3_gather_16bit_weights_on_model_save": "auto"
+ },
+ "gradient_accumulation_steps": 1,
+ "gradient_clipping": "auto",
+ "steps_per_print": 2000,
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "wall_clock_breakdown": false
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage3_offload_config.json b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage3_offload_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..edae8e6286e632d40fffd990b39bbde5d7409c03
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/deepspeed_config_templates/zero_stage3_offload_config.json
@@ -0,0 +1,52 @@
+{
+ "fp16": {
+ "enabled": true,
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "optimizer": {
+ "type": "AdamW",
+ "params": {
+ "lr": "auto",
+ "weight_decay": "auto"
+ }
+ },
+ "scheduler": {
+ "type": "WarmupDecayLR",
+ "params": {
+ "warmup_min_lr": "auto",
+ "warmup_max_lr": "auto",
+ "warmup_num_steps": "auto",
+ "total_num_steps": "auto"
+ }
+ },
+ "zero_optimization": {
+ "stage": 3,
+ "offload_optimizer": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "offload_param": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "overlap_comm": true,
+ "contiguous_gradients": true,
+ "reduce_bucket_size": "auto",
+ "stage3_prefetch_bucket_size": "auto",
+ "stage3_param_persistence_threshold": "auto",
+ "sub_group_size": 1e9,
+ "stage3_max_live_parameters": 1e9,
+ "stage3_max_reuse_distance": 1e9,
+ "stage3_gather_16bit_weights_on_model_save": "auto"
+ },
+ "gradient_accumulation_steps": 1,
+ "gradient_clipping": "auto",
+ "steps_per_print": 2000,
+ "train_batch_size": "auto",
+ "train_micro_batch_size_per_gpu": "auto",
+ "wall_clock_breakdown": false
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/README.md b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..92828e7d94164360aeb5c58fb73de469ede2e75f
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/README.md
@@ -0,0 +1,25 @@
+# Distributed inference examples
+
+This folder contains a variety of tutorials for running distributed inference with the following strategy:
+
+Load an entire model onto each GPU and sending chunks of a batch through each GPU’s model copy at a time
+
+## Installation
+
+```bash
+pip install accelerate torch
+```
+
+## Running code
+
+You can either use `torchrun` or the recommended way of `accelerate launch` (without needing to run `accelerate config`) on each script:
+
+```bash
+accelerate launch --num_processes {NUM_GPUS} phi2.py
+```
+
+Or:
+
+```bash
+torchrun --nproc-per-node {NUM_GPUS} phi2.py
+```
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/distributed_image_generation.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/distributed_image_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..68997e9e11ffa70ecd63379c19f622c2f4fc85a1
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/distributed_image_generation.py
@@ -0,0 +1,117 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Originally by jiwooya1000, put together together by sayakpaul.
+Documentation: https://huggingface.co/docs/diffusers/main/en/training/distributed_inference
+
+Run:
+
+accelerate launch distributed_image_generation.py --batch_size 8
+
+# Enable memory optimizations for large models like SD3
+accelerate launch distributed_image_generation.py --batch_size 8 --low_mem
+"""
+
+import os
+import time
+
+import fire
+import torch
+from datasets import load_dataset
+from diffusers import DiffusionPipeline
+from tqdm import tqdm
+
+from accelerate import PartialState
+from accelerate.utils import gather_object
+
+
+START_TIME = time.strftime("%Y%m%d_%H%M%S")
+DTYPE_MAP = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16}
+
+
+def get_batches(items, batch_size):
+ num_batches = (len(items) + batch_size - 1) // batch_size
+ batches = []
+
+ for i in range(num_batches):
+ start_index = i * batch_size
+ end_index = min((i + 1) * batch_size, len(items))
+ batch = items[start_index:end_index]
+ batches.append(batch)
+
+ return batches
+
+
+def main(
+ ckpt_id: str = "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
+ save_dir: str = "./evaluation/examples",
+ seed: int = 1,
+ batch_size: int = 4,
+ num_inference_steps: int = 20,
+ guidance_scale: float = 4.5,
+ dtype: str = "fp16",
+ low_mem: bool = False,
+):
+ pipeline = DiffusionPipeline.from_pretrained(ckpt_id, torch_dtype=DTYPE_MAP[dtype])
+
+ save_dir = save_dir + f"_{START_TIME}"
+
+ parti_prompts = load_dataset("nateraw/parti-prompts", split="train")
+ data_loader = get_batches(items=parti_prompts["Prompt"], batch_size=batch_size)
+
+ distributed_state = PartialState()
+ if low_mem:
+ pipeline.enable_model_cpu_offload(gpu_id=distributed_state.device.index)
+ else:
+ pipeline = pipeline.to(distributed_state.device)
+
+ if distributed_state.is_main_process:
+ if not os.path.exists(save_dir):
+ os.makedirs(save_dir)
+ print(f"Directory '{save_dir}' created successfully.")
+ else:
+ print(f"Directory '{save_dir}' already exists.")
+
+ count = 0
+ for _, prompts_raw in tqdm(enumerate(data_loader), total=len(data_loader)):
+ input_prompts = []
+
+ with distributed_state.split_between_processes(prompts_raw) as prompts:
+ generator = torch.manual_seed(seed)
+ images = pipeline(
+ prompts, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator
+ ).images
+ input_prompts.extend(prompts)
+
+ distributed_state.wait_for_everyone()
+
+ images = gather_object(images)
+ input_prompts = gather_object(input_prompts)
+
+ if distributed_state.is_main_process:
+ for image, prompt in zip(images, input_prompts):
+ count += 1
+ temp_dir = os.path.join(save_dir, f"example_{count}")
+
+ os.makedirs(temp_dir)
+ prompt = "_".join(prompt.split())
+ image.save(f"image_{prompt}.png")
+
+ if distributed_state.is_main_process:
+ print(f">>> Image Generation Finished. Saved in {save_dir}")
+
+
+if __name__ == "__main__":
+ fire.Fire(main)
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/distributed_speech_generation.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/distributed_speech_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..f44346c533fa0f5d9d9e6c7156b69996102f8f55
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/distributed_speech_generation.py
@@ -0,0 +1,234 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import json
+import os
+import pathlib
+import queue
+from concurrent.futures import ThreadPoolExecutor
+from typing import Union
+
+import fire
+import scipy.io.wavfile
+import torch
+from datasets import load_dataset
+from transformers import AutoTokenizer, VitsModel
+
+from accelerate import PartialState
+from accelerate.utils import tqdm
+
+
+"""
+Requirements: transformers accelerate fire scipy datasets
+pip install transformers accelerate fire scipy datasets
+Example usage:
+accelerate launch distributed_speech_generation.py --output_path outputs --batch_size 8 --num_workers 2 --dataset_split train
+"""
+
+"""
+To run the speech generation
+import scipy.io.wavfile
+import numpy as np
+from IPython.display import Audio
+sample_rate, audio_data = scipy.io.wavfile.read('path_to_you_wav_file.wav')
+audio_data = audio_data.astype(np.float32) / 32762.0
+Audio(audio_data, rate=sample_rate)
+"""
+
+
+def load_pokemon_data(split: str, max_text_length: int):
+ """Load Pokemon descriptions from the dataset"""
+ ds = load_dataset("svjack/pokemon-blip-captions-en-zh", split=split)
+
+ # Create dataset of dictionaries
+ dataset = []
+ for idx, text in enumerate(ds["en_text"]):
+ if len(text.strip()) > 0: # Skip empty descriptions
+ dataset.append(
+ {
+ "id": f"pokemon_{idx:06d}",
+ "text": text.strip()[:max_text_length], # Truncate long descriptions
+ "original_text": text.strip(), # Keep original for metadata
+ }
+ )
+ return dataset
+
+
+class ExistsFilter:
+ def __init__(self, output_dir: Union[pathlib.Path, str]):
+ current_files = [f.split(".wav")[0] for f in os.listdir(output_dir) if f.endswith(".wav")]
+ self.processed_files = set(current_files)
+ print(f"Existing audio files found: {len(self.processed_files)}.")
+
+ def __call__(self, x):
+ return x["id"] not in self.processed_files
+
+
+def preprocess_fn(sample, tokenizer, max_text_length: int):
+ inputs = tokenizer(sample["text"], padding=False, truncation=True, max_length=max_text_length, return_tensors="pt")
+
+ return {
+ "input_ids": inputs["input_ids"][0].tolist(),
+ "attention_mask": inputs["attention_mask"][0].tolist(),
+ "id": sample["id"],
+ "text": sample["text"],
+ "original_text": sample["original_text"],
+ }
+
+
+def collate_fn(examples, tokenizer):
+ """Collate batch of examples with proper padding"""
+ # Find max length in this batch
+ max_length = max(len(example["input_ids"]) for example in examples)
+
+ # Pad sequences to max_length
+ input_ids_list = []
+ attention_mask_list = []
+
+ for example in examples:
+ # Get current lengths
+ curr_len = len(example["input_ids"])
+ padding_length = max_length - curr_len
+
+ # Pad sequences
+ padded_input_ids = example["input_ids"] + [tokenizer.pad_token_id] * padding_length
+ padded_attention_mask = example["attention_mask"] + [0] * padding_length
+
+ input_ids_list.append(padded_input_ids)
+ attention_mask_list.append(padded_attention_mask)
+
+ # Convert to tensors
+ input_ids = torch.tensor(input_ids_list, dtype=torch.long)
+ attention_mask = torch.tensor(attention_mask_list, dtype=torch.long)
+
+ ids = [example["id"] for example in examples]
+ texts = [example["text"] for example in examples]
+ original_texts = [example["original_text"] for example in examples]
+
+ return {
+ "input_ids": input_ids,
+ "attention_mask": attention_mask,
+ "ids": ids,
+ "texts": texts,
+ "original_texts": original_texts,
+ }
+
+
+def create_dataloader(dataset, batch_size, distributed_state, tokenizer):
+ """Create dataloader with preprocessing"""
+ processed_dataset = [preprocess_fn(item, tokenizer, max_text_length=200) for item in dataset]
+
+ # Split dataset for distributed processing
+ if distributed_state.num_processes > 1:
+ chunk_size = len(processed_dataset) // distributed_state.num_processes
+ start_idx = distributed_state.process_index * chunk_size
+ end_idx = (
+ start_idx + chunk_size
+ if distributed_state.process_index < distributed_state.num_processes - 1
+ else len(processed_dataset)
+ )
+ processed_dataset = processed_dataset[start_idx:end_idx]
+
+ # Create batches
+ batches = []
+ for i in range(0, len(processed_dataset), batch_size):
+ batch = processed_dataset[i : i + batch_size]
+ batches.append(collate_fn(batch, tokenizer))
+ return batches
+
+
+def save_results(output_queue: queue.Queue, output_dir: pathlib.Path, sampling_rate: int):
+ while True:
+ try:
+ item = output_queue.get(timeout=5)
+ if item is None:
+ break
+ waveforms, ids, texts, original_texts = item
+
+ # Save each audio file and its metadata
+ for waveform, file_id, text, original_text in zip(waveforms, ids, texts, original_texts):
+ # Save audio
+ wav_path = output_dir / f"{file_id}.wav"
+ scipy.io.wavfile.write(wav_path, rate=sampling_rate, data=waveform.cpu().float().numpy())
+
+ # Save metadata with both truncated and original text
+ metadata = {
+ "text_used": text,
+ "original_text": original_text,
+ "model": "facebook/mms-tts-eng",
+ "sampling_rate": sampling_rate,
+ }
+ metadata_path = output_dir / f"{file_id}_metadata.json"
+ with metadata_path.open("w") as f:
+ json.dump(metadata, f, indent=4)
+
+ except queue.Empty:
+ continue
+
+
+def main(
+ output_path: str = "speech_data",
+ batch_size: int = 8,
+ num_workers: int = 2,
+ dataset_split: str = "train",
+ model_name: str = "facebook/mms-tts-eng",
+ max_text_length: int = 200,
+):
+ output_dir = pathlib.Path(output_path)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ distributed_state = PartialState()
+
+ # Load model and tokenizer
+ model = VitsModel.from_pretrained(
+ model_name,
+ device_map=distributed_state.device,
+ torch_dtype=torch.float32,
+ )
+
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+
+ # Load and filter data
+ dataset = load_pokemon_data(dataset_split, max_text_length)
+ exist_filter = ExistsFilter(output_dir)
+ dataset = [item for item in dataset if exist_filter(item)]
+
+ distributed_state.print(f"Processing {len(dataset)} Pokemon descriptions")
+
+ # Create dataloader
+ batches = create_dataloader(dataset, batch_size, distributed_state, tokenizer)
+
+ # Setup output queue and save thread
+ output_queue = queue.Queue()
+ save_thread = ThreadPoolExecutor(max_workers=num_workers)
+ save_future = save_thread.submit(save_results, output_queue, output_dir, model.config.sampling_rate)
+
+ try:
+ for batch in tqdm(batches, desc="Generating Pokemon descriptions"):
+ with torch.no_grad():
+ outputs = model(
+ input_ids=batch["input_ids"].to(distributed_state.device, dtype=torch.long),
+ attention_mask=batch["attention_mask"].to(distributed_state.device, dtype=torch.long),
+ ).waveform
+
+ output_queue.put((outputs, batch["ids"], batch["texts"], batch["original_texts"]))
+ finally:
+ output_queue.put(None)
+ save_thread.shutdown(wait=True)
+
+ save_future.result()
+
+
+if __name__ == "__main__":
+ fire.Fire(main)
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/florence2.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/florence2.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f17ce6bcc140f1accc2777f19d990b554eb5f26
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/florence2.py
@@ -0,0 +1,202 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import pathlib
+import queue
+from concurrent.futures import ThreadPoolExecutor
+from functools import partial
+from typing import Union
+
+import fire
+import torch
+import webdataset as wds
+from huggingface_hub.utils import insecure_hashlib
+from PIL import Image
+from tqdm import tqdm
+from transformers import AutoModelForCausalLM, AutoProcessor
+
+from accelerate import PartialState
+
+
+"""
+Additional requirements: flash_attn einops timm webdataset fire tqdm huggingface_hub
+pip install flash_attn einops timm webdataset fire tqdm huggingface_hub
+
+Example:
+
+accelerate launch --num_processes=2 florence2.py --data_path "https://huggingface.co/datasets/pixparse/cc3m-wds/resolve/main/cc3m-train-0000.tar" --output_path outputs --batch_size 12 --num_workers 1 --prompt "
"
+"""
+
+
+def main(
+ data_path: str,
+ output_path: str,
+ batch_size: int,
+ num_workers: int,
+ prompt: str = "",
+ model_name: str = "microsoft/Florence-2-large",
+ max_new_tokens: int = 1024,
+ num_beams: int = 3,
+):
+ output_dir = pathlib.Path(output_path)
+
+ distributed_state = PartialState()
+
+ if distributed_state.is_main_process:
+ output_dir.mkdir(exist_ok=True)
+
+ model = AutoModelForCausalLM.from_pretrained(
+ model_name,
+ device_map=distributed_state.device,
+ torch_dtype=torch.float16,
+ trust_remote_code=True,
+ )
+
+ processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True, clean_up_tokenization_spaces=True)
+
+ class ExistsFilter:
+ def __init__(self, output_dir: Union[pathlib.Path, str]):
+ current_training_img_hashes = [f.split(".jpg")[0] for f in os.listdir(output_dir) if f.endswith(".jpg")]
+ self.current_training_img_hashes = set(current_training_img_hashes)
+ if distributed_state.is_main_process:
+ print(f"Existing images found: {len(self.current_training_img_hashes)}.")
+
+ def __call__(self, x):
+ if len(self.current_training_img_hashes) > 0:
+ if x["img_hash"] in self.current_training_img_hashes:
+ return False
+ else:
+ return True
+ else:
+ return True
+
+ def preprocess_fn(sample, processor):
+ image: Image.Image = sample["jpg"].convert("RGB")
+ img_hash = insecure_hashlib.sha1(image.tobytes()).hexdigest()
+ inputs = processor(
+ text=prompt,
+ images=image,
+ return_tensors="pt",
+ )
+ return {
+ "input_ids": inputs["input_ids"],
+ "pixel_values": inputs["pixel_values"],
+ "image": image,
+ "img_hash": img_hash,
+ "original_caption": sample["txt"],
+ }
+
+ def collate_fn(examples):
+ input_ids = torch.cat([example["input_ids"] for example in examples])
+ pixel_values = torch.cat([example["pixel_values"] for example in examples])
+ images = [example["image"] for example in examples]
+ img_hashes = [example["img_hash"] for example in examples]
+ captions = [example["original_caption"] for example in examples]
+ return {
+ "input_ids": input_ids,
+ "pixel_values": pixel_values,
+ "images": images,
+ "img_hashes": img_hashes,
+ "original_captions": captions,
+ }
+
+ exist_filter = ExistsFilter(output_dir)
+ dataset = (
+ wds.WebDataset(
+ data_path,
+ handler=wds.warn_and_continue,
+ nodesplitter=None,
+ shardshuffle=False,
+ empty_check=False,
+ )
+ .decode("pil", handler=wds.warn_and_continue)
+ .map(partial(preprocess_fn, processor=processor), handler=wds.warn_and_continue)
+ )
+ if len(exist_filter.current_training_img_hashes) > 0:
+ dataset = dataset.select(exist_filter)
+ dataset = dataset.batched(
+ batch_size,
+ partial=False,
+ collation_fn=collate_fn,
+ )
+ dataloader = wds.WebLoader(
+ dataset,
+ batch_size=None,
+ num_workers=num_workers,
+ pin_memory=True,
+ persistent_workers=True,
+ )
+
+ def save_results(output_queue: queue.Queue, output_dir: pathlib.Path, processor):
+ while True:
+ try:
+ item = output_queue.get(timeout=5)
+ if item is None:
+ break
+ original_captions, predictions, images, img_hashes = item
+ predicted_captions = processor.batch_decode(
+ predictions,
+ skip_special_tokens=False,
+ )
+ for caption, pred_caption, image, img_hash in zip(
+ original_captions, predicted_captions, images, img_hashes
+ ):
+ processed_caption = processor.post_process_generation(
+ pred_caption, task=prompt, image_size=(image.width, image.height)
+ )[prompt]
+ img_path = output_dir.joinpath(f"{img_hash}.jpg")
+ image.save(img_path)
+
+ caption_dict = {"original": caption, "predicted": processed_caption}
+ with output_dir.joinpath(f"{img_hash}_caption.json").open("w") as f:
+ json.dump(caption_dict, f, indent=4)
+
+ except queue.Empty:
+ continue
+
+ output_queue = queue.Queue()
+ save_thread = ThreadPoolExecutor(max_workers=num_workers)
+ save_future = save_thread.submit(save_results, output_queue, output_dir, processor)
+
+ try:
+ for _, batch_raw in tqdm(
+ enumerate(dataloader),
+ disable=not distributed_state.is_main_process,
+ ):
+ with distributed_state.split_between_processes(batch_raw) as batch:
+ outputs = model.generate(
+ input_ids=batch["input_ids"].to(distributed_state.device),
+ pixel_values=batch["pixel_values"].to(distributed_state.device, model.dtype),
+ max_new_tokens=max_new_tokens,
+ num_beams=num_beams,
+ )
+ output_queue.put(
+ (
+ batch["original_captions"],
+ outputs,
+ batch["images"],
+ batch["img_hashes"],
+ )
+ )
+ finally:
+ output_queue.put(None)
+ save_thread.shutdown(wait=True)
+
+ save_future.result()
+
+
+if __name__ == "__main__":
+ fire.Fire(main)
diff --git a/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/llava_next_video.py b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/llava_next_video.py
new file mode 100644
index 0000000000000000000000000000000000000000..10044293ee0801e8b5201eb6e86a8efbb3a3f77e
--- /dev/null
+++ b/tasks/tasksmith-c98f3a4a299d/tests/source/examples/inference/distributed/llava_next_video.py
@@ -0,0 +1,192 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import os
+import pathlib
+import queue
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+import av
+import fire
+import numpy as np
+import torch
+from huggingface_hub import snapshot_download
+from tqdm import tqdm
+from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor
+
+from accelerate import PartialState
+
+
+START_TIME = time.strftime("%Y%m%d_%H%M%S")
+DTYPE_MAP = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16}
+
+
+"""
+Example:
+
+accelerate launch llava_next_video.py
+"""
+
+
+def save_results(output_queue: queue.Queue, output_dir: pathlib.Path):
+ count = 0
+ while True:
+ try:
+ item = output_queue.get(timeout=5)
+ if item is None:
+ break
+ prompt, video, generated_text = item
+ example_file = f"example_{count}"
+ temp_dir = os.path.join(output_dir, example_file)
+
+ metadata = {"prompt": prompt, "video": video, "generated_text": generated_text}
+ with open(temp_dir, "w") as f:
+ json.dump(metadata, f, indent=4)
+ count += 1
+
+ except queue.Empty:
+ continue
+
+
+def get_batches(processed_videos, batch_size):
+ num_batches = (len(processed_videos) + batch_size - 1) // batch_size
+ batches = []
+
+ for i in range(num_batches):
+ start_index = i * batch_size
+ end_index = min((i + 1) * batch_size, len(processed_videos))
+ batch = processed_videos[start_index:end_index]
+ batches.append(batch)
+
+ return batches
+
+
+def read_video_pyav(container, indices):
+ """
+ Decode the video with PyAV decoder.
+ Args:
+ container (`av.container.input.InputContainer`): PyAV container.
+ indices (`List[int]`): List of frame indices to decode.
+ Returns:
+ result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
+ """
+ frames = []
+ container.seek(0)
+ start_index = indices[0]
+ end_index = indices[-1]
+ for i, frame in enumerate(container.decode(video=0)):
+ if i > end_index:
+ break
+ if i >= start_index and i in indices:
+ frames.append(frame)
+ return np.stack([x.to_ndarray(format="rgb24") for x in frames])
+
+
+def get_video_paths(video_dir):
+ """Get paths to all video files in the directory and its subdirectories."""
+ video_extensions = (".mp4", ".avi", ".mov", ".mkv") # Add more extensions if needed
+ video_paths = []
+
+ for root, _, files in os.walk(video_dir):
+ for file in files:
+ if file.lower().endswith(video_extensions):
+ video_paths.append(os.path.join(root, file))
+
+ return video_paths
+
+
+def process_videos(video_paths, processor, prompt, frames_per_video):
+ """Process a batch of videos and prepare them for the model."""
+ batch_inputs = []
+
+ for video_path in video_paths:
+ try:
+ with av.open(video_path) as container:
+ total_frames = container.streams.video[0].frames
+ indices = np.arange(0, total_frames, total_frames / frames_per_video).astype(int)
+ clip = read_video_pyav(container, indices)
+
+ processed = processor(text=prompt, videos=clip, return_tensors="pt")
+ batch_inputs.append(
+ {
+ "input_ids": processed["input_ids"],
+ "pixel_values_videos": processed["pixel_values_videos"],
+ "video": video_path,
+ }
+ )
+
+ except Exception as e:
+ print(f"Error processing video {video_path}: {str(e)}")
+ continue
+
+ return batch_inputs
+
+
+def main(
+ model_name: str = "llava-hf/LLaVA-NeXT-Video-7B-hf",
+ save_dir: str = "./evaluation/examples",
+ prompt: str = "USER: