


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


SCREAMING_SNAKE_CASE_      =			16
SCREAMING_SNAKE_CASE_      =			32




def        __lowercase						(      __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE = 16		)				->					Optional[Any]:
     """simple docstring"""




     __a       =   AutoTokenizer.from_pretrained("""bert-base-cased"""		)
     __a       =   load_dataset("""glue"""				,  """mrpc"""		)

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

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

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

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

 SCREAMING_SNAKE_CASE_      =			mocked_dataloaders  # noqa: F811




def        __lowercase						(      __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE		)				->					int:
     """simple docstring"""




     if os.environ.get("""TESTING_MOCKED_DATALOADERS"""				,  __SCREAMING_SNAKE_CASE		) == "1":
          __a       =   2
     # New Code #
     __a       =   int(args.gradient_accumulation_steps		)
     # Initialize accelerator
     __a       =   Accelerator(
         cpu=args.cpu				,  mixed_precision=args.mixed_precision				,  gradient_accumulation_steps=__SCREAMING_SNAKE_CASE		)
     if accelerator.distributed_type == DistributedType.TPU 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
     __a       =   config["""lr"""]
     __a       =   int(config["""num_epochs"""]		)
     __a       =   int(config["""seed"""]		)
     __a       =   int(config["""batch_size"""]		)

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

     set_seed(__SCREAMING_SNAKE_CASE		)
     __a ,						__a       =   get_dataloaders(__SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE		)
     # Instantiate the model (we build the model here so that the seed also control new weights initialization)
     __a       =   AutoModelForSequenceClassification.from_pretrained("""bert-base-cased"""				,  return_dict=__SCREAMING_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).
     __a       =   model.to(accelerator.device		)

     # Instantiate optimizer
     __a       =   AdamW(params=model.parameters()				,  lr=__SCREAMING_SNAKE_CASE		)

     # Instantiate scheduler
     __a       =   get_linear_schedule_with_warmup(
         optimizer=__SCREAMING_SNAKE_CASE				,  num_warmup_steps=100				,  num_training_steps=(len(__SCREAMING_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.
     __a ,						__a ,						__a ,						__a ,						__a       =   accelerator.prepare(
         __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE		)

     # Now we train the model
     for epoch in range(__SCREAMING_SNAKE_CASE		):
          model.train()
          for step, batch in enumerate(__SCREAMING_SNAKE_CASE		):
               # 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(__SCREAMING_SNAKE_CASE		):
                    __a       =   model(**__SCREAMING_SNAKE_CASE		)
                    __a       =   output.loss
                    accelerator.backward(__SCREAMING_SNAKE_CASE		)
                    optimizer.step()
                    lr_scheduler.step()
                    optimizer.zero_grad()

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

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




def        __lowercase						(      )				->					int:
     """simple docstring"""




     __a       =   argparse.ArgumentParser(description="""Simple example of training script."""		)
     parser.add_argument(
         """--mixed_precision"""				,  type=__SCREAMING_SNAKE_CASE				,  default=__SCREAMING_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."""				,  )
     # New Code #
     parser.add_argument(
         """--gradient_accumulation_steps"""				,  type=__SCREAMING_SNAKE_CASE				,  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."""		)
     __a       =   parser.parse_args()
     __a       =   {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
     training_function(__SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE		)


if __name__ == "__main__":
 main()










'''simple docstring'''







import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
 from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor


class  lowerCAmelCase_						:





  """simple docstring"""



  def __init__(					self     :							Any				,							SCREAMING_SNAKE_CASE__     :							int				,							SCREAMING_SNAKE_CASE__     :							List[str]=1_3				,							SCREAMING_SNAKE_CASE__     :							int=3_0				,							SCREAMING_SNAKE_CASE__     :							List[str]=2				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=3				,							SCREAMING_SNAKE_CASE__     :							List[str]=True				,							SCREAMING_SNAKE_CASE__     :							Dict=True				,							SCREAMING_SNAKE_CASE__     :							str=3_2				,							SCREAMING_SNAKE_CASE__     :							Tuple=5				,							SCREAMING_SNAKE_CASE__     :							List[Any]=4				,							SCREAMING_SNAKE_CASE__     :							Dict=3_7				,							SCREAMING_SNAKE_CASE__     :							Any="gelu"				,							SCREAMING_SNAKE_CASE__     :							Optional[Any]=0.1				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=0.1				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=1_0				,							SCREAMING_SNAKE_CASE__     :							str=0.0_2				,							SCREAMING_SNAKE_CASE__     :							Union[str, Any]=None				,							SCREAMING_SNAKE_CASE__     :							Any=2				,							):





       '''simple docstring'''

       __a       =   parent
       __a       =   batch_size
       __a       =   image_size
       __a       =   patch_size
       __a       =   num_channels
       __a       =   is_training
       __a       =   use_labels
       __a       =   hidden_size
       __a       =   num_hidden_layers
       __a       =   num_attention_heads
       __a       =   intermediate_size
       __a       =   hidden_act
       __a       =   hidden_dropout_prob
       __a       =   attention_probs_dropout_prob
       __a       =   type_sequence_label_size
       __a       =   initializer_range
       __a       =   scope
       __a       =   encoder_stride

       # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
       __a       =   (image_size // patch_size) ** 2
       __a       =   num_patches + 1

  def __a						(					self     :							Any						):





       '''simple docstring'''

       __a       =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       __a       =   None
       if self.use_labels:
            __a       =   ids_tensor([self.batch_size]				,							self.type_sequence_label_size						)

       __a       =   self.get_config()

       return config, pixel_values, labels

  def __a						(					self     :							Optional[int]						):





       '''simple docstring'''

       return ViTConfig(
           image_size=self.image_size				,							patch_size=self.patch_size				,							num_channels=self.num_channels				,							hidden_size=self.hidden_size				,							num_hidden_layers=self.num_hidden_layers				,							num_attention_heads=self.num_attention_heads				,							intermediate_size=self.intermediate_size				,							hidden_act=self.hidden_act				,							hidden_dropout_prob=self.hidden_dropout_prob				,							attention_probs_dropout_prob=self.attention_probs_dropout_prob				,							is_decoder=SCREAMING_SNAKE_CASE__				,							initializer_range=self.initializer_range				,							encoder_stride=self.encoder_stride				,							)

  def __a						(					self     :							Dict				,							SCREAMING_SNAKE_CASE__     :							Optional[Any]				,							SCREAMING_SNAKE_CASE__     :							Any				,							SCREAMING_SNAKE_CASE__     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   ViTModel(config=SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()
       __a       =   model(SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, self.seq_length, self.hidden_size)						)

  def __a						(					self     :							str				,							SCREAMING_SNAKE_CASE__     :							List[str]				,							SCREAMING_SNAKE_CASE__     :							Tuple				,							SCREAMING_SNAKE_CASE__     :							str						):





       '''simple docstring'''

       __a       =   ViTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()
       __a       =   model(SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(
           result.reconstruction.shape				,							(self.batch_size, self.num_channels, self.image_size, self.image_size)						)

       # test greyscale images
       __a       =   1
       __a       =   ViTForMaskedImageModeling(SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()

       __a       =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       __a       =   model(SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(result.reconstruction.shape				,							(self.batch_size, 1, self.image_size, self.image_size)						)

  def __a						(					self     :							str				,							SCREAMING_SNAKE_CASE__     :							Tuple				,							SCREAMING_SNAKE_CASE__     :							List[Any]				,							SCREAMING_SNAKE_CASE__     :							Dict						):





       '''simple docstring'''

       __a       =   self.type_sequence_label_size
       __a       =   ViTForImageClassification(SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()
       __a       =   model(SCREAMING_SNAKE_CASE__				,							labels=SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)						)

       # test greyscale images
       __a       =   1
       __a       =   ViTForImageClassification(SCREAMING_SNAKE_CASE__						)
       model.to(SCREAMING_SNAKE_CASE__						)
       model.eval()

       __a       =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       __a       =   model(SCREAMING_SNAKE_CASE__						)
       self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)						)


  def __a						(					self     :							str						):





       '''simple docstring'''

       __a       =   self.prepare_config_and_inputs()
       (
           (
           __a
       ) ,						(
           __a
       ) ,						(
           __a
       ) ,						
       )       =   config_and_inputs
       __a       =   {"""pixel_values""": pixel_values}
       return config, inputs_dict


@require_torch
class  lowerCAmelCase_						(       snake_case__		,    snake_case__		,    unittest.TestCase      ):





  """simple docstring"""



  a_       :str												=(
      (
          ViTModel,
          ViTForImageClassification,
          ViTForMaskedImageModeling,
      )
      if is_torch_available()
      else ()
  )
  a_       :Tuple												=(
      {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification}
      if is_torch_available()
      else {}
  )
  a_       :List[str]												=True

  a_       :str												=False
  a_       :Optional[int]												=False
  a_       :Tuple												=False

  def __a						(					self     :							str						):





       '''simple docstring'''

       __a       =   ViTModelTester(self						)
       __a       =   ConfigTester(self				,							config_class=SCREAMING_SNAKE_CASE__				,							has_text_modality=SCREAMING_SNAKE_CASE__				,							hidden_size=3_7						)

  def __a						(					self     :							Dict						):





       '''simple docstring'''

       self.config_tester.run_common_tests()

  @unittest.skip(reason="""ViT does not use inputs_embeds"""						)
  def __a						(					self     :							List[Any]						):





       '''simple docstring'''

       pass

  def __a						(					self     :							int						):





       '''simple docstring'''

       __a ,						__a       =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            __a       =   model_class(SCREAMING_SNAKE_CASE__						)
            self.assertIsInstance(model.get_input_embeddings()				,							(nn.Module)						)
            __a       =   model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__				,							nn.Linear						)						)

  def __a						(					self     :							int						):





       '''simple docstring'''

       __a ,						__a       =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            __a       =   model_class(SCREAMING_SNAKE_CASE__						)
            __a       =   inspect.signature(model.forward						)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            __a       =   [*signature.parameters.keys()]

            __a       =   ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]				,							SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							Union[str, Any]						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__						)

  def __a						(					self     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__						)


  @slow
  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __a       =   ViTModel.from_pretrained(SCREAMING_SNAKE_CASE__						)
            self.assertIsNotNone(SCREAMING_SNAKE_CASE__						)




def        __lowercase						(      )				->					int:
     """simple docstring"""




     __a       =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
     return image



@require_torch
@require_vision
class  lowerCAmelCase_						(       unittest.TestCase      ):





  """simple docstring"""



  @cached_property
  def __a						(					self     :							str						):





       '''simple docstring'''

       return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""						) if is_vision_available() else None

  @slow
  def __a						(					self     :							Dict						):





       '''simple docstring'''

       __a       =   ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""						).to(SCREAMING_SNAKE_CASE__						)

       __a       =   self.default_image_processor
       __a       =   prepare_img()
       __a       =   image_processor(images=SCREAMING_SNAKE_CASE__				,							return_tensors="""pt"""						).to(SCREAMING_SNAKE_CASE__						)

       # forward pass
       with torch.no_grad():
            __a       =   model(**SCREAMING_SNAKE_CASE__						)

       # verify the logits
       __a       =   torch.Size((1, 1_0_0_0)						)
       self.assertEqual(outputs.logits.shape				,							SCREAMING_SNAKE_CASE__						)

       __a       =   torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]						).to(SCREAMING_SNAKE_CASE__						)

       self.assertTrue(torch.allclose(outputs.logits[0, :3]				,							SCREAMING_SNAKE_CASE__				,							atol=1E-4						)						)

  @slow
  def __a						(					self     :							int						):





       '''simple docstring'''

       __a       =   ViTModel.from_pretrained("""facebook/dino-vits8"""						).to(SCREAMING_SNAKE_CASE__						)

       __a       =   ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""				,							size=4_8_0						)
       __a       =   prepare_img()
       __a       =   image_processor(images=SCREAMING_SNAKE_CASE__				,							return_tensors="""pt"""						)
       __a       =   inputs.pixel_values.to(SCREAMING_SNAKE_CASE__						)

       # forward pass
       with torch.no_grad():
            __a       =   model(SCREAMING_SNAKE_CASE__				,							interpolate_pos_encoding=SCREAMING_SNAKE_CASE__						)

       # verify the logits
       __a       =   torch.Size((1, 3_6_0_1, 3_8_4)						)
       self.assertEqual(outputs.last_hidden_state.shape				,							SCREAMING_SNAKE_CASE__						)

       __a       =   torch.tensor(
           [[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]]						).to(SCREAMING_SNAKE_CASE__						)

       self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]				,							SCREAMING_SNAKE_CASE__				,							atol=1E-4						)						)


  @slow
  @require_accelerate
  @require_torch_gpu
  def __a						(					self     :							Optional[Any]						):





       '''simple docstring'''

       __a       =   ViTModel.from_pretrained("""facebook/dino-vits8"""				,							torch_dtype=torch.floataa				,							device_map="""auto"""						)
       __a       =   self.default_image_processor

       __a       =   prepare_img()
       __a       =   image_processor(images=SCREAMING_SNAKE_CASE__				,							return_tensors="""pt"""						)
       __a       =   inputs.pixel_values.to(SCREAMING_SNAKE_CASE__						)

       # forward pass to make sure inference works in fp16
       with torch.no_grad():
            __a       =   model(SCREAMING_SNAKE_CASE__						)






