



'''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
from accelerate.local_sgd import LocalSGD


########################################################################
# This is a fully working simple example to use Accelerate
# with LocalSGD, which is a method to synchronize model
# parameters every K batches. It is different, but complementary
# to 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
#
########################################################################


_lowerCAmelCase										=     16
_lowerCAmelCase										=     32
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase = 16      ):



    """simple docstring"""





    lowerCAmelCase__			:  Tuple											= AutoTokenizer.from_pretrained("""bert-base-cased"""      )
    lowerCAmelCase__			:  int											= load_dataset("""glue"""							,   """mrpc"""      )

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

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

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

    # Instantiate dataloaders.
    lowerCAmelCase__			:  Dict											= DataLoader(
        tokenized_datasets["""train"""]							,   shuffle=_lowerCAmelCase							,   collate_fn=_lowerCAmelCase							,   batch_size=_lowerCAmelCase      )
    lowerCAmelCase__			:  Any											= 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

 _lowerCAmelCase										=     mocked_dataloaders  # noqa: F811
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase      ):



    """simple docstring"""





    if os.environ.get("""TESTING_MOCKED_DATALOADERS"""							,   _lowerCAmelCase      ) == "1":
        lowerCAmelCase__			:  List[str]											= 2
    # New Code #
    lowerCAmelCase__			:  Optional[int]											= int(args.gradient_accumulation_steps      )
    lowerCAmelCase__			:  Dict											= int(args.local_sgd_steps      )
    # Initialize accelerator
    lowerCAmelCase__			:  int											= Accelerator(
        cpu=args.cpu							,   mixed_precision=args.mixed_precision							,   gradient_accumulation_steps=_lowerCAmelCase      )
    if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]:
        raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)"""      )
    # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
    lowerCAmelCase__			:  Any											= config["""lr"""]
    lowerCAmelCase__			:  List[Any]											= int(config["""num_epochs"""]      )
    lowerCAmelCase__			:  Union[str, Any]											= int(config["""seed"""]      )
    lowerCAmelCase__			:  Optional[Any]											= int(config["""batch_size"""]      )

    lowerCAmelCase__			:  str											= evaluate.load("""glue"""							,   """mrpc"""      )

    set_seed(_lowerCAmelCase      )
    lowerCAmelCase__				,       lowerCAmelCase__			:  Dict											= get_dataloaders(_lowerCAmelCase							,   _lowerCAmelCase      )
    # Instantiate the model (we build the model here so that the seed also control new weights initialization)
    lowerCAmelCase__			:  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).
    lowerCAmelCase__			:  Optional[Any]											= model.to(accelerator.device      )

    # Instantiate optimizer
    lowerCAmelCase__			:  List[Any]											= AdamW(params=model.parameters()							,   lr=_lowerCAmelCase      )

    # Instantiate scheduler
    lowerCAmelCase__			:  Dict											= get_linear_schedule_with_warmup(
        optimizer=_lowerCAmelCase							,   num_warmup_steps=100							,   num_training_steps=(len(_lowerCAmelCase      ) * 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.
    lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__			:  Optional[int]											= accelerator.prepare(
        _lowerCAmelCase							,   _lowerCAmelCase							,   _lowerCAmelCase							,   _lowerCAmelCase							,   _lowerCAmelCase      )

    # Now we train the model
    for epoch in range(_lowerCAmelCase      ):
        model.train()
        with LocalSGD(
            accelerator=_lowerCAmelCase							,   model=_lowerCAmelCase							,   local_sgd_steps=_lowerCAmelCase							,   enabled=local_sgd_steps is not None      ) as local_sgd:
            for step, batch in enumerate(_lowerCAmelCase      ):
                # 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(_lowerCAmelCase      ):
                    lowerCAmelCase__			:  int											= model(**_lowerCAmelCase      )
                    lowerCAmelCase__			:  str											= output.loss
                    accelerator.backward(_lowerCAmelCase      )
                    optimizer.step()
                    lr_scheduler.step()
                    optimizer.zero_grad()
                    # LocalSGD-specific line
                    local_sgd.step()

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

        lowerCAmelCase__			:  str											= metric.compute()
        # Use accelerator.print to print only on the main process.
        accelerator.print(f"""epoch {epoch}:"""							,   _lowerCAmelCase      )
def        _SCREAMING_SNAKE_CASE  (	):



    """simple docstring"""





    lowerCAmelCase__			:  List[str]											= 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."""							,   )
    # New Code #
    parser.add_argument(
        """--gradient_accumulation_steps"""							,   type=_lowerCAmelCase							,   default=1							,   help="""The number of minibatches to be ran before gradients are accumulated."""							,   )
    parser.add_argument(
        """--local_sgd_steps"""							,   type=_lowerCAmelCase							,   default=8							,   help="""Number of local SGD steps or None to disable local SGD"""      )
    parser.add_argument("""--cpu"""							,   action="""store_true"""							,   help="""If passed, will train on the CPU."""      )
    lowerCAmelCase__			:  str											= parser.parse_args()
    lowerCAmelCase__			:  Dict											= {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
    training_function(_lowerCAmelCase							,   _lowerCAmelCase      )


if __name__ == "__main__":
 main()








'''simple docstring'''





import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


_lowerCAmelCase										=     logging.get_logger(__name__)

_lowerCAmelCase										=     {
    '''Salesforce/instruct-blip-flan-t5''': '''https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json''',
}






class 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_					):
  '''simple docstring'''




  __lowercase							:				Optional[Any]           =				'''instructblip_vision_model'''




  def __init__(   self  ,__UpperCAmelCase=1408  ,__UpperCAmelCase=6144  ,__UpperCAmelCase=39  ,__UpperCAmelCase=16  ,__UpperCAmelCase=224  ,__UpperCAmelCase=14  ,__UpperCAmelCase="gelu"  ,__UpperCAmelCase=1E-6  ,__UpperCAmelCase=0.0  ,__UpperCAmelCase=1E-10  ,__UpperCAmelCase=True  ,**__UpperCAmelCase  ,)   ->		List[Any]:
      super().__init__(**__UpperCAmelCase				)

      lowerCAmelCase__			:  Any											= hidden_size
      lowerCAmelCase__			:  List[str]											= intermediate_size
      lowerCAmelCase__			:  str											= num_hidden_layers
      lowerCAmelCase__			:  Tuple											= num_attention_heads
      lowerCAmelCase__			:  Union[str, Any]											= patch_size
      lowerCAmelCase__			:  int											= image_size
      lowerCAmelCase__			:  Tuple											= initializer_range
      lowerCAmelCase__			:  Optional[int]											= attention_dropout
      lowerCAmelCase__			:  List[str]											= layer_norm_eps
      lowerCAmelCase__			:  List[Any]											= hidden_act
      lowerCAmelCase__			:  int											= qkv_bias






  @classmethod
  def 							UpperCAmelCase_     (   cls  ,__UpperCAmelCase  ,**__UpperCAmelCase				)   ->		"PretrainedConfig":
      cls._set_token_in_kwargs(__UpperCAmelCase				)

      lowerCAmelCase__				,       lowerCAmelCase__			:  Tuple											= cls.get_config_dict(__UpperCAmelCase  ,**__UpperCAmelCase				)

      # get the vision config dict if we are loading from InstructBlipConfig
      if config_dict.get("""model_type"""				) == "instructblip":
          lowerCAmelCase__			:  Optional[int]											= config_dict["""vision_config"""]

      if "model_type" in config_dict and hasattr(cls  ,"""model_type"""				) and config_dict["model_type"] != cls.model_type:
          logger.warning(
              F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
              F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""				)

      return cls.from_dict(__UpperCAmelCase  ,**__UpperCAmelCase				)







class 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_					):
  '''simple docstring'''




  __lowercase							:				int           =				'''instructblip_qformer'''




  def __init__(   self  ,__UpperCAmelCase=3_0522  ,__UpperCAmelCase=768  ,__UpperCAmelCase=12  ,__UpperCAmelCase=12  ,__UpperCAmelCase=3072  ,__UpperCAmelCase="gelu"  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=512  ,__UpperCAmelCase=0.0_2  ,__UpperCAmelCase=1E-12  ,__UpperCAmelCase=0  ,__UpperCAmelCase="absolute"  ,__UpperCAmelCase=2  ,__UpperCAmelCase=1408  ,**__UpperCAmelCase  ,)   ->		Tuple:
      super().__init__(pad_token_id=__UpperCAmelCase  ,**__UpperCAmelCase				)

      lowerCAmelCase__			:  List[Any]											= vocab_size
      lowerCAmelCase__			:  Optional[Any]											= hidden_size
      lowerCAmelCase__			:  Any											= num_hidden_layers
      lowerCAmelCase__			:  int											= num_attention_heads
      lowerCAmelCase__			:  Tuple											= hidden_act
      lowerCAmelCase__			:  int											= intermediate_size
      lowerCAmelCase__			:  Tuple											= hidden_dropout_prob
      lowerCAmelCase__			:  Optional[Any]											= attention_probs_dropout_prob
      lowerCAmelCase__			:  Optional[Any]											= max_position_embeddings
      lowerCAmelCase__			:  Any											= initializer_range
      lowerCAmelCase__			:  Tuple											= layer_norm_eps
      lowerCAmelCase__			:  Dict											= position_embedding_type
      lowerCAmelCase__			:  int											= cross_attention_frequency
      lowerCAmelCase__			:  List[Any]											= encoder_hidden_size






  @classmethod
  def 							UpperCAmelCase_     (   cls  ,__UpperCAmelCase  ,**__UpperCAmelCase				)   ->		"PretrainedConfig":
      cls._set_token_in_kwargs(__UpperCAmelCase				)

      lowerCAmelCase__				,       lowerCAmelCase__			:  Any											= cls.get_config_dict(__UpperCAmelCase  ,**__UpperCAmelCase				)

      # get the qformer config dict if we are loading from InstructBlipConfig
      if config_dict.get("""model_type"""				) == "instructblip":
          lowerCAmelCase__			:  Tuple											= config_dict["""qformer_config"""]

      if "model_type" in config_dict and hasattr(cls  ,"""model_type"""				) and config_dict["model_type"] != cls.model_type:
          logger.warning(
              F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
              F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""				)

      return cls.from_dict(__UpperCAmelCase  ,**__UpperCAmelCase				)







class 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_					):
  '''simple docstring'''




  __lowercase							:				Any           =				'''instructblip'''
  __lowercase							:				str           =				True




  def __init__(   self  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None  ,__UpperCAmelCase=32  ,**__UpperCAmelCase				)   ->		Any:
      super().__init__(**__UpperCAmelCase				)

      if vision_config is None:
          lowerCAmelCase__			:  Any											= {}
          logger.info("""vision_config is None. initializing the InstructBlipVisionConfig with default values."""				)

      if qformer_config is None:
          lowerCAmelCase__			:  List[str]											= {}
          logger.info("""qformer_config is None. Initializing the InstructBlipQFormerConfig with default values."""				)

      if text_config is None:
          lowerCAmelCase__			:  List[Any]											= {}
          logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`)."""				)

      lowerCAmelCase__			:  Any											= InstructBlipVisionConfig(**__UpperCAmelCase				)
      lowerCAmelCase__			:  Tuple											= InstructBlipQFormerConfig(**__UpperCAmelCase				)
      lowerCAmelCase__			:  Tuple											= text_config["""model_type"""] if """model_type""" in text_config else """opt"""
      lowerCAmelCase__			:  Any											= CONFIG_MAPPING[text_model_type](**__UpperCAmelCase				)

      lowerCAmelCase__			:  Union[str, Any]											= self.text_config.tie_word_embeddings
      lowerCAmelCase__			:  Any											= self.text_config.is_encoder_decoder

      lowerCAmelCase__			:  int											= num_query_tokens
      lowerCAmelCase__			:  List[str]											= self.vision_config.hidden_size
      lowerCAmelCase__			:  Optional[int]											= self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
      lowerCAmelCase__			:  Optional[Any]											= 1.0
      lowerCAmelCase__			:  Dict											= 0.0_2




  @classmethod
  def 							UpperCAmelCase_     (   cls  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,**__UpperCAmelCase  ,)   ->		Union[str, Any]:
      return cls(
          vision_config=vision_config.to_dict()  ,qformer_config=qformer_config.to_dict()  ,text_config=text_config.to_dict()  ,**__UpperCAmelCase  ,)






  def 							UpperCAmelCase_     (   self				)   ->		str:
      lowerCAmelCase__			:  List[Any]											= copy.deepcopy(self.__dict__				)
      lowerCAmelCase__			:  str											= self.vision_config.to_dict()
      lowerCAmelCase__			:  Union[str, Any]											= self.qformer_config.to_dict()
      lowerCAmelCase__			:  Union[str, Any]											= self.text_config.to_dict()
      lowerCAmelCase__			:  str											= self.__class__.model_type
      return output


