


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

lowercase							=16
lowercase							=32





def lowerCamelCase__			(						__lowerCamelCase       :							Accelerator       ,    __lowerCamelCase       :							int = 1_6							):







   '''simple docstring'''




   _UpperCAmelCase   :   List[Any]							    =AutoTokenizer.from_pretrained('bert-base-cased'							)
   _UpperCAmelCase   :   Tuple							    =load_dataset('glue'       ,    'mrpc'							)

   def tokenize_function(__lowerCamelCase       :							Union[str, Any]							):
      # max_length=None => use the model max length (it's actually the default)
      _UpperCAmelCase   :   str							    =tokenizer(examples['sentence1']       ,    examples['sentence2']       ,    truncation=__lowerCamelCase       ,    max_length=__lowerCamelCase							)
      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(
          __lowerCamelCase       ,    batched=__lowerCamelCase       ,    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   :   Tuple							    =tokenized_datasets.rename_column('label'       ,    'labels'							)

   def collate_fn(__lowerCamelCase       :							List[Any]							):
      # On TPU it's best to pad everything to the same length or training will be very slow.
      _UpperCAmelCase   :   Union[str, Any]							    =1_2_8 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   :   Tuple							    =1_6
      elif accelerator.mixed_precision != "no":
         _UpperCAmelCase   :   str							    =8
      else:
         _UpperCAmelCase   :   List[str]							    =None

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

   # Instantiate dataloaders.
   _UpperCAmelCase   :   str							    =DataLoader(
       tokenized_datasets['train']       ,    shuffle=__lowerCamelCase       ,    collate_fn=__lowerCamelCase       ,    batch_size=__lowerCamelCase							)
   _UpperCAmelCase   :   int							    =DataLoader(
       tokenized_datasets['validation']       ,    shuffle=__lowerCamelCase       ,    collate_fn=__lowerCamelCase       ,    batch_size=__lowerCamelCase							)

   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

 lowercase							=mocked_dataloaders  # noqa: F811





def lowerCamelCase__			(						__lowerCamelCase       :							List[Any]       ,    __lowerCamelCase       :							int							):







   '''simple docstring'''




   if os.environ.get('TESTING_MOCKED_DATALOADERS'       ,    __lowerCamelCase							) == "1":
      _UpperCAmelCase   :   Optional[Any]							    =2
   # Initialize accelerator
   _UpperCAmelCase   :   List[Any]							    =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[Any]							    =config['lr']
   _UpperCAmelCase   :   str							    =int(config['num_epochs']							)
   _UpperCAmelCase   :   List[Any]							    =int(config['seed']							)
   _UpperCAmelCase   :   Optional[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   :   str							    =args.checkpointing_steps
      elif args.checkpointing_steps.isdigit():
         _UpperCAmelCase   :   Optional[Any]							    =int(args.checkpointing_steps							)
      else:
         raise ValueError(
             f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."							)
   else:
      _UpperCAmelCase   :   Union[str, Any]							    =None

   set_seed(__lowerCamelCase							)

   _UpperCAmelCase    ,       _UpperCAmelCase   :   str							    =get_dataloaders(__lowerCamelCase       ,    __lowerCamelCase							)
   _UpperCAmelCase   :   Tuple							    =evaluate.load('glue'       ,    'mrpc'							)

   # If the batch size is too big we use gradient accumulation
   _UpperCAmelCase   :   Tuple							    =1
   if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
      _UpperCAmelCase   :   List[str]							    =batch_size // MAX_GPU_BATCH_SIZE
      _UpperCAmelCase   :   int							    =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=__lowerCamelCase							)

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

   # Instantiate optimizer
   _UpperCAmelCase   :   Tuple							    =AdamW(params=model.parameters()       ,    lr=__lowerCamelCase							)

   # Instantiate scheduler
   _UpperCAmelCase   :   List[Any]							    =get_linear_schedule_with_warmup(
       optimizer=__lowerCamelCase       ,    num_warmup_steps=1_0_0       ,    num_training_steps=(len(__lowerCamelCase							) * 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(
       __lowerCamelCase       ,    __lowerCamelCase       ,    __lowerCamelCase       ,    __lowerCamelCase       ,    __lowerCamelCase							)

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

      if "epoch" in training_difference:
         _UpperCAmelCase   :   Union[str, Any]							    =int(training_difference.replace('epoch_'       ,    ''							)							) + 1
         _UpperCAmelCase   :   Dict							    =None
      else:
         _UpperCAmelCase   :   Any							    =int(training_difference.replace('step_'       ,    ''							)							)
         _UpperCAmelCase   :   Tuple							    =resume_step // len(__lowerCamelCase							)
         resume_step -= starting_epoch * len(__lowerCamelCase							)

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

      model.eval()
      for step, batch in enumerate(__lowerCamelCase							):
         # 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   :   List[Any]							    =model(**__lowerCamelCase							)
         _UpperCAmelCase   :   Optional[int]							    =outputs.logits.argmax(dim=-1							)
         _UpperCAmelCase    ,       _UpperCAmelCase   :   Any							    =accelerator.gather_for_metrics((predictions, batch['labels'])							)
         metric.add_batch(
             predictions=__lowerCamelCase       ,    references=__lowerCamelCase       ,    )

      _UpperCAmelCase   :   Optional[Any]							    =metric.compute()
      # Use accelerator.print to print only on the main process.
      accelerator.print(f"epoch {epoch}:"       ,    __lowerCamelCase							)

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





def lowerCamelCase__			(						):







   '''simple docstring'''




   _UpperCAmelCase   :   int							    =argparse.ArgumentParser(description='Simple example of training script.'							)
   parser.add_argument(
       '--mixed_precision'       ,    type=__lowerCamelCase       ,    default=__lowerCamelCase       ,    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=__lowerCamelCase       ,    default=__lowerCamelCase       ,    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=__lowerCamelCase       ,    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=__lowerCamelCase       ,    default=__lowerCamelCase       ,    help='If the training should continue from a checkpoint folder.'       ,    )
   _UpperCAmelCase   :   List[Any]							    =parser.parse_args()
   _UpperCAmelCase   :   Union[str, Any]							    ={'lr': 2e-5, 'num_epochs': 3, 'seed': 4_2, 'batch_size': 1_6}
   training_function(__lowerCamelCase       ,    __lowerCamelCase							)


if __name__ == "__main__":
 main()







import unittest

from transformers import BlenderbotTokenizer, BlenderbotTokenizerFast
from transformers.utils import cached_property






class 	A	(						unittest.TestCase						):
     """simple docstring"""

     @cached_property
     def        __snake_case      (			self     :      Union[str, Any]	) ->				str:
           return BlenderbotTokenizer.from_pretrained('facebook/blenderbot-3B'	)




     @cached_property
     def        __snake_case      (			self     :      Tuple	) ->				Dict:
           return BlenderbotTokenizerFast.from_pretrained('facebook/blenderbot-3B'	)




     def        __snake_case      (			self     :      List[str]	) ->				int:
           lowerCamelCase__					     = self.tokenizer_ab
           lowerCamelCase__					     = ' I am a small frog.'
           lowerCamelCase__					     = tok([src_text]		,     padding=A__		,     truncation=A__	)['input_ids']
           lowerCamelCase__					     = tok.batch_decode(A__		,     skip_special_tokens=A__		,     clean_up_tokenization_spaces=A__	)[0]
           assert src_text == decoded




     def        __snake_case      (			self     :      List[str]	) ->				str:
           lowerCamelCase__					     = self.rust_tokenizer_ab
           lowerCamelCase__					     = ' I am a small frog.'
           lowerCamelCase__					     = tok([src_text]		,     padding=A__		,     truncation=A__	)['input_ids']
           lowerCamelCase__					     = tok.batch_decode(A__		,     skip_special_tokens=A__		,     clean_up_tokenization_spaces=A__	)[0]
           assert src_text == decoded




     def        __snake_case      (			self     :      Any	) ->				str:
           assert self.tokenizer_ab.add_prefix_space
           assert self.tokenizer_ab([' Sam', 'Sam']	).input_ids == [[5_5_0_2, 2], [5_5_0_2, 2]]




     def        __snake_case      (			self     :      str	) ->				Union[str, Any]:
           assert self.rust_tokenizer_ab.add_prefix_space
           assert self.rust_tokenizer_ab([' Sam', 'Sam']	).input_ids == [[5_5_0_2, 2], [5_5_0_2, 2]]