

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

_UpperCamelCase     =    32
def 		UpperCamelCase_(    snake_case__:						Accelerator						,					snake_case__:						int = 16     ) ->				Any:
 UpperCAmelCase__           =       AutoTokenizer.from_pretrained('bert-base-cased'     )
 UpperCAmelCase__           =       load_dataset('glue'						,					'mrpc'     )

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

 def collate_fn(snake_case__:						List[Any]     ):
  # When using mixed precision we want round multiples of 8/16
  if accelerator.mixed_precision == "fp8":
   UpperCAmelCase__           =       16
  elif accelerator.mixed_precision != "no":
   UpperCAmelCase__           =       8
  else:
   UpperCAmelCase__           =       None

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

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

 _UpperCamelCase     =    mocked_dataloaders  # noqa: F811
def 		UpperCamelCase_(    snake_case__:						List[Any]						,					snake_case__:						Tuple     ) ->				Any:
 # For testing only
 if os.environ.get('TESTING_MOCKED_DATALOADERS'						,					snake_case__     ) == "1":
  UpperCAmelCase__           =       2
 # Initialize accelerator
 UpperCAmelCase__           =       Accelerator(cpu=args.cpu						,					mixed_precision=args.mixed_precision     )
 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
 UpperCAmelCase__           =       config['lr']
 UpperCAmelCase__           =       int(config['num_epochs']     )
 UpperCAmelCase__           =       int(config['seed']     )
 UpperCAmelCase__           =       int(config['batch_size']     )

 UpperCAmelCase__           =       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(snake_case__     )     )
 def inner_training_loop(snake_case__:						List[Any]     ):
  # 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
  UpperCAmelCase__           =       observed_batch_size // batch_size

  # And then set it in the Accelerator directly:
  UpperCAmelCase__           =       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(snake_case__     )

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

  # Instantiate optimizer
  UpperCAmelCase__           =       AdamW(params=model.parameters()						,					lr=snake_case__     )
  UpperCAmelCase__       ,					UpperCAmelCase__           =       get_dataloaders(snake_case__						,					snake_case__     )

  # Instantiate scheduler
  UpperCAmelCase__           =       get_linear_schedule_with_warmup(
      optimizer=snake_case__						,					num_warmup_steps=1_00						,					num_training_steps=(len(snake_case__     ) * 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.
  UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__           =       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__     ):
    # And perform gradient accumulation
    with accelerator.accumulate(snake_case__     ):
     # We could avoid this line since we set the accelerator with `device_placement=True`.
     batch.to(accelerator.device     )
     UpperCAmelCase__           =       model(**snake_case__     )
     UpperCAmelCase__           =       outputs.loss
     accelerator.backward(snake_case__     )
     optimizer.step()
     lr_scheduler.step()
     optimizer.zero_grad()

   model.eval()
   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():
     UpperCAmelCase__           =       model(**snake_case__     )
    UpperCAmelCase__           =       outputs.logits.argmax(dim=-1     )
    UpperCAmelCase__       ,					UpperCAmelCase__           =       accelerator.gather_for_metrics((predictions, batch['labels'])     )
    metric.add_batch(
        predictions=snake_case__						,					references=snake_case__						,					)

   UpperCAmelCase__           =       metric.compute()
   # Use accelerator.print to print only on the main process.
   accelerator.print(f"epoch {epoch}:"						,					snake_case__     )

    # 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()
def 		UpperCamelCase_(    ) ->				Tuple:
 UpperCAmelCase__           =       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.'     )
 UpperCAmelCase__           =       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
 UpperCAmelCase__           =       {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 2_56}
 training_function(snake_case__						,					snake_case__     )


if __name__ == "__main__":
 main()






import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import transformers
from transformers import (
    AutoConfig,
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    DataCollatorWithPadding,
    HfArgumentParser,
    SquadDataset,
    Trainer,
    TrainingArguments,
)
from transformers import SquadDataTrainingArguments as DataTrainingArguments
from transformers.trainer_utils import is_main_process


_UpperCamelCase     =    logging.getLogger(__name__)



@dataclass
class 					lowercase		:



 '''simple docstring'''


 __SCREAMING_SNAKE_CASE      							=       field(
     metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}      )
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}      )
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}      )
 __SCREAMING_SNAKE_CASE      							=       field(default=_UpperCamelCase				,       metadata={"""help""": """Set this flag to use fast tokenization."""}      )
 # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
 # or just modify its tokenizer_config.json.
 __SCREAMING_SNAKE_CASE      							=       field(
     default=_UpperCamelCase				,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}				,       )







