


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


a_      			=				16
a_      			=				32





def __snake_case      (   UpperCAmelCase_		:		Tuple      ,       UpperCAmelCase_		:		Dict = 16	):
 lowerCamelCase_  				=						AutoTokenizer.from_pretrained("bert-base-cased"	)
 lowerCamelCase_  				=						load_dataset("glue"      ,       "mrpc"	)

 def tokenize_function(UpperCAmelCase_		:		Optional[Any]	):
  # max_length=None => use the model max length (it's actually the default)
  lowerCamelCase_  				=						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():
  lowerCamelCase_  				=						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
 lowerCamelCase_  				=						tokenized_datasets.rename_column("label"      ,       "labels"	)

 def collate_fn(UpperCAmelCase_		:		Tuple	):
  # On TPU it's best to pad everything to the same length or training will be very slow.
  lowerCamelCase_  				=						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":
   lowerCamelCase_  				=						16
  elif accelerator.mixed_precision != "no":
   lowerCamelCase_  				=						8
  else:
   lowerCamelCase_  				=						None

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

 # Instantiate dataloaders.
 lowerCamelCase_  				=						DataLoader(
     tokenized_datasets["train"]      ,       shuffle=__snake_case      ,       collate_fn=__snake_case      ,       batch_size=__snake_case	)
 lowerCamelCase_  				=						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

     a_      			=				mocked_dataloaders  # noqa: F811





def __snake_case      (   UpperCAmelCase_		:		Dict      ,       UpperCAmelCase_		:		Optional[Any]	):
 # For testing only
 if os.environ.get("TESTING_MOCKED_DATALOADERS"      ,       __snake_case	) == "1":
  lowerCamelCase_  				=						2
 # Initialize accelerator
 lowerCamelCase_  				=						Accelerator(cpu=args.cpu      ,       mixed_precision=args.mixed_precision	)
 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
 lowerCamelCase_  				=						config["lr"]
 lowerCamelCase_  				=						int(config["num_epochs"]	)
 lowerCamelCase_  				=						int(config["seed"]	)
 lowerCamelCase_  				=						int(config["batch_size"]	)

 lowerCamelCase_  				=						evaluate.load("glue"      ,       "mrpc"	)

 # If the batch size is too big we use gradient accumulation
 lowerCamelCase_  				=						1
 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
  lowerCamelCase_  				=						batch_size // MAX_GPU_BATCH_SIZE
  lowerCamelCase_  				=						MAX_GPU_BATCH_SIZE

 set_seed(__snake_case	)
 lowerCamelCase_				,lowerCamelCase_  				=						get_dataloaders(__snake_case      ,       __snake_case	)
 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
 lowerCamelCase_  				=						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).
 lowerCamelCase_  				=						model.to(accelerator.device	)

 # Instantiate optimizer
 lowerCamelCase_  				=						AdamW(params=model.parameters()      ,       lr=__snake_case	)

 # Instantiate scheduler
 lowerCamelCase_  				=						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.
 lowerCamelCase_				,lowerCamelCase_				,lowerCamelCase_				,lowerCamelCase_				,lowerCamelCase_  				=						accelerator.prepare(
     __snake_case      ,       __snake_case      ,       __snake_case      ,       __snake_case      ,       __snake_case	)

 # Now we train the model
 for epoch in range(__snake_case	):
  model.train()
  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	)
   lowerCamelCase_  				=						model(**__snake_case	)
   lowerCamelCase_  				=						outputs.loss
   lowerCamelCase_  				=						loss / gradient_accumulation_steps
   accelerator.backward(__snake_case	)
   if step % gradient_accumulation_steps == 0:
    optimizer.step()
    lr_scheduler.step()
    optimizer.zero_grad()

  model.eval()
  lowerCamelCase_  				=						0
  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	)
   with torch.no_grad():
    lowerCamelCase_  				=						model(**__snake_case	)
   lowerCamelCase_  				=						outputs.logits.argmax(dim=-1	)
   lowerCamelCase_				,lowerCamelCase_  				=						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(__snake_case	) - 1:
     # Last batch needs to be truncated on distributed systems as it contains additional samples
     lowerCamelCase_  				=						predictions[: len(eval_dataloader.dataset	) - samples_seen]
     lowerCamelCase_  				=						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=__snake_case      ,       references=__snake_case      ,       )

  lowerCamelCase_  				=						metric.compute()
  # Use accelerator.print to print only on the main process.
  accelerator.print(F'''epoch {epoch}:'''      ,       __snake_case	)





