


from __future__ import annotations

import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import numpy
    import tensorflow as tf

    from transformers import (
        TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
        BertConfig,
        DPRConfig,
        TFDPRContextEncoder,
        TFDPRQuestionEncoder,
        TFDPRReader,
    )


class     lowercase__  :






  def __init__(					self      :					List[str]		,						_lowercase      :					int		,						_lowercase      :					Any=13		,						_lowercase      :					List[str]=7		,						_lowercase      :					List[Any]=True		,						_lowercase      :					Tuple=True		,						_lowercase      :					Union[str, Any]=True		,						_lowercase      :					List[Any]=True		,						_lowercase      :					Dict=99		,						_lowercase      :					List[Any]=32		,						_lowercase      :					int=2		,						_lowercase      :					Union[str, Any]=4		,						_lowercase      :					Dict=37		,						_lowercase      :					int="gelu"		,						_lowercase      :					int=0.1		,						_lowercase      :					Optional[Any]=0.1		,						_lowercase      :					str=5_12		,						_lowercase      :					Any=16		,						_lowercase      :					Dict=2		,						_lowercase      :					Any=0.0_2		,						_lowercase      :					Optional[int]=3		,						_lowercase      :					Any=4		,						_lowercase      :					Dict=None		,						_lowercase      :					str=0		,						):




         """simple docstring"""







         UpperCAmelCase__										=     parent
         UpperCAmelCase__										=     batch_size
         UpperCAmelCase__										=     seq_length
         UpperCAmelCase__										=     is_training
         UpperCAmelCase__										=     use_input_mask
         UpperCAmelCase__										=     use_token_type_ids
         UpperCAmelCase__										=     use_labels
         UpperCAmelCase__										=     vocab_size
         UpperCAmelCase__										=     hidden_size
         UpperCAmelCase__										=     num_hidden_layers
         UpperCAmelCase__										=     num_attention_heads
         UpperCAmelCase__										=     intermediate_size
         UpperCAmelCase__										=     hidden_act
         UpperCAmelCase__										=     hidden_dropout_prob
         UpperCAmelCase__										=     attention_probs_dropout_prob
         UpperCAmelCase__										=     max_position_embeddings
         UpperCAmelCase__										=     type_vocab_size
         UpperCAmelCase__										=     type_sequence_label_size
         UpperCAmelCase__										=     initializer_range
         UpperCAmelCase__										=     num_labels
         UpperCAmelCase__										=     num_choices
         UpperCAmelCase__										=     scope
         UpperCAmelCase__										=     projection_dim






  def 			_UpperCAmelCase  (					self      :					List[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     ids_tensor([self.batch_size, self.seq_length]		,						self.vocab_size )

         UpperCAmelCase__										=     None
         if self.use_input_mask:
                # follow test_modeling_tf_ctrl.py
                UpperCAmelCase__										=     random_attention_mask([self.batch_size, self.seq_length] )

         UpperCAmelCase__										=     None
         if self.use_token_type_ids:
                UpperCAmelCase__										=     ids_tensor([self.batch_size, self.seq_length]		,						self.type_vocab_size )

         UpperCAmelCase__										=     None
         UpperCAmelCase__										=     None
         UpperCAmelCase__										=     None
         if self.use_labels:
                UpperCAmelCase__										=     ids_tensor([self.batch_size]		,						self.type_sequence_label_size )
                UpperCAmelCase__										=     ids_tensor([self.batch_size, self.seq_length]		,						self.num_labels )
                UpperCAmelCase__										=     ids_tensor([self.batch_size]		,						self.num_choices )

         UpperCAmelCase__										=     BertConfig(
             vocab_size=self.vocab_size		,						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		,						max_position_embeddings=self.max_position_embeddings		,						type_vocab_size=self.type_vocab_size		,						is_decoder=_lowercase		,						initializer_range=self.initializer_range		,						)
         UpperCAmelCase__										=     DPRConfig(projection_dim=self.projection_dim		,						**config.to_dict() )

         return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels






  def 			_UpperCAmelCase  (					self      :					Any		,						_lowercase      :					Dict		,						_lowercase      :					Tuple		,						_lowercase      :					List[str]		,						_lowercase      :					Union[str, Any]		,						_lowercase      :					List[str]		,						_lowercase      :					int		,						_lowercase      :					Tuple ):




         """simple docstring"""







         UpperCAmelCase__										=     TFDPRContextEncoder(config=_lowercase )
         UpperCAmelCase__										=     model(_lowercase		,						attention_mask=_lowercase		,						token_type_ids=_lowercase )
         UpperCAmelCase__										=     model(_lowercase		,						token_type_ids=_lowercase )
         UpperCAmelCase__										=     model(_lowercase )
         self.parent.assertEqual(result.pooler_output.shape		,						(self.batch_size, self.projection_dim or self.hidden_size) )






  def 			_UpperCAmelCase  (					self      :					Dict		,						_lowercase      :					Tuple		,						_lowercase      :					int		,						_lowercase      :					int		,						_lowercase      :					List[Any]		,						_lowercase      :					Optional[Any]		,						_lowercase      :					int		,						_lowercase      :					List[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     TFDPRQuestionEncoder(config=_lowercase )
         UpperCAmelCase__										=     model(_lowercase		,						attention_mask=_lowercase		,						token_type_ids=_lowercase )
         UpperCAmelCase__										=     model(_lowercase		,						token_type_ids=_lowercase )
         UpperCAmelCase__										=     model(_lowercase )
         self.parent.assertEqual(result.pooler_output.shape		,						(self.batch_size, self.projection_dim or self.hidden_size) )






  def 			_UpperCAmelCase  (					self      :					Any		,						_lowercase      :					Optional[Any]		,						_lowercase      :					Dict		,						_lowercase      :					Union[str, Any]		,						_lowercase      :					Dict		,						_lowercase      :					Any		,						_lowercase      :					str		,						_lowercase      :					str ):




         """simple docstring"""







         UpperCAmelCase__										=     TFDPRReader(config=_lowercase )
         UpperCAmelCase__										=     model(_lowercase		,						attention_mask=_lowercase )

         self.parent.assertEqual(result.start_logits.shape		,						(self.batch_size, self.seq_length) )
         self.parent.assertEqual(result.end_logits.shape		,						(self.batch_size, self.seq_length) )
         self.parent.assertEqual(result.relevance_logits.shape		,						(self.batch_size,) )






  def 			_UpperCAmelCase  (					self      :					Any ):




         """simple docstring"""







         UpperCAmelCase__										=     self.prepare_config_and_inputs()
         (
             (
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			
         )										=     config_and_inputs
         UpperCAmelCase__										=     {"input_ids": input_ids}
         return config, inputs_dict




@require_tf
class     lowercase__  (					__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							unittest.TestCase		):
  A__=  (
      (
          TFDPRContextEncoder,
          TFDPRQuestionEncoder,
          TFDPRReader,
      )
      if is_tf_available()
      else ()
  )
  A__=  {'feature-extraction': TFDPRQuestionEncoder} if is_tf_available() else {}

  A__=  False
  A__=  False
  A__=  False
  A__=  False
  A__=  False






  def 			_UpperCAmelCase  (					self      :					Tuple ):




         """simple docstring"""







         UpperCAmelCase__										=     TFDPRModelTester(self )
         UpperCAmelCase__										=     ConfigTester(self		,						config_class=_lowercase		,						hidden_size=37 )






  def 			_UpperCAmelCase  (					self      :					str ):




         """simple docstring"""







         self.config_tester.run_common_tests()






  def 			_UpperCAmelCase  (					self      :					Tuple ):




         """simple docstring"""







         UpperCAmelCase__										=     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_dpr_context_encoder(*_lowercase )






  def 			_UpperCAmelCase  (					self      :					List[str] ):




         """simple docstring"""







         UpperCAmelCase__										=     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_dpr_question_encoder(*_lowercase )






  def 			_UpperCAmelCase  (					self      :					List[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_dpr_reader(*_lowercase )






  @slow
  def 			_UpperCAmelCase  (					self      :					Any ):




         """simple docstring"""







         for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase__										=     TFDPRContextEncoder.from_pretrained(_lowercase )
                self.assertIsNotNone(_lowercase )

         for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase__										=     TFDPRContextEncoder.from_pretrained(_lowercase )
                self.assertIsNotNone(_lowercase )

         for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase__										=     TFDPRQuestionEncoder.from_pretrained(_lowercase )
                self.assertIsNotNone(_lowercase )

         for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCAmelCase__										=     TFDPRReader.from_pretrained(_lowercase )
                self.assertIsNotNone(_lowercase )




@require_tf
class     lowercase__  (					unittest.TestCase		):






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




         """simple docstring"""







         UpperCAmelCase__										=     TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base" )

         UpperCAmelCase__										=     tf.constant(
             [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]] )  # [CLS] hello, is my dog cute? [SEP]
         UpperCAmelCase__										=     model(_lowercase )[0]  # embedding shape = (1, 768)
         # compare the actual values for a slice.
         UpperCAmelCase__										=     tf.constant(
             [
                 [
                     0.0_3_2_3_6_2_5_3,
                     0.1_2_7_5_3_3_3_5,
                     0.1_6_8_1_8_5_0_9,
                     0.0_0_2_7_9_7_8_6,
                     0.3_8_9_6_9_3_3,
                     0.2_4_2_6_4_9_4_5,
                     0.2_1_7_8_9_7_1,
                     -0.0_2_3_3_5_2_2_7,
                     -0.0_8_4_8_1_9_5_9,
                     -0.1_4_3_2_4_1_1_7,
                 ]
             ] )
         self.assertTrue(numpy.allclose(output[:, :10].numpy()		,						expected_slice.numpy()		,						atol=1E-4 ) )









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


A      = 16
A      = 32





def __UpperCAmelCase       (		__A ,						__A = 1_6			)						->					Tuple:



       '''simple docstring'''





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

       def tokenize_function(__A			):
              # max_length=None => use the model max length (it's actually the default)
              UpperCAmelCase__										=     tokenizer(examples["sentence1"] ,						examples["sentence2"] ,						truncation=__A ,						max_length=__A			)
              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(
                  __A ,						batched=__A ,						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(__A			):
              # On TPU it's best to pad everything to the same length or training will be very slow.
              UpperCAmelCase__										=     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__										=     1_6
              elif accelerator.mixed_precision != "no":
                     UpperCAmelCase__										=     8
              else:
                     UpperCAmelCase__										=     None

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

       # Instantiate dataloaders.
       UpperCAmelCase__										=     DataLoader(
           tokenized_datasets["train"] ,						shuffle=__A ,						collate_fn=__A ,						batch_size=__A			)
       UpperCAmelCase__										=     DataLoader(
           tokenized_datasets["validation"] ,						shuffle=__A ,						collate_fn=__A ,						batch_size=__A			)

       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 __UpperCAmelCase       (		__A ,						__A			)						->					Dict:



       '''simple docstring'''





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

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

       set_seed(__A			)
       UpperCAmelCase__						,			UpperCAmelCase__										=     get_dataloaders(__A ,						__A			)
       # 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=__A			)

       # 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=__A			)

       # Instantiate scheduler
       UpperCAmelCase__										=     get_linear_schedule_with_warmup(
           optimizer=__A ,						num_warmup_steps=1_0_0 ,						num_training_steps=(len(__A			) * 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(
           __A ,						__A ,						__A ,						__A ,						__A			)

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

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

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





def __UpperCAmelCase       (		)						->					Dict:



       '''simple docstring'''





       UpperCAmelCase__										=     argparse.ArgumentParser(description="Simple example of training script."			)
       parser.add_argument(
           "--mixed_precision" ,						type=__A ,						default=__A ,						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=__A ,						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."			)
       UpperCAmelCase__										=     parser.parse_args()
       UpperCAmelCase__										=     {"lr": 2E-5, "num_epochs": 3, "seed": 4_2, "batch_size": 1_6}
       training_function(__A ,						__A			)


if __name__ == "__main__":
    main()





