import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

# Register SEW's fairseq modules
from sew_asapp import tasks  # noqa: F401

from transformers import (
    SEWConfig,
    SEWForCTC,
    SEWModel,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
    logging,
)


logging.set_verbosity_info()
__magic_name__								=logging.get_logger(__name__)

__magic_name__								={
    '''post_extract_proj''': '''feature_projection''',
    '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''',
    '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''',
    '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''',
    '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''',
    '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''',
    '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''',
    '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''',
    '''fc2''': '''encoder.layers.*.feed_forward.output_dense''',
    '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''',
    '''encoder.upsample.0''': '''encoder.upsample.projection''',
    '''encoder.layer_norm''': '''encoder.layer_norm''',
    '''w2v_model.layer_norm''': '''layer_norm''',
    '''w2v_encoder.proj''': '''lm_head''',
    '''mask_emb''': '''masked_spec_embed''',
}







def  __UpperCamelCase    (						A ,							A ,							A ,							A ,							A							):
     for attribute in key.split('''.'''							):
          UpperCamelCase__										=      getattr(A ,							A							)

     if weight_type is not None:
          UpperCamelCase__										=      getattr(A ,							A							).shape
     else:
          UpperCamelCase__										=      hf_pointer.shape

     assert hf_shape == value.shape, (
         f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
         f" {value.shape} for {full_name}"
     )

     if weight_type == "weight":
          UpperCamelCase__										=      value
     elif weight_type == "weight_g":
          UpperCamelCase__										=      value
     elif weight_type == "weight_v":
          UpperCamelCase__										=      value
     elif weight_type == "bias":
          UpperCamelCase__										=      value
     else:
          UpperCamelCase__										=      value

     logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}."							)