def __snake_case      (   ):
 lowerCamelCase_  				=						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."	)
 lowerCamelCase_  				=						parser.parse_args()
 lowerCamelCase_  				=						{"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 tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
     import tensorflow as tf

     from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments





@require_tf
class   snake_case					(					unittest.TestCase    ):





  """simple docstring"""




  def 						snake_case	(					self    ,						UpperCamelCase  ):







   """simple docstring"""
   for model_result in results.values():
    for batch_size, sequence_length in zip(model_result["bs"]    ,						model_result["ss"]  ):
     lowerCamelCase_  				=						model_result["result"][batch_size][sequence_length]
     self.assertIsNotNone(UpperCamelCase  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						eager_mode=UpperCamelCase    ,						multi_process=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_inference_result  )
   self.check_results_dict_not_empty(results.memory_inference_result  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sgugger/tiny-distilbert-classification"
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						multi_process=UpperCamelCase    ,						only_pretrain_model=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_inference_result  )
   self.check_results_dict_not_empty(results.memory_inference_result  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						multi_process=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_inference_result  )
   self.check_results_dict_not_empty(results.memory_inference_result  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"
   lowerCamelCase_  				=						AutoConfig.from_pretrained(UpperCamelCase  )
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						eager_mode=UpperCamelCase    ,						multi_process=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase    ,						[config]  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_inference_result  )
   self.check_results_dict_not_empty(results.memory_inference_result  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"
   lowerCamelCase_  				=						AutoConfig.from_pretrained(UpperCamelCase  )
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						multi_process=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase    ,						[config]  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_inference_result  )
   self.check_results_dict_not_empty(results.memory_inference_result  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						multi_process=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_train_result  )
   self.check_results_dict_not_empty(results.memory_train_result  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"
   lowerCamelCase_  				=						AutoConfig.from_pretrained(UpperCamelCase  )
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						multi_process=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase    ,						[config]  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_train_result  )
   self.check_results_dict_not_empty(results.memory_train_result  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"patrickvonplaten/t5-tiny-random"
   lowerCamelCase_  				=						AutoConfig.from_pretrained(UpperCamelCase  )
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						multi_process=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase    ,						configs=[config]  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_inference_result  )
   self.check_results_dict_not_empty(results.memory_inference_result  )






  @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("GPU"  )  ) == 0    ,						"Cannot do xla on CPU."  )
  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"
   lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
       models=[MODEL_ID]    ,						training=UpperCamelCase    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						use_xla=UpperCamelCase    ,						multi_process=UpperCamelCase    ,						)
   lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase  )
   lowerCamelCase_  				=						benchmark.run()
   self.check_results_dict_not_empty(results.time_inference_result  )
   self.check_results_dict_not_empty(results.memory_inference_result  )






  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"
   with tempfile.TemporaryDirectory() as tmp_dir:
    lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
        models=[MODEL_ID]    ,						inference=UpperCamelCase    ,						save_to_csv=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						inference_time_csv_file=os.path.join(UpperCamelCase    ,						"inf_time.csv"  )    ,						inference_memory_csv_file=os.path.join(UpperCamelCase    ,						"inf_mem.csv"  )    ,						env_info_csv_file=os.path.join(UpperCamelCase    ,						"env.csv"  )    ,						multi_process=UpperCamelCase    ,						)
    lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase  )
    benchmark.run()
    self.assertTrue(Path(os.path.join(UpperCamelCase    ,						"inf_time.csv"  )  ).exists()  )
    self.assertTrue(Path(os.path.join(UpperCamelCase    ,						"inf_mem.csv"  )  ).exists()  )
    self.assertTrue(Path(os.path.join(UpperCamelCase    ,						"env.csv"  )  ).exists()  )







  def 						snake_case	(					self  ):







   """simple docstring"""
   lowerCamelCase_  				=						"sshleifer/tiny-gpt2"

   def _check_summary_is_not_empty(UpperCamelCase  ):
    self.assertTrue(hasattr(UpperCamelCase    ,						"sequential"  )  )
    self.assertTrue(hasattr(UpperCamelCase    ,						"cumulative"  )  )
    self.assertTrue(hasattr(UpperCamelCase    ,						"current"  )  )
    self.assertTrue(hasattr(UpperCamelCase    ,						"total"  )  )

   with tempfile.TemporaryDirectory() as tmp_dir:
    lowerCamelCase_  				=						TensorFlowBenchmarkArguments(
        models=[MODEL_ID]    ,						inference=UpperCamelCase    ,						sequence_lengths=[8]    ,						batch_sizes=[1]    ,						log_filename=os.path.join(UpperCamelCase    ,						"log.txt"  )    ,						log_print=UpperCamelCase    ,						trace_memory_line_by_line=UpperCamelCase    ,						eager_mode=UpperCamelCase    ,						multi_process=UpperCamelCase    ,						)
    lowerCamelCase_  				=						TensorFlowBenchmark(UpperCamelCase  )
    lowerCamelCase_  				=						benchmark.run()
    _check_summary_is_not_empty(result.inference_summary  )
    self.assertTrue(Path(os.path.join(UpperCamelCase    ,						"log.txt"  )  ).exists()  )



