import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import numpy as np
import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForMaskedImageModeling,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
__magic_name__								=logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''')

__magic_name__								=list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys())
__magic_name__								=tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



@dataclass
class     _A   :
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(
      default="cifar10"	, metadata={"help": "Name of a dataset from the datasets package"}							)
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(
      default=__UpperCamelCase	, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}							)
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(
      default=__UpperCamelCase	, metadata={"help": "The column name of the images in the files. If not set, will try to use 'image' or 'img'."}	, )
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(default=__UpperCamelCase	, metadata={"help": "A folder containing the training data."}							)
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(default=__UpperCamelCase	, metadata={"help": "A folder containing the validation data."}							)
  SCREAMING_SNAKE_CASE_	:	Optional[float]						=field(
      default=0.1_5	, metadata={"help": "Percent to split off of train for validation."}							)
  SCREAMING_SNAKE_CASE_	:	int						=field(default=32	, metadata={"help": "The size of the square patches to use for masking."}							)
  SCREAMING_SNAKE_CASE_	:	float						=field(
      default=0.6	, metadata={"help": "Percentage of patches to mask."}	, )
  SCREAMING_SNAKE_CASE_	:	Optional[int]						=field(
      default=__UpperCamelCase	, metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of training examples to this "
              "value if set."
          )
      }	, )
  SCREAMING_SNAKE_CASE_	:	Optional[int]						=field(
      default=__UpperCamelCase	, metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
              "value if set."
          )
      }	, )






  def 		_a					(self	)		->      Any:





       '''simple docstring'''





       UpperCamelCase__										=      {}
       if self.train_dir is not None:
            UpperCamelCase__										=      self.train_dir
       if self.validation_dir is not None:
            UpperCamelCase__										=      self.validation_dir
       UpperCamelCase__										=      data_files if data_files else None



@dataclass
class     _A   :
  SCREAMING_SNAKE_CASE_	:	str						=field(
      default=__UpperCamelCase	, metadata={
          "help": (
              "The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a "
              "checkpoint identifier on the hub. "
              "Don't set if you want to train a model from scratch."
          )
      }	, )
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(
      default=__UpperCamelCase	, metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(__UpperCamelCase							)}	, )
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(
      default=__UpperCamelCase	, metadata={"help": "Pretrained config name or path if not the same as model_name"}							)
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(
      default=__UpperCamelCase	, metadata={
          "help": (
              "Override some existing default config settings when a model is trained from scratch. Example: "
              "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
          )
      }	, )
  SCREAMING_SNAKE_CASE_	:	Optional[str]						=field(
      default=__UpperCamelCase	, metadata={"help": "Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"}	, )
  SCREAMING_SNAKE_CASE_	:	str						=field(
      default="main"	, metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}	, )
  SCREAMING_SNAKE_CASE_	:	str						=field(default=__UpperCamelCase	, metadata={"help": "Name or path of preprocessor config."}							)
  SCREAMING_SNAKE_CASE_	:	bool						=field(
      default=__UpperCamelCase	, metadata={
          "help": (
              "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
              "with private models)."
          )
      }	, )
  SCREAMING_SNAKE_CASE_	:	Optional[int]						=field(
      default=__UpperCamelCase	, metadata={
          "help": (
              "The size (resolution) of each image. If not specified, will use `image_size` of the configuration."
          )
      }	, )
  SCREAMING_SNAKE_CASE_	:	Optional[int]						=field(
      default=__UpperCamelCase	, metadata={
          "help": (
              "The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration."
          )
      }	, )
  SCREAMING_SNAKE_CASE_	:	Optional[int]						=field(
      default=__UpperCamelCase	, metadata={"help": "Stride to use for the encoder."}	, )



class     _A   :






  def __init__(self   ,				SCREAMING_SNAKE_CASE_=192   ,				SCREAMING_SNAKE_CASE_=32   ,				SCREAMING_SNAKE_CASE_=4   ,				SCREAMING_SNAKE_CASE_=0.6	)		->      Optional[Any]:





       '''simple docstring'''





       UpperCamelCase__										=      input_size
       UpperCamelCase__										=      mask_patch_size
       UpperCamelCase__										=      model_patch_size
       UpperCamelCase__										=      mask_ratio

       if self.input_size % self.mask_patch_size != 0:
            raise ValueError('''Input size must be divisible by mask patch size'''	)
       if self.mask_patch_size % self.model_patch_size != 0:
            raise ValueError('''Mask patch size must be divisible by model patch size'''	)

       UpperCamelCase__										=      self.input_size // self.mask_patch_size
       UpperCamelCase__										=      self.mask_patch_size // self.model_patch_size

       UpperCamelCase__										=      self.rand_size**2
       UpperCamelCase__										=      int(np.ceil(self.token_count * self.mask_ratio	)	)






  def __call__(self	)		->      Optional[int]:





       '''simple docstring'''





       UpperCamelCase__										=      np.random.permutation(self.token_count	)[: self.mask_count]
       UpperCamelCase__										=      np.zeros(self.token_count   ,				dtype=SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      1

       UpperCamelCase__										=      mask.reshape((self.rand_size, self.rand_size)	)
       UpperCamelCase__										=      mask.repeat(self.scale   ,				axis=0	).repeat(self.scale   ,				axis=1	)

       return torch.tensor(mask.flatten()	)







def  __UpperCamelCase    (						A							):
     UpperCamelCase__										=      torch.stack([example['''pixel_values'''] for example in examples]							)
     UpperCamelCase__										=      torch.stack([example['''mask'''] for example in examples]							)
     return {"pixel_values": pixel_values, "bool_masked_pos": mask}







def  __UpperCamelCase    (						):
     # See all possible arguments in src/transformers/training_args.py
     # or by passing the --help flag to this script.
     # We now keep distinct sets of args, for a cleaner separation of concerns.

     UpperCamelCase__										=      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)
     if len(sys.argv							) == 2 and sys.argv[1].endswith('''.json'''							):
          # If we pass only one argument to the script and it's the path to a json file,
          # let's parse it to get our arguments.
          UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__										=      parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]							)							)
     else:
          UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__										=      parser.parse_args_into_dataclasses()

     # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
     # information sent is the one passed as arguments along with your Python/PyTorch versions.
     send_example_telemetry('''run_mim''' ,							A ,							A							)

     # Setup logging
     logging.basicConfig(
         format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' ,							datefmt='''%m/%d/%Y %H:%M:%S''' ,							handlers=[logging.StreamHandler(sys.stdout							)] ,							)

     if training_args.should_log:
          # The default of training_args.log_level is passive, so we set log level at info here to have that default.
          transformers.utils.logging.set_verbosity_info()

     UpperCamelCase__										=      training_args.get_process_log_level()
     logger.setLevel(A							)
     transformers.utils.logging.set_verbosity(A							)
     transformers.utils.logging.enable_default_handler()
     transformers.utils.logging.enable_explicit_format()

     # Log on each process the small summary:
     logger.warning(
         f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
         + f"distributed training: {bool(training_args.local_rank != -1							)}, 16-bits training: {training_args.fpaa}"							)
     logger.info(f"Training/evaluation parameters {training_args}"							)

     # Detecting last checkpoint.
     UpperCamelCase__										=      None
     if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
          UpperCamelCase__										=      get_last_checkpoint(training_args.output_dir							)
          if last_checkpoint is None and len(os.listdir(training_args.output_dir							)							) > 0:
               raise ValueError(
                   f"Output directory ({training_args.output_dir}) already exists and is not empty. "
                   '''Use --overwrite_output_dir to overcome.'''							)
          elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
               logger.info(
                   f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
                   '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''							)

    # Initialize our dataset.
     UpperCamelCase__										=      load_dataset(
         data_args.dataset_name ,							data_args.dataset_config_name ,							data_files=data_args.data_files ,							cache_dir=model_args.cache_dir ,							use_auth_token=True if model_args.use_auth_token else None ,							)

     # If we don't have a validation split, split off a percentage of train as validation.
     UpperCamelCase__										=      None if '''validation''' in ds.keys() else data_args.train_val_split
     if isinstance(data_args.train_val_split ,							A							) and data_args.train_val_split > 0.0:
          UpperCamelCase__										=      ds['''train'''].train_test_split(data_args.train_val_split							)
          UpperCamelCase__										=      split['''train''']
          UpperCamelCase__										=      split['''test''']

     # Create config
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.
     UpperCamelCase__										=      {
         '''cache_dir''': model_args.cache_dir,
         '''revision''': model_args.model_revision,
         '''use_auth_token''': True if model_args.use_auth_token else None,
     }
     if model_args.config_name_or_path:
          UpperCamelCase__										=      AutoConfig.from_pretrained(model_args.config_name_or_path ,							**A							)
     elif model_args.model_name_or_path:
          UpperCamelCase__										=      AutoConfig.from_pretrained(model_args.model_name_or_path ,							**A							)
     else:
          UpperCamelCase__										=      CONFIG_MAPPING[model_args.model_type]()
          logger.warning('''You are instantiating a new config instance from scratch.'''							)
          if model_args.config_overrides is not None:
               logger.info(f"Overriding config: {model_args.config_overrides}"							)
               config.update_from_string(model_args.config_overrides							)
               logger.info(f"New config: {config}"							)

    # make sure the decoder_type is "simmim" (only relevant for BEiT)
     if hasattr(A ,							'''decoder_type'''							):
          UpperCamelCase__										=      '''simmim'''

     # adapt config
     UpperCamelCase__										=      model_args.image_size if model_args.image_size is not None else config.image_size
     UpperCamelCase__										=      model_args.patch_size if model_args.patch_size is not None else config.patch_size
     UpperCamelCase__										=      (
         model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride
     )

     config.update(
         {
             '''image_size''': model_args.image_size,
             '''patch_size''': model_args.patch_size,
             '''encoder_stride''': model_args.encoder_stride,
         }							)

     # create image processor
     if model_args.image_processor_name:
          UpperCamelCase__										=      AutoImageProcessor.from_pretrained(model_args.image_processor_name ,							**A							)
     elif model_args.model_name_or_path:
          UpperCamelCase__										=      AutoImageProcessor.from_pretrained(model_args.model_name_or_path ,							**A							)
     else:
          UpperCamelCase__										=      {
              conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items()
          }
          UpperCamelCase__										=      IMAGE_PROCESSOR_TYPES[model_args.model_type]()

     # create model
     if model_args.model_name_or_path:
          UpperCamelCase__										=      AutoModelForMaskedImageModeling.from_pretrained(
              model_args.model_name_or_path ,							from_tf=bool('''.ckpt''' in model_args.model_name_or_path							) ,							config=A ,							cache_dir=model_args.cache_dir ,							revision=model_args.model_revision ,							use_auth_token=True if model_args.use_auth_token else None ,							)
     else:
          logger.info('''Training new model from scratch'''							)
          UpperCamelCase__										=      AutoModelForMaskedImageModeling.from_config(A							)

     if training_args.do_train:
          UpperCamelCase__										=      ds['''train'''].column_names
     else:
          UpperCamelCase__										=      ds['''validation'''].column_names

     if data_args.image_column_name is not None:
          UpperCamelCase__										=      data_args.image_column_name
     elif "image" in column_names:
          UpperCamelCase__										=      '''image'''
     elif "img" in column_names:
          UpperCamelCase__										=      '''img'''
     else:
          UpperCamelCase__										=      column_names[0]

     # transformations as done in original SimMIM paper
     # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py
     UpperCamelCase__										=      Compose(
         [
             Lambda(lambda A							: img.convert('''RGB'''							) if img.mode != "RGB" else img							),
             RandomResizedCrop(model_args.image_size ,							scale=(0.67, 1.0) ,							ratio=(3.0 / 4.0, 4.0 / 3.0)							),
             RandomHorizontalFlip(),
             ToTensor(),
             Normalize(mean=image_processor.image_mean ,							std=image_processor.image_std							),
         ]							)

     # create mask generator
     UpperCamelCase__										=      MaskGenerator(
         input_size=model_args.image_size ,							mask_patch_size=data_args.mask_patch_size ,							model_patch_size=model_args.patch_size ,							mask_ratio=data_args.mask_ratio ,							)

     def preprocess_images(A							):
          UpperCamelCase__										=      [transforms(A							) for image in examples[image_column_name]]
          UpperCamelCase__										=      [mask_generator() for i in range(len(examples[image_column_name]							)							)]

          return examples

     if training_args.do_train:
          if "train" not in ds:
               raise ValueError('''--do_train requires a train dataset'''							)
          if data_args.max_train_samples is not None:
               UpperCamelCase__										=      ds['''train'''].shuffle(seed=training_args.seed							).select(range(data_args.max_train_samples							)							)
          # Set the training transforms
          ds["train"].set_transform(A							)

     if training_args.do_eval:
          if "validation" not in ds:
               raise ValueError('''--do_eval requires a validation dataset'''							)
          if data_args.max_eval_samples is not None:
               UpperCamelCase__										=      (
                   ds['''validation'''].shuffle(seed=training_args.seed							).select(range(data_args.max_eval_samples							)							)
               )
          # Set the validation transforms
          ds["validation"].set_transform(A							)

     # Initialize our trainer
     UpperCamelCase__										=      Trainer(
         model=A ,							args=A ,							train_dataset=ds['''train'''] if training_args.do_train else None ,							eval_dataset=ds['''validation'''] if training_args.do_eval else None ,							tokenizer=A ,							data_collator=A ,							)

     # Training
     if training_args.do_train:
          UpperCamelCase__										=      None
          if training_args.resume_from_checkpoint is not None:
               UpperCamelCase__										=      training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
               UpperCamelCase__										=      last_checkpoint
          UpperCamelCase__										=      trainer.train(resume_from_checkpoint=A							)
          trainer.save_model()
          trainer.log_metrics('''train''' ,							train_result.metrics							)
          trainer.save_metrics('''train''' ,							train_result.metrics							)
          trainer.save_state()

     # Evaluation
     if training_args.do_eval:
          UpperCamelCase__										=      trainer.evaluate()
          trainer.log_metrics('''eval''' ,							A							)
          trainer.save_metrics('''eval''' ,							A							)

     # Write model card and (optionally) push to hub
     UpperCamelCase__										=      {
         '''finetuned_from''': model_args.model_name_or_path,
         '''tasks''': '''masked-image-modeling''',
         '''dataset''': data_args.dataset_name,
         '''tags''': ['''masked-image-modeling'''],
     }
     if training_args.push_to_hub:
          trainer.push_to_hub(**A							)
     else:
          trainer.create_model_card(**A							)


if __name__ == "__main__":
     main()




import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
     from transformers import (
         FlaxBertModel,
         FlaxCLIPVisionModel,
         FlaxVisionTextDualEncoderModel,
         FlaxViTModel,
         VisionTextDualEncoderConfig,
         VisionTextDualEncoderProcessor,
     )
     from transformers.modeling_flax_pytorch_utils import (
         convert_pytorch_state_dict_to_flax,
         load_flax_weights_in_pytorch_model,
     )


if is_torch_available():
     import torch

     from transformers import VisionTextDualEncoderModel

if is_vision_available():
     from PIL import Image







def  __UpperCamelCase    (						A							):
     if isinstance(A ,							collections.abc.Iterable							):
          return x
     return (x, x)



@require_flax
class     _A   :






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      Tuple:





       '''simple docstring'''





       pass






  def 		_a					(self	)		->      Optional[int]:





       '''simple docstring'''





       pass






  def 		_a					(self	)		->      Tuple:





       '''simple docstring'''





       pass






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      Any:





       '''simple docstring'''





       UpperCamelCase__										=      np.abs((a - b)	).max()
       self.assertLessEqual(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				F"Difference between torch and flax is {diff} (>= {tol})."	)






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_=None   ,				**SCREAMING_SNAKE_CASE_	)		->      Dict:





       '''simple docstring'''





       UpperCamelCase__										=      VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      model(input_ids=SCREAMING_SNAKE_CASE_   ,				pixel_values=SCREAMING_SNAKE_CASE_   ,				attention_mask=SCREAMING_SNAKE_CASE_	)

       self.assertEqual(output['''text_embeds'''].shape   ,				(input_ids.shape[0], config.projection_dim)	)
       self.assertEqual(output['''image_embeds'''].shape   ,				(pixel_values.shape[0], config.projection_dim)	)






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_=None   ,				**SCREAMING_SNAKE_CASE_	)		->      int:





       '''simple docstring'''





       UpperCamelCase__						,       UpperCamelCase__										=      self.get_vision_text_model(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      {'''vision_model''': vision_model, '''text_model''': text_model}
       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      model(input_ids=SCREAMING_SNAKE_CASE_   ,				pixel_values=SCREAMING_SNAKE_CASE_   ,				attention_mask=SCREAMING_SNAKE_CASE_	)

       self.assertEqual(output['''text_embeds'''].shape   ,				(input_ids.shape[0], model.config.projection_dim)	)
       self.assertEqual(output['''image_embeds'''].shape   ,				(pixel_values.shape[0], model.config.projection_dim)	)






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_=None   ,				**SCREAMING_SNAKE_CASE_	)		->      List[Any]:





       '''simple docstring'''





       UpperCamelCase__						,       UpperCamelCase__										=      self.get_vision_text_model(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      {'''vision_model''': vision_model, '''text_model''': text_model}
       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      model(input_ids=SCREAMING_SNAKE_CASE_   ,				pixel_values=SCREAMING_SNAKE_CASE_   ,				attention_mask=SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      output[0]

       with tempfile.TemporaryDirectory() as tmpdirname:
            model.save_pretrained(SCREAMING_SNAKE_CASE_	)
            UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE_	)

            UpperCamelCase__										=      model(input_ids=SCREAMING_SNAKE_CASE_   ,				pixel_values=SCREAMING_SNAKE_CASE_   ,				attention_mask=SCREAMING_SNAKE_CASE_	)
            UpperCamelCase__										=      after_output[0]
            UpperCamelCase__										=      np.amax(np.abs(out_a - out_a	)	)
            self.assertLessEqual(SCREAMING_SNAKE_CASE_   ,				1E-3	)






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_=None   ,				**SCREAMING_SNAKE_CASE_	)		->      Any:





       '''simple docstring'''





       UpperCamelCase__						,       UpperCamelCase__										=      self.get_vision_text_model(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      {'''vision_model''': vision_model, '''text_model''': text_model}
       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      model(
           input_ids=SCREAMING_SNAKE_CASE_   ,				pixel_values=SCREAMING_SNAKE_CASE_   ,				attention_mask=SCREAMING_SNAKE_CASE_   ,				output_attentions=SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      output.vision_model_output.attentions
       self.assertEqual(len(SCREAMING_SNAKE_CASE_	)   ,				vision_config.num_hidden_layers	)

       # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
       UpperCamelCase__										=      to_atuple(vision_model.config.image_size	)
       UpperCamelCase__										=      to_atuple(vision_model.config.patch_size	)
       UpperCamelCase__										=      (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
       UpperCamelCase__										=      num_patches + 1
       self.assertEqual(vision_attentions[0].shape[-3:]   ,				(vision_config.num_attention_heads, seq_len, seq_len)	)

       UpperCamelCase__										=      output.text_model_output.attentions
       self.assertEqual(len(SCREAMING_SNAKE_CASE_	)   ,				text_config.num_hidden_layers	)

       self.assertEqual(
           text_attentions[0].shape[-3:]   ,				(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])   ,				)






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      List[str]:





       '''simple docstring'''





       pt_model.to(SCREAMING_SNAKE_CASE_	)
       pt_model.eval()

       # prepare inputs
       UpperCamelCase__										=      inputs_dict
       UpperCamelCase__										=      {k: torch.tensor(v.tolist()	) for k, v in flax_inputs.items()}

       with torch.no_grad():
            UpperCamelCase__										=      pt_model(**SCREAMING_SNAKE_CASE_	).to_tuple()

       UpperCamelCase__										=      fx_model(**SCREAMING_SNAKE_CASE_	).to_tuple()
       self.assertEqual(len(SCREAMING_SNAKE_CASE_	)   ,				len(SCREAMING_SNAKE_CASE_	)   ,				'''Output lengths differ between Flax and PyTorch'''	)
       for fx_output, pt_output in zip(fx_outputs[:4]   ,				pt_outputs[:4]	):
            self.assert_almost_equals(SCREAMING_SNAKE_CASE_   ,				pt_output.numpy()   ,				4E-2	)

       # PT -> Flax
       with tempfile.TemporaryDirectory() as tmpdirname:
            pt_model.save_pretrained(SCREAMING_SNAKE_CASE_	)
            UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE_   ,				from_pt=SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      fx_model_loaded(**SCREAMING_SNAKE_CASE_	).to_tuple()
       self.assertEqual(len(SCREAMING_SNAKE_CASE_	)   ,				len(SCREAMING_SNAKE_CASE_	)   ,				'''Output lengths differ between Flax and PyTorch'''	)
       for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]   ,				pt_outputs[:4]	):
            self.assert_almost_equals(SCREAMING_SNAKE_CASE_   ,				pt_output.numpy()   ,				4E-2	)

       # Flax -> PT
       with tempfile.TemporaryDirectory() as tmpdirname:
            fx_model.save_pretrained(SCREAMING_SNAKE_CASE_	)
            UpperCamelCase__										=      VisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE_   ,				from_flax=SCREAMING_SNAKE_CASE_	)

       pt_model_loaded.to(SCREAMING_SNAKE_CASE_	)
       pt_model_loaded.eval()

       with torch.no_grad():
            UpperCamelCase__										=      pt_model_loaded(**SCREAMING_SNAKE_CASE_	).to_tuple()

       self.assertEqual(len(SCREAMING_SNAKE_CASE_	)   ,				len(SCREAMING_SNAKE_CASE_	)   ,				'''Output lengths differ between Flax and PyTorch'''	)
       for fx_output, pt_output_loaded in zip(fx_outputs[:4]   ,				pt_outputs_loaded[:4]	):
            self.assert_almost_equals(SCREAMING_SNAKE_CASE_   ,				pt_output_loaded.numpy()   ,				4E-2	)






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      Tuple:





       '''simple docstring'''





       UpperCamelCase__										=      VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      VisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      convert_pytorch_state_dict_to_flax(pt_model.state_dict()   ,				SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      fx_state

       self.check_pt_flax_equivalence(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      str:





       '''simple docstring'''





       UpperCamelCase__										=      VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      VisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE_   ,				fx_model.params	)

       self.check_pt_flax_equivalence(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)






  def 		_a					(self	)		->      str:





       '''simple docstring'''





       UpperCamelCase__										=      self.prepare_config_and_inputs()
       self.check_model_from_pretrained_configs(**SCREAMING_SNAKE_CASE_	)






  def 		_a					(self	)		->      str:





       '''simple docstring'''





       UpperCamelCase__										=      self.prepare_config_and_inputs()
       self.check_vision_text_dual_encoder_from_pretrained(**SCREAMING_SNAKE_CASE_	)






  def 		_a					(self	)		->      Dict:





       '''simple docstring'''





       UpperCamelCase__										=      self.prepare_config_and_inputs()
       self.check_save_load(**SCREAMING_SNAKE_CASE_	)






  def 		_a					(self	)		->      Union[str, Any]:





       '''simple docstring'''





       UpperCamelCase__										=      self.prepare_config_and_inputs()
       self.check_vision_text_output_attention(**SCREAMING_SNAKE_CASE_	)






  @is_pt_flax_cross_test
  def 		_a					(self	)		->      str:





       '''simple docstring'''





       UpperCamelCase__										=      self.prepare_config_and_inputs()
       UpperCamelCase__										=      config_inputs_dict.pop('''vision_config'''	)
       UpperCamelCase__										=      config_inputs_dict.pop('''text_config'''	)

       UpperCamelCase__										=      config_inputs_dict

       self.check_equivalence_pt_to_flax(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)
       self.check_equivalence_flax_to_pt(SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)






  @slow
  def 		_a					(self	)		->      Tuple:





       '''simple docstring'''





       UpperCamelCase__						,       UpperCamelCase__										=      self.get_pretrained_model_and_inputs()

       UpperCamelCase__										=      model_a(**SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      outputs[0]

       with tempfile.TemporaryDirectory() as tmp_dirname:
            model_a.save_pretrained(SCREAMING_SNAKE_CASE_	)
            UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE_	)

            UpperCamelCase__										=      model_a(**SCREAMING_SNAKE_CASE_	)
            UpperCamelCase__										=      after_outputs[0]
            UpperCamelCase__										=      np.amax(np.abs(out_a - out_a	)	)
            self.assertLessEqual(SCREAMING_SNAKE_CASE_   ,				1E-5	)



@require_flax
class     _A   (    __UpperCamelCase	, unittest.TestCase							):






  def 		_a					(self	)		->      Any:





       '''simple docstring'''





       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
           '''hf-internal-testing/tiny-random-vit'''   ,				'''hf-internal-testing/tiny-bert'''   ,				vision_from_pt=SCREAMING_SNAKE_CASE_   ,				text_from_pt=SCREAMING_SNAKE_CASE_   ,				)
       UpperCamelCase__										=      13
       UpperCamelCase__										=      floats_tensor(
           [
               batch_size,
               model.config.vision_config.num_channels,
               model.config.vision_config.image_size,
               model.config.vision_config.image_size,
           ]	)
       UpperCamelCase__										=      ids_tensor([batch_size, 4]   ,				model.config.text_config.vocab_size	)
       UpperCamelCase__										=      random_attention_mask([batch_size, 4]	)
       UpperCamelCase__										=      {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

       return model, inputs






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      Union[str, Any]:





       '''simple docstring'''





       UpperCamelCase__										=      FlaxViTModel(SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      FlaxBertModel(SCREAMING_SNAKE_CASE_	)
       return vision_model, text_model






  def 		_a					(self	)		->      Optional[Any]:





       '''simple docstring'''





       UpperCamelCase__										=      FlaxViTModelTester(self	)
       UpperCamelCase__										=      FlaxBertModelTester(self	)
       UpperCamelCase__										=      vit_model_tester.prepare_config_and_inputs()
       UpperCamelCase__										=      bert_model_tester.prepare_config_and_inputs()

       UpperCamelCase__						,       UpperCamelCase__										=      vision_config_and_inputs

       UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__										=      text_config_and_inputs

       # make sure that cross attention layers are added
       return {
           "text_config": text_config,
           "vision_config": vision_config,
           "pixel_values": pixel_values,
           "attention_mask": attention_mask,
           "input_ids": input_ids,
           "token_type_ids": token_type_ids,
       }



@require_torch
class     _A   (    __UpperCamelCase	, unittest.TestCase							):






  def 		_a					(self	)		->      Dict:





       '''simple docstring'''





       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
           '''hf-internal-testing/tiny-random-clip'''   ,				'''hf-internal-testing/tiny-bert'''   ,				vision_from_pt=SCREAMING_SNAKE_CASE_   ,				text_from_pt=SCREAMING_SNAKE_CASE_   ,				)
       UpperCamelCase__										=      13
       UpperCamelCase__										=      floats_tensor(
           [
               batch_size,
               model.config.vision_config.num_channels,
               model.config.vision_config.image_size,
               model.config.vision_config.image_size,
           ]	)
       UpperCamelCase__										=      ids_tensor([batch_size, 4]   ,				model.config.text_config.vocab_size	)
       UpperCamelCase__										=      random_attention_mask([batch_size, 4]	)
       UpperCamelCase__										=      {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

       return model, inputs






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      int:





       '''simple docstring'''





       UpperCamelCase__										=      FlaxCLIPVisionModel(SCREAMING_SNAKE_CASE_	)
       UpperCamelCase__										=      FlaxBertModel(SCREAMING_SNAKE_CASE_	)
       return vision_model, text_model






  def 		_a					(self	)		->      List[Any]:





       '''simple docstring'''





       UpperCamelCase__										=      FlaxCLIPVisionModelTester(self	)
       UpperCamelCase__										=      FlaxBertModelTester(self	)
       UpperCamelCase__										=      clip_model_tester.prepare_config_and_inputs()
       UpperCamelCase__										=      bert_model_tester.prepare_config_and_inputs()

       UpperCamelCase__						,       UpperCamelCase__										=      vision_config_and_inputs

       UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__										=      text_config_and_inputs

       # make sure that cross attention layers are added
       return {
           "text_config": text_config,
           "vision_config": vision_config,
           "pixel_values": pixel_values,
           "attention_mask": attention_mask,
           "input_ids": input_ids,
           "token_type_ids": token_type_ids,
       }



@require_flax
@require_vision
class     _A   (    unittest.TestCase							):






  @slow
  def 		_a					(self	)		->      int:





       '''simple docstring'''





       UpperCamelCase__										=      FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian'''   ,				logit_scale_init_value=1.0	)
       UpperCamelCase__										=      VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian'''	)

       UpperCamelCase__										=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
       UpperCamelCase__										=      processor(
           text=['''una foto di un gatto''', '''una foto di un cane''']   ,				images=SCREAMING_SNAKE_CASE_   ,				padding=SCREAMING_SNAKE_CASE_   ,				return_tensors='''np'''	)

       UpperCamelCase__										=      model(**SCREAMING_SNAKE_CASE_	)

       # verify the logits
       self.assertEqual(outputs.logits_per_image.shape   ,				(inputs.pixel_values.shape[0], inputs.input_ids.shape[0])	)
       self.assertEqual(
           outputs.logits_per_text.shape   ,				(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])   ,				)

       UpperCamelCase__										=      np.array([[1.2284727, 0.3104122]]	)

       self.assertTrue(np.allclose(outputs.logits_per_image   ,				SCREAMING_SNAKE_CASE_   ,				atol=1E-3	)	)