def  __UpperCamelCase    (						A ,							A ,							A							):
     UpperCamelCase__										=      []
     UpperCamelCase__										=      fairseq_model.state_dict()

     UpperCamelCase__										=      hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor

     for name, value in fairseq_dict.items():
          UpperCamelCase__										=      False
          if "conv_layers" in name:
               load_conv_layer(
                   A ,							A ,							A ,							A ,							hf_model.config.feat_extract_norm == '''group''' ,							)
               UpperCamelCase__										=      True
          else:
               for key, mapped_key in MAPPING.items():
                    UpperCamelCase__										=      '''sew.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key

                    if key in name or key.split('''w2v_model.'''							)[-1] == name.split('''.'''							)[0]:
                         UpperCamelCase__										=      True
                         if "*" in mapped_key:
                              UpperCamelCase__										=      name.split(A							)[0].split('''.'''							)[-2]
                              UpperCamelCase__										=      mapped_key.replace('''*''' ,							A							)
                         if "weight_g" in name:
                              UpperCamelCase__										=      '''weight_g'''
                         elif "weight_v" in name:
                              UpperCamelCase__										=      '''weight_v'''
                         elif "weight" in name:
                              UpperCamelCase__										=      '''weight'''
                         elif "bias" in name:
                              UpperCamelCase__										=      '''bias'''
                         else:
                              UpperCamelCase__										=      None
                         set_recursively(A ,							A ,							A ,							A ,							A							)
                    continue
          if not is_used:
               unused_weights.append(A							)

     logger.warning(f"Unused weights: {unused_weights}"							)







def  __UpperCamelCase    (						A ,							A ,							A ,							A ,							A							):
     UpperCamelCase__										=      full_name.split('''conv_layers.'''							)[-1]
     UpperCamelCase__										=      name.split('''.'''							)
     UpperCamelCase__										=      int(items[0]							)
     UpperCamelCase__										=      int(items[1]							)

     if type_id == 0:
          if "bias" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
                   f"{full_name} has size {value.shape}, but"
                   f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
               )
               UpperCamelCase__										=      value
               logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}."							)
          elif "weight" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
                   f"{full_name} has size {value.shape}, but"
                   f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
               )
               UpperCamelCase__										=      value
               logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}."							)
     elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
          if "bias" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
                   f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"
                   " found."
               )
               UpperCamelCase__										=      value
               logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."							)
          elif "weight" in name:
               assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
                   f"{full_name} has size {value.shape}, but"
                   f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
               )
               UpperCamelCase__										=      value
               logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."							)
     else:
          unused_weights.append(A							)







def  __UpperCamelCase    (						A ,							A							):
     UpperCamelCase__										=      SEWConfig()
     if is_finetuned:
          UpperCamelCase__										=      model.wav_encoder.wav_model.cfg
     else:
          UpperCamelCase__										=      model.cfg

     UpperCamelCase__										=      fs_config.conv_bias
     UpperCamelCase__										=      eval(fs_config.conv_feature_layers							)
     UpperCamelCase__										=      [x[0] for x in conv_layers]
     UpperCamelCase__										=      [x[1] for x in conv_layers]
     UpperCamelCase__										=      [x[2] for x in conv_layers]
     UpperCamelCase__										=      '''gelu'''
     UpperCamelCase__										=      '''layer''' if fs_config.extractor_mode == '''layer_norm''' else '''group'''
     UpperCamelCase__										=      0.0
     UpperCamelCase__										=      fs_config.activation_fn.name
     UpperCamelCase__										=      fs_config.encoder_embed_dim
     UpperCamelCase__										=      0.02
     UpperCamelCase__										=      fs_config.encoder_ffn_embed_dim
     UpperCamelCase__										=      1e-5
     UpperCamelCase__										=      fs_config.encoder_layerdrop
     UpperCamelCase__										=      fs_config.encoder_attention_heads
     UpperCamelCase__										=      fs_config.conv_pos_groups
     UpperCamelCase__										=      fs_config.conv_pos
     UpperCamelCase__										=      len(A							)
     UpperCamelCase__										=      fs_config.encoder_layers
     UpperCamelCase__										=      fs_config.squeeze_factor

     # take care of any params that are overridden by the Wav2VecCtc model
     if is_finetuned:
          UpperCamelCase__										=      model.cfg
          UpperCamelCase__										=      fs_config.final_dropout
          UpperCamelCase__										=      fs_config.layerdrop
     UpperCamelCase__										=      fs_config.activation_dropout
     UpperCamelCase__										=      fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
     UpperCamelCase__										=      fs_config.attention_dropout
     UpperCamelCase__										=      fs_config.dropout_input
     UpperCamelCase__										=      fs_config.dropout
     UpperCamelCase__										=      fs_config.mask_channel_length
     UpperCamelCase__										=      fs_config.mask_channel_prob
     UpperCamelCase__										=      fs_config.mask_length
     UpperCamelCase__										=      fs_config.mask_prob

     UpperCamelCase__										=      '''Wav2Vec2FeatureExtractor'''
     UpperCamelCase__										=      '''Wav2Vec2CTCTokenizer'''

     return config







@torch.no_grad()
def  __UpperCamelCase    (						A ,							A ,							A=None ,							A=None ,							A=True							):

     if is_finetuned:
          UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__										=      fairseq.checkpoint_utils.load_model_ensemble_and_task(
              [checkpoint_path] ,							arg_overrides={'''data''': '''/'''.join(dict_path.split('''/'''							)[:-1]							)}							)
     else:
          UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__										=      fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]							)

     if config_path is not None:
          UpperCamelCase__										=      SEWConfig.from_pretrained(A							)
     else:
          UpperCamelCase__										=      convert_config(model[0] ,							A							)
     UpperCamelCase__										=      model[0].eval()

     UpperCamelCase__										=      True if config.feat_extract_norm == '''layer''' else False
     UpperCamelCase__										=      WavaVecaFeatureExtractor(
         feature_size=1 ,							sampling_rate=16000 ,							padding_value=0 ,							do_normalize=A ,							return_attention_mask=A ,							)

     if is_finetuned:
          if dict_path:
               UpperCamelCase__										=      Dictionary.load(A							)

               # important change bos & pad token id since CTC symbol is <pad> and
               # not <s> as in fairseq
               UpperCamelCase__										=      target_dict.pad_index
               UpperCamelCase__										=      target_dict.bos_index
               UpperCamelCase__										=      target_dict.pad_index
               UpperCamelCase__										=      target_dict.bos_index
               UpperCamelCase__										=      target_dict.eos_index
               UpperCamelCase__										=      len(target_dict.symbols							)
               UpperCamelCase__										=      os.path.join(A ,							'''vocab.json'''							)
               if not os.path.isdir(A							):
                    logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(A							)							)
                    return
               os.makedirs(A ,							exist_ok=A							)
               with open(A ,							'''w''' ,							encoding='''utf-8'''							) as vocab_handle:
                    json.dump(target_dict.indices ,							A							)
               UpperCamelCase__										=      WavaVecaCTCTokenizer(
                   A ,							unk_token=target_dict.unk_word ,							pad_token=target_dict.pad_word ,							bos_token=target_dict.bos_word ,							eos_token=target_dict.eos_word ,							word_delimiter_token='''|''' ,							do_lower_case=A ,							)
               UpperCamelCase__										=      WavaVecaProcessor(feature_extractor=A ,							tokenizer=A							)
               processor.save_pretrained(A							)

          UpperCamelCase__										=      SEWForCTC(A							)
     else:
          UpperCamelCase__										=      SEWModel(A							)
          feature_extractor.save_pretrained(A							)

     recursively_load_weights(A ,							A ,							A							)

     hf_model.save_pretrained(A							)


if __name__ == "__main__":
     __magic_name__								=argparse.ArgumentParser()
     parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
     parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
     parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''')
     parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
     parser.add_argument(
         '''--is_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not'''
     )
     __magic_name__								=parser.parse_args()
     convert_sew_checkpoint(
         args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned
     )




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



