




'''simple docstring'''






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 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
#
########################################################################

_lowerCAmelCase       =   16
_lowerCAmelCase       =   32

def      __lowerCAmelCase   (       snake_case__   , snake_case__ = 16		):
			__UpperCamelCase :     Any										=  AutoTokenizer.from_pretrained("bert-base-cased"		)
			__UpperCamelCase :     Tuple										=  load_dataset("glue"   , "mrpc"		)

			def tokenize_function(snake_case__		):
						# max_length=None => use the model max length (it's actually the default)
						__UpperCamelCase :     Optional[int]										=  tokenizer(examples["sentence1"]   , examples["sentence2"]   , truncation=snake_case__   , max_length=snake_case__		)
						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():
						__UpperCamelCase :     Any										=  datasets.map(
						    snake_case__   , batched=snake_case__   , 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
			__UpperCamelCase :     str										=  tokenized_datasets.rename_column("label"   , "labels"		)

			def collate_fn(snake_case__		):
						# On TPU it's best to pad everything to the same length or training will be very slow.
						__UpperCamelCase :     Dict										=  128 if accelerator.distributed_type == DistributedType.TPU else None
						# When using mixed precision we want round multiples of 8/16
						if accelerator.mixed_precision == "fp8":
									__UpperCamelCase :     Optional[Any]										=  16
						elif accelerator.mixed_precision != "no":
									__UpperCamelCase :     int										=  8
						else:
									__UpperCamelCase :     Dict										=  None

						return tokenizer.pad(
						    snake_case__   , padding="longest"   , max_length=snake_case__   , pad_to_multiple_of=snake_case__   , return_tensors="pt"   , )

			# Instantiate dataloaders.
			__UpperCamelCase :     List[Any]										=  DataLoader(
			    tokenized_datasets["train"]   , shuffle=snake_case__   , collate_fn=snake_case__   , batch_size=snake_case__		)
			__UpperCamelCase :     List[Any]										=  DataLoader(
			    tokenized_datasets["validation"]   , shuffle=snake_case__   , collate_fn=snake_case__   , batch_size=snake_case__		)

			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

				_lowerCAmelCase       =   mocked_dataloaders  # noqa: F811

def      __lowerCAmelCase   (       snake_case__   , snake_case__		):
			# For testing only
			if os.environ.get("TESTING_MOCKED_DATALOADERS"   , snake_case__		) == "1":
						__UpperCamelCase :     List[str]										=  2
			# Initialize accelerator
			__UpperCamelCase :     Tuple										=  Accelerator(cpu=args.cpu   , mixed_precision=args.mixed_precision		)
			# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
			__UpperCamelCase :     List[str]										=  config["lr"]
			__UpperCamelCase :     Union[str, Any]										=  int(config["num_epochs"]		)
			__UpperCamelCase :     Any										=  int(config["seed"]		)
			__UpperCamelCase :     List[Any]										=  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":
									__UpperCamelCase :     Dict										=  args.checkpointing_steps
						elif args.checkpointing_steps.isdigit():
									__UpperCamelCase :     Dict										=  int(args.checkpointing_steps		)
						else:
									raise ValueError(
									    F"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."		)
			else:
						__UpperCamelCase :     List[str]										=  None

			set_seed(snake_case__		)

			__UpperCamelCase						,   __UpperCamelCase :     List[Any]										=  get_dataloaders(snake_case__   , snake_case__		)
			__UpperCamelCase :     Optional[Any]										=  evaluate.load("glue"   , "mrpc"		)

			# If the batch size is too big we use gradient accumulation
			__UpperCamelCase :     Dict										=  1
			if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
						__UpperCamelCase :     List[Any]										=  batch_size // MAX_GPU_BATCH_SIZE
						__UpperCamelCase :     Tuple										=  MAX_GPU_BATCH_SIZE

			# Instantiate the model (we build the model here so that the seed also control new weights initialization)
			__UpperCamelCase :     str										=  AutoModelForSequenceClassification.from_pretrained("bert-base-cased"   , return_dict=snake_case__		)

			# 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).
			__UpperCamelCase :     Optional[Any]										=  model.to(accelerator.device		)

			# Instantiate optimizer
			__UpperCamelCase :     str										=  AdamW(params=model.parameters()   , lr=snake_case__		)

			# Instantiate scheduler
			__UpperCamelCase :     Optional[int]										=  get_linear_schedule_with_warmup(
			    optimizer=snake_case__   , num_warmup_steps=100   , num_training_steps=(len(snake_case__		) * 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.
			__UpperCamelCase						,   __UpperCamelCase						,   __UpperCamelCase						,   __UpperCamelCase						,   __UpperCamelCase :     List[str]										=  accelerator.prepare(
			    snake_case__   , snake_case__   , snake_case__   , snake_case__   , snake_case__		)

			# New Code #
			# We need to keep track of how many total steps we have iterated over
			__UpperCamelCase :     Union[str, Any]										=  0
			# We also need to keep track of the stating epoch so files are named properly
			__UpperCamelCase :     List[Any]										=  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		)
									__UpperCamelCase :     Any										=  os.path.basename(args.resume_from_checkpoint		)
						else:
									# Get the most recent checkpoint
									__UpperCamelCase :     Any										=  [f.name for f in os.scandir(os.getcwd()		) if f.is_dir()]
									dirs.sort(key=os.path.getctime		)
									__UpperCamelCase :     Tuple										=  dirs[-1]  # Sorts folders by date modified, most recent checkpoint is the last
						# Extract `epoch_{i}` or `step_{i}`
						__UpperCamelCase :     List[str]										=  os.path.splitext(snake_case__		)[0]

						if "epoch" in training_difference:
									__UpperCamelCase :     List[str]										=  int(training_difference.replace("epoch_"   , ""		)		) + 1
									__UpperCamelCase :     Dict										=  None
						else:
									__UpperCamelCase :     Optional[Any]										=  int(training_difference.replace("step_"   , ""		)		)
									__UpperCamelCase :     Union[str, Any]										=  resume_step // len(snake_case__		)
									resume_step -= starting_epoch * len(snake_case__		)

    # Now we train the model
			for epoch in range(snake_case__   , snake_case__		):
						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
									__UpperCamelCase :     str										=  accelerator.skip_first_batches(snake_case__   , snake_case__		)
									overall_step += resume_step
						else:
									# After the first iteration though, we need to go back to the original dataloader
									__UpperCamelCase :     Tuple										=  train_dataloader
						for step, batch in enumerate(snake_case__		):
									# We could avoid this line since we set the accelerator with `device_placement=True`.
									batch.to(accelerator.device		)
									__UpperCamelCase :     int										=  model(**snake_case__		)
									__UpperCamelCase :     str										=  outputs.loss
									__UpperCamelCase :     Union[str, Any]										=  loss / gradient_accumulation_steps
									accelerator.backward(snake_case__		)
									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(snake_case__   , snake_case__		):
												__UpperCamelCase :     Any										=  F"step_{overall_step}"
												if overall_step % checkpointing_steps == 0:
															if args.output_dir is not None:
																		__UpperCamelCase :     str										=  os.path.join(args.output_dir   , snake_case__		)
															accelerator.save_state(snake_case__		)

						model.eval()
						for step, batch in enumerate(snake_case__		):
									# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
									batch.to(accelerator.device		)
									with torch.no_grad():
												__UpperCamelCase :     Optional[Any]										=  model(**snake_case__		)
									__UpperCamelCase :     Optional[int]										=  outputs.logits.argmax(dim=-1		)
									__UpperCamelCase						,   __UpperCamelCase :     List[Any]										=  accelerator.gather_for_metrics((predictions, batch["labels"])		)
									metric.add_batch(
									    predictions=snake_case__   , references=snake_case__   , )

						__UpperCamelCase :     Union[str, Any]										=  metric.compute()
						# Use accelerator.print to print only on the main process.
						accelerator.print(F"epoch {epoch}:"   , snake_case__		)

						# 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":
									__UpperCamelCase :     List[str]										=  F"epoch_{epoch}"
									if args.output_dir is not None:
												__UpperCamelCase :     Optional[Any]										=  os.path.join(args.output_dir   , snake_case__		)
									accelerator.save_state(snake_case__		)

def      __lowerCAmelCase   (       ):
			__UpperCamelCase :     Optional[int]										=  argparse.ArgumentParser(description="Simple example of training script."		)
			parser.add_argument(
			    "--mixed_precision"   , type=snake_case__   , default=snake_case__   , 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=snake_case__   , default=snake_case__   , 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=snake_case__   , 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=snake_case__   , default=snake_case__   , help="If the training should continue from a checkpoint folder."   , )
			__UpperCamelCase :     Tuple										=  parser.parse_args()
			__UpperCamelCase :     str										=  {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
			training_function(snake_case__   , snake_case__		)


if __name__ == "__main__":
				main()









'''simple docstring'''






import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


_lowerCAmelCase       =   namedtuple('''ExampleNamedTuple''', '''a b c''')



class    A						(					unittest.TestCase						):




				'''simple docstring'''





				def 			a_			(self     )      ->			Tuple:
							__UpperCamelCase :     Optional[int]										=  torch.randn(5					,    2     )
							__UpperCamelCase :     List[str]										=  torch.device("cuda"     ) if torch.cuda.is_available() else torch.device("cpu"     )

							__UpperCamelCase :     Optional[Any]										=  send_to_device(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta.cpu()					,    _UpperCAmelCase     )     )

							__UpperCamelCase :     Any										=  send_to_device((tensor, [tensor, tensor], 1)					,    _UpperCAmelCase     )
							self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta[0].cpu()					,    _UpperCAmelCase     )     )
							self.assertIsInstance(resulta[1]					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta[1][0].cpu()					,    _UpperCAmelCase     )     )
							self.assertTrue(torch.equal(resulta[1][1].cpu()					,    _UpperCAmelCase     )     )
							self.assertEqual(resulta[2]					,    1     )

							__UpperCamelCase :     Optional[int]										=  send_to_device({"a": tensor, "b": [tensor, tensor], "c": 1}					,    _UpperCAmelCase     )
							self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta["a"].cpu()					,    _UpperCAmelCase     )     )
							self.assertIsInstance(resulta["b"]					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta["b"][0].cpu()					,    _UpperCAmelCase     )     )
							self.assertTrue(torch.equal(resulta["b"][1].cpu()					,    _UpperCAmelCase     )     )
							self.assertEqual(resulta["c"]					,    1     )

							__UpperCamelCase :     Optional[Any]										=  send_to_device(ExampleNamedTuple(a=_UpperCAmelCase					,    b=[tensor, tensor]					,    c=1     )					,    _UpperCAmelCase     )
							self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta.a.cpu()					,    _UpperCAmelCase     )     )
							self.assertIsInstance(resulta.b					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta.b[0].cpu()					,    _UpperCAmelCase     )     )
							self.assertTrue(torch.equal(resulta.b[1].cpu()					,    _UpperCAmelCase     )     )
							self.assertEqual(resulta.c					,    1     )

							__UpperCamelCase :     Dict										=  send_to_device(UserDict({"a": tensor, "b": [tensor, tensor], "c": 1}     )					,    _UpperCAmelCase     )
							self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta["a"].cpu()					,    _UpperCAmelCase     )     )
							self.assertIsInstance(resulta["b"]					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta["b"][0].cpu()					,    _UpperCAmelCase     )     )
							self.assertTrue(torch.equal(resulta["b"][1].cpu()					,    _UpperCAmelCase     )     )
							self.assertEqual(resulta["c"]					,    1     )
				def 			a_			(self     )      ->			Optional[Any]:
							with self.assertRaises(_UpperCAmelCase     ) as cm:
										__UpperCamelCase :     int										=  recursively_apply(torch.tensor					,    (torch.tensor(1     ), 1)					,    error_on_other_type=_UpperCAmelCase     )
							self.assertEqual(
							    str(cm.exception     )					,    "Unsupported types (<class 'int'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed."					,    )
				def 			a_			(self     )      ->			Union[str, Any]:
							__UpperCamelCase :     Dict										=  torch.tensor([1, 2, 3, 4, 5]     )
							self.assertEqual(listify(_UpperCAmelCase     )					,    [1, 2, 3, 4, 5]     )

							__UpperCamelCase :     int										=  torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]]     )
							self.assertEqual(listify(_UpperCAmelCase     )					,    [[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]]     )

							__UpperCamelCase :     Dict										=  torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]], [[1_1, 1_2, 1_3, 1_4, 1_5], [1_6, 1_7, 1_8, 1_9, 2_0]]]     )
							self.assertEqual(
							    listify(_UpperCAmelCase     )					,    [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]], [[1_1, 1_2, 1_3, 1_4, 1_5], [1_6, 1_7, 1_8, 1_9, 2_0]]]     )
				def 			a_			(self     )      ->			Optional[Any]:
							with patch_environment(aa=1					,    BB=2     ):
										self.assertEqual(os.environ.get("AA"     )					,    "1"     )
										self.assertEqual(os.environ.get("BB"     )					,    "2"     )

							self.assertNotIn("AA"					,    os.environ     )
							self.assertNotIn("BB"					,    os.environ     )
				def 			a_			(self     )      ->			Dict:
							__UpperCamelCase :     Tuple										=  RegressionModel()
							__UpperCamelCase :     List[str]										=  model.forward
							__UpperCamelCase :     Any										=  convert_outputs_to_fpaa(model.forward     )
							__UpperCamelCase :     List[str]										=  extract_model_from_parallel(_UpperCAmelCase					,    keep_fpaa_wrapper=_UpperCAmelCase     )
							__UpperCamelCase :     Dict										=  pickle.dumps(_UpperCAmelCase     )
				@require_cuda
				def 			a_			(self     )      ->			str:
							__UpperCamelCase :     List[str]										=  RegressionModel()
							__UpperCamelCase :     List[Any]										=  model.forward
							__UpperCamelCase :     List[str]										=  torch.cuda.amp.autocast(dtype=torch.floataa     )(model.forward     )
							__UpperCamelCase :     str										=  convert_outputs_to_fpaa(model.forward     )
							__UpperCamelCase :     int										=  extract_model_from_parallel(_UpperCAmelCase					,    keep_fpaa_wrapper=_UpperCAmelCase     )
							__UpperCamelCase :     int										=  pickle.dumps(_UpperCAmelCase     )
				@require_cuda
				@require_torch_min_version(version="2.0"     )
				def 			a_			(self     )      ->			Tuple:
							__UpperCamelCase :     List[Any]										=  RegressionModel()
							__UpperCamelCase :     Tuple										=  model.forward
							__UpperCamelCase :     Optional[int]										=  torch.cuda.amp.autocast(dtype=torch.floataa     )(model.forward     )
							__UpperCamelCase :     List[Any]										=  convert_outputs_to_fpaa(model.forward     )
							__UpperCamelCase :     Union[str, Any]										=  torch.compile(model.forward					,    backend="inductor"     )
							__UpperCamelCase :     int										=  torch.randn(4					,    1_0     ).cuda()
							__UpperCamelCase :     int										=  model(_UpperCAmelCase     )
				def 			a_			(self     )      ->			Union[str, Any]:
							__UpperCamelCase :     List[Any]										=  RegressionModel()
							# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
							__UpperCamelCase :     Optional[Any]										=  torch.nn.parallel.DataParallel(_UpperCAmelCase     )
							__UpperCamelCase :     Union[str, Any]										=  extract_model_from_parallel(_UpperCAmelCase     )

							self.assertEqual(_UpperCAmelCase					,    _UpperCAmelCase     )
				@require_torch_min_version(version="2.0"     )
				def 			a_			(self     )      ->			Union[str, Any]:
							__UpperCamelCase :     int										=  RegressionModel()
							__UpperCamelCase :     List[str]										=  torch.compile(_UpperCAmelCase     )

							# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
							__UpperCamelCase :     Union[str, Any]										=  torch.nn.parallel.DataParallel(_UpperCAmelCase     )
							__UpperCamelCase :     List[str]										=  torch.compile(_UpperCAmelCase     )
							__UpperCamelCase :     Optional[int]										=  extract_model_from_parallel(_UpperCAmelCase     )

							self.assertEqual(compiled_model._orig_mod					,    compiled_model_unwrapped._orig_mod     )





				def 			a_			(self     )      ->			str:
							self.assertEqual(find_device([1, "a", torch.tensor([1, 2, 3]     )]     )					,    torch.device("cpu"     )     )
							self.assertEqual(find_device({"a": 1, "b": torch.tensor([1, 2, 3]     )}     )					,    torch.device("cpu"     )     )
							self.assertIsNone(find_device([1, "a"]     )     )



