



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


a_			=					logging.get_logger(__name__)

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



class  __lowerCAmelCase     (	lowerCAmelCase__   ):
 lowerCAmelCase__       					=  """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-1_0	,				__UpperCAmelCase=True	,				**__UpperCAmelCase	,				):



    '''simple docstring'''
    super().__init__(**__UpperCAmelCase				)

    __lowerCamelCase													=    hidden_size
    __lowerCamelCase													=    intermediate_size
    __lowerCamelCase													=    num_hidden_layers
    __lowerCamelCase													=    num_attention_heads
    __lowerCamelCase													=    patch_size
    __lowerCamelCase													=    image_size
    __lowerCamelCase													=    initializer_range
    __lowerCamelCase													=    attention_dropout
    __lowerCamelCase													=    layer_norm_eps
    __lowerCamelCase													=    hidden_act
    __lowerCamelCase													=    qkv_bias




 @classmethod
 def        lowerCamelCase      (						cls	,				__UpperCAmelCase	,				**__UpperCAmelCase				):



    '''simple docstring'''
    cls._set_token_in_kwargs(__UpperCAmelCase				)

    __lowerCamelCase							,__lowerCamelCase													=    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													=    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     (	lowerCAmelCase__   ):
 lowerCAmelCase__       					=  """instructblip_qformer"""




 def __init__(						self	,				__UpperCAmelCase=30522	,				__UpperCAmelCase=768	,				__UpperCAmelCase=12	,				__UpperCAmelCase=12	,				__UpperCAmelCase=3072	,				__UpperCAmelCase="gelu"	,				__UpperCAmelCase=0.1	,				__UpperCAmelCase=0.1	,				__UpperCAmelCase=512	,				__UpperCAmelCase=0.02	,				__UpperCAmelCase=1E-1_2	,				__UpperCAmelCase=0	,				__UpperCAmelCase="absolute"	,				__UpperCAmelCase=2	,				__UpperCAmelCase=1408	,				**__UpperCAmelCase	,				):



    '''simple docstring'''
    super().__init__(pad_token_id=__UpperCAmelCase	,				**__UpperCAmelCase				)

    __lowerCamelCase													=    vocab_size
    __lowerCamelCase													=    hidden_size
    __lowerCamelCase													=    num_hidden_layers
    __lowerCamelCase													=    num_attention_heads
    __lowerCamelCase													=    hidden_act
    __lowerCamelCase													=    intermediate_size
    __lowerCamelCase													=    hidden_dropout_prob
    __lowerCamelCase													=    attention_probs_dropout_prob
    __lowerCamelCase													=    max_position_embeddings
    __lowerCamelCase													=    initializer_range
    __lowerCamelCase													=    layer_norm_eps
    __lowerCamelCase													=    position_embedding_type
    __lowerCamelCase													=    cross_attention_frequency
    __lowerCamelCase													=    encoder_hidden_size




 @classmethod
 def        lowerCamelCase      (						cls	,				__UpperCAmelCase	,				**__UpperCAmelCase				):



    '''simple docstring'''
    cls._set_token_in_kwargs(__UpperCAmelCase				)

    __lowerCamelCase							,__lowerCamelCase													=    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													=    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     (	lowerCAmelCase__   ):
 lowerCAmelCase__       					=  """instructblip"""
 lowerCAmelCase__       					=  True




 def __init__(						self	,				__UpperCAmelCase=None	,				__UpperCAmelCase=None	,				__UpperCAmelCase=None	,				__UpperCAmelCase=32	,				**__UpperCAmelCase				):



    '''simple docstring'''
    super().__init__(**__UpperCAmelCase				)

    if vision_config is None:
       __lowerCamelCase													=    {}
       logger.info('''vision_config is None. initializing the InstructBlipVisionConfig with default values.'''				)

    if qformer_config is None:
       __lowerCamelCase													=    {}
       logger.info('''qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.'''				)

    if text_config is None:
       __lowerCamelCase													=    {}
       logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).'''				)

    __lowerCamelCase													=    InstructBlipVisionConfig(**__UpperCAmelCase				)
    __lowerCamelCase													=    InstructBlipQFormerConfig(**__UpperCAmelCase				)
    __lowerCamelCase													=    text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
    __lowerCamelCase													=    CONFIG_MAPPING[text_model_type](**__UpperCAmelCase				)

    __lowerCamelCase													=    self.text_config.tie_word_embeddings
    __lowerCamelCase													=    self.text_config.is_encoder_decoder

    __lowerCamelCase													=    num_query_tokens
    __lowerCamelCase													=    self.vision_config.hidden_size
    __lowerCamelCase													=    self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
    __lowerCamelCase													=    1.0
    __lowerCamelCase													=    0.02




 @classmethod
 def        lowerCamelCase      (						cls	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				**__UpperCAmelCase	,				):



    '''simple docstring'''
    return cls(
        vision_config=vision_config.to_dict()	,				qformer_config=qformer_config.to_dict()	,				text_config=text_config.to_dict()	,				**__UpperCAmelCase	,				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    copy.deepcopy(self.__dict__				)
    __lowerCamelCase													=    self.vision_config.to_dict()
    __lowerCamelCase													=    self.qformer_config.to_dict()
    __lowerCamelCase													=    self.text_config.to_dict()
    __lowerCamelCase													=    self.__class__.model_type
    return output











import math
import os
from copy import deepcopy

import datasets
import evaluate
import torch
import transformers
from datasets import load_dataset
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer

from accelerate import Accelerator
from accelerate.test_utils import RegressionDataset, RegressionModel
from accelerate.utils import is_tpu_available, set_seed


a_			=					"""true"""





def 		a__			(		_UpperCamelCase			: Union[str, Any] ,_UpperCamelCase			: List[str]=82 ,_UpperCamelCase			: Optional[Any]=16							):
   set_seed(42							)
   __lowerCamelCase													=    RegressionModel()
   __lowerCamelCase													=    deepcopy(_UpperCamelCase							)
   __lowerCamelCase													=    RegressionDataset(length=_UpperCamelCase							)
   __lowerCamelCase													=    DataLoader(_UpperCamelCase ,batch_size=_UpperCamelCase							)
   model.to(accelerator.device							)
   __lowerCamelCase							,__lowerCamelCase													=    accelerator.prepare(_UpperCamelCase ,_UpperCamelCase							)
   return model, ddp_model, dataloader





def 		a__			(		_UpperCamelCase			: Accelerator ,_UpperCamelCase			: str=False							):
   __lowerCamelCase													=    AutoTokenizer.from_pretrained('''hf-internal-testing/mrpc-bert-base-cased'''							)
   __lowerCamelCase													=    load_dataset('''glue''' ,'''mrpc''' ,split='''validation'''							)

   def tokenize_function(_UpperCamelCase			: int							):
      __lowerCamelCase													=    tokenizer(examples['''sentence1'''] ,examples['''sentence2'''] ,truncation=_UpperCamelCase ,max_length=_UpperCamelCase							)
      return outputs

   with accelerator.main_process_first():
      __lowerCamelCase													=    dataset.map(
          _UpperCamelCase ,batched=_UpperCamelCase ,remove_columns=['''idx''', '''sentence1''', '''sentence2'''] ,)

   __lowerCamelCase													=    tokenized_datasets.rename_column('''label''' ,'''labels'''							)

   def collate_fn(_UpperCamelCase			: Any							):
      if use_longest:
         return tokenizer.pad(_UpperCamelCase ,padding='''longest''' ,return_tensors='''pt'''							)
      return tokenizer.pad(_UpperCamelCase ,padding='''max_length''' ,max_length=1_28 ,return_tensors='''pt'''							)

   return DataLoader(_UpperCamelCase ,shuffle=_UpperCamelCase ,collate_fn=_UpperCamelCase ,batch_size=16							)





def 		a__			(		_UpperCamelCase			: Dict ,_UpperCamelCase			: List[str]							):
   __lowerCamelCase													=    Accelerator(dispatch_batches=_UpperCamelCase ,split_batches=_UpperCamelCase							)
   __lowerCamelCase													=    get_dataloader(_UpperCamelCase ,not dispatch_batches							)
   __lowerCamelCase													=    AutoModelForSequenceClassification.from_pretrained(
       '''hf-internal-testing/mrpc-bert-base-cased''' ,return_dict=_UpperCamelCase							)
   __lowerCamelCase							,__lowerCamelCase													=    accelerator.prepare(_UpperCamelCase ,_UpperCamelCase							)
   return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator





def 		a__			(		_UpperCamelCase			: Dict ,_UpperCamelCase			: Optional[Any] ,_UpperCamelCase			: Union[str, Any]							):
   __lowerCamelCase													=    []
   for batch in dataloader:
      __lowerCamelCase							,__lowerCamelCase													=    batch.values()
      with torch.no_grad():
         __lowerCamelCase													=    model(_UpperCamelCase							)
         __lowerCamelCase							,__lowerCamelCase													=    accelerator.gather_for_metrics((logit, target)							)
         logits_and_targets.append((logit, target)							)
   __lowerCamelCase							,__lowerCamelCase													=    [], []
   for logit, targ in logits_and_targets:
      logits.append(_UpperCamelCase							)
      targs.append(_UpperCamelCase							)
   __lowerCamelCase							,__lowerCamelCase													=    torch.cat(_UpperCamelCase							), torch.cat(_UpperCamelCase							)
   return logits, targs





def 		a__			(		_UpperCamelCase			: Accelerator ,_UpperCamelCase			: List[Any]=82 ,_UpperCamelCase			: str=False ,_UpperCamelCase			: List[str]=False ,_UpperCamelCase			: Optional[int]=16							):
   __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    get_basic_setup(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase							)
   __lowerCamelCase							,__lowerCamelCase													=    generate_predictions(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase							)
   assert (
       len(_UpperCamelCase							) == num_samples
   ), F"""Unexpected number of inputs:\n    Expected: {num_samples}\n    Actual: {len(_UpperCamelCase							)}"""





def 		a__			(		_UpperCamelCase			: bool = False ,_UpperCamelCase			: bool = False							):
   __lowerCamelCase													=    evaluate.load('''glue''' ,'''mrpc'''							)
   __lowerCamelCase							,__lowerCamelCase													=    get_mrpc_setup(_UpperCamelCase ,_UpperCamelCase							)
   # First do baseline
   __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    setup['''no''']
   model.to(_UpperCamelCase							)
   model.eval()
   for batch in dataloader:
      batch.to(_UpperCamelCase							)
      with torch.inference_mode():
         __lowerCamelCase													=    model(**_UpperCamelCase							)
      __lowerCamelCase													=    outputs.logits.argmax(dim=-1							)
      metric.add_batch(predictions=_UpperCamelCase ,references=batch['''labels''']							)
   __lowerCamelCase													=    metric.compute()

   # Then do distributed
   __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    setup['''ddp''']
   model.eval()
   for batch in dataloader:
      with torch.inference_mode():
         __lowerCamelCase													=    model(**_UpperCamelCase							)
      __lowerCamelCase													=    outputs.logits.argmax(dim=-1							)
      __lowerCamelCase													=    batch['''labels''']
      __lowerCamelCase							,__lowerCamelCase													=    accelerator.gather_for_metrics((preds, references)							)
      metric.add_batch(predictions=_UpperCamelCase ,references=_UpperCamelCase							)
   __lowerCamelCase													=    metric.compute()

   for key in "accuracy f1".split():
      assert math.isclose(
          baseline[key] ,distributed[key]							), F"""Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n"""





def 		a__			(		):
   __lowerCamelCase													=    Accelerator(split_batches=_UpperCamelCase ,dispatch_batches=_UpperCamelCase							)
   if accelerator.is_local_main_process:
      datasets.utils.logging.set_verbosity_warning()
      transformers.utils.logging.set_verbosity_warning()
   else:
      datasets.utils.logging.set_verbosity_error()
      transformers.utils.logging.set_verbosity_error()
   # These are a bit slower so they should only be ran on the GPU or TPU
   if torch.cuda.is_available() or is_tpu_available():
      if accelerator.is_local_main_process:
         print('''**Testing gather_for_metrics**'''							)
      for split_batches in [True, False]:
         for dispatch_batches in [True, False]:
            if accelerator.is_local_main_process:
               print(F"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`"""							)
            test_mrpc(_UpperCamelCase ,_UpperCamelCase							)
            accelerator.state._reset_state()
   if accelerator.is_local_main_process:
      print('''**Test torch metrics**'''							)
   for split_batches in [True, False]:
      for dispatch_batches in [True, False]:
         __lowerCamelCase													=    Accelerator(split_batches=_UpperCamelCase ,dispatch_batches=_UpperCamelCase							)
         if accelerator.is_local_main_process:
            print(F"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99"""							)
         test_torch_metrics(_UpperCamelCase ,99							)
         accelerator.state._reset_state()
   if accelerator.is_local_main_process:
      print('''**Test last batch is not dropped when perfectly divisible**'''							)
   __lowerCamelCase													=    Accelerator()
   test_torch_metrics(_UpperCamelCase ,5_12							)
   accelerator.state._reset_state()





def 		a__			(		_UpperCamelCase			: Optional[int]							):
   # For xla_spawn (TPUs)
   main()


if __name__ == "__main__":
  main()