def 		UpperCamelCase_(    ) ->				List[str]:
 # See all possible arguments in src/transformers/training_args.py
 # or by passing the --help flag to this script.
 # We now keep distinct sets of args, for a cleaner separation of concerns.

 UpperCAmelCase__           =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )

 if len(sys.argv     ) == 2 and sys.argv[1].endswith('.json'     ):
  # If we pass only one argument to the script and it's the path to a json file,
  # let's parse it to get our arguments.
  UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__           =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
 else:
  UpperCAmelCase__       ,					UpperCAmelCase__       ,					UpperCAmelCase__           =       parser.parse_args_into_dataclasses()

 if (
     os.path.exists(training_args.output_dir     )
     and os.listdir(training_args.output_dir     )
     and training_args.do_train
     and not training_args.overwrite_output_dir
 ):
  raise ValueError(
      f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
      ' --overwrite_output_dir to overcome.'     )

 # Setup logging
 logging.basicConfig(
     format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'						,					datefmt='%m/%d/%Y %H:%M:%S'						,					level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN						,					)
 logger.warning(
     'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'						,					training_args.local_rank						,					training_args.device						,					training_args.n_gpu						,					bool(training_args.local_rank != -1     )						,					training_args.fpaa						,					)
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank     ):
  transformers.utils.logging.set_verbosity_info()
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()
 logger.info('Training/evaluation parameters %s'						,					snake_case__     )

 # Prepare Question-Answering task
 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.

 UpperCAmelCase__           =       AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path						,					cache_dir=model_args.cache_dir						,					)
 UpperCAmelCase__           =       AutoTokenizer.from_pretrained(
     model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path						,					cache_dir=model_args.cache_dir						,					use_fast=snake_case__						,					)
 UpperCAmelCase__           =       AutoModelForQuestionAnswering.from_pretrained(
     model_args.model_name_or_path						,					from_tf=bool('.ckpt' in model_args.model_name_or_path     )						,					config=snake_case__						,					cache_dir=model_args.cache_dir						,					)

 # Get datasets
 UpperCAmelCase__           =       hasattr(model.config						,					'lang2id'     )
 UpperCAmelCase__           =       (
     SquadDataset(
         snake_case__						,					tokenizer=snake_case__						,					is_language_sensitive=snake_case__						,					cache_dir=model_args.cache_dir     )
     if training_args.do_train
     else None
 )
 UpperCAmelCase__           =       (
     SquadDataset(
         snake_case__						,					tokenizer=snake_case__						,					mode='dev'						,					is_language_sensitive=snake_case__						,					cache_dir=model_args.cache_dir						,					)
     if training_args.do_eval
     else None
 )

 # Data collator
 UpperCAmelCase__           =       DataCollatorWithPadding(snake_case__						,					pad_to_multiple_of=8     ) if training_args.fpaa else None

 # Initialize our Trainer
 UpperCAmelCase__           =       Trainer(
     model=snake_case__						,					args=snake_case__						,					train_dataset=snake_case__						,					eval_dataset=snake_case__						,					data_collator=snake_case__						,					)

 # Training
 if training_args.do_train:
  trainer.train(
      model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path     ) else None     )
  trainer.save_model()
  # For convenience, we also re-save the tokenizer to the same directory,
  # so that you can share your model easily on huggingface.co/models =)
  if trainer.is_world_master():
   tokenizer.save_pretrained(training_args.output_dir     )
def 		UpperCamelCase_(    snake_case__:						Optional[int]     ) ->				Union[str, Any]:
 # For xla_spawn (TPUs)
 main()


if __name__ == "__main__":
 main()



