import argparse
import os

# New Code #
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.utils import find_executable_batch_size


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to ensure out-of-memory errors never
# interrupt training, and builds off the `nlp_example.py` script.
#
# 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)
#
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# 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
#
########################################################################


__magic_name__								=16
__magic_name__								=32







def  __UpperCamelCase    (						A ,							A = 16							):
					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=__UpperCamelCase ,							max_length=__UpperCamelCase							)
										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(
										    __UpperCamelCase ,							batched=__UpperCamelCase ,							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__										=      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":
															UpperCamelCase__										=      16
										elif accelerator.mixed_precision != "no":
															UpperCamelCase__										=      8
										else:
															UpperCamelCase__										=      None

										return tokenizer.pad(
										    __UpperCamelCase ,							padding='''longest''' ,							max_length=__UpperCamelCase ,							pad_to_multiple_of=__UpperCamelCase ,							return_tensors='''pt''' ,							)

					# Instantiate dataloaders.
					UpperCamelCase__										=      DataLoader(
					    tokenized_datasets['''train'''] ,							shuffle=__UpperCamelCase ,							collate_fn=__UpperCamelCase ,							batch_size=__UpperCamelCase							)
					UpperCamelCase__										=      DataLoader(
					    tokenized_datasets['''validation'''] ,							shuffle=__UpperCamelCase ,							collate_fn=__UpperCamelCase ,							batch_size=__UpperCamelCase							)

					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

					__magic_name__								=mocked_dataloaders  # noqa: F811







def  __UpperCamelCase    (						A ,							A							):
					# For testing only
					if os.environ.get('''TESTING_MOCKED_DATALOADERS''' ,							__UpperCamelCase							) == "1":
										UpperCamelCase__										=      2
					# Initialize accelerator
					UpperCamelCase__										=      Accelerator(cpu=args.cpu ,							mixed_precision=args.mixed_precision							)
					# 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'''							)

					# New Code #
					# We now can define an inner training loop function. It should take a batch size as the only parameter,
					# and build the dataloaders in there.
					# It also gets our decorator
					@find_executable_batch_size(starting_batch_size=__UpperCamelCase							)
					def inner_training_loop(A							):
										# And now just move everything below under this function
										# We need to bring in the Accelerator object from earlier
										nonlocal accelerator
										# And reset all of its attributes that could hold onto any memory:
										accelerator.free_memory()

										# Then we can declare the model, optimizer, and everything else:
										set_seed(__UpperCamelCase							)

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

										# 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=__UpperCamelCase							)
										UpperCamelCase__						,       UpperCamelCase__										=      get_dataloaders(__UpperCamelCase ,							__UpperCamelCase							)

										# Instantiate scheduler
										UpperCamelCase__										=      get_linear_schedule_with_warmup(
										    optimizer=__UpperCamelCase ,							num_warmup_steps=100 ,							num_training_steps=(len(__UpperCamelCase							) * 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(
										    __UpperCamelCase ,							__UpperCamelCase ,							__UpperCamelCase ,							__UpperCamelCase ,							__UpperCamelCase							)

										# Now we train the model
										for epoch in range(__UpperCamelCase							):
															model.train()
															for step, batch in enumerate(__UpperCamelCase							):
																				# We could avoid this line since we set the accelerator with `device_placement=True`.
																				batch.to(accelerator.device							)
																				UpperCamelCase__										=      model(**__UpperCamelCase							)
																				UpperCamelCase__										=      outputs.loss
																				accelerator.backward(__UpperCamelCase							)
																				optimizer.step()
																				lr_scheduler.step()
																				optimizer.zero_grad()

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

															UpperCamelCase__										=      metric.compute()
															# Use accelerator.print to print only on the main process.
															accelerator.print(f"epoch {epoch}:" ,							__UpperCamelCase							)

    # New Code #
    # And call it at the end with no arguments
    # Note: You could also refactor this outside of your training loop function
					inner_training_loop()







def  __UpperCamelCase    (						):
					UpperCamelCase__										=      argparse.ArgumentParser(description='''Simple example of training script.'''							)
					parser.add_argument(
					    '''--mixed_precision''' ,							type=__UpperCamelCase ,							default=__UpperCamelCase ,							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.''' ,							)
					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''': 42, '''batch_size''': 16}
					training_function(__UpperCamelCase ,							__UpperCamelCase							)


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



