import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig
from transformers.utils import logging


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







def  __UpperCamelCase    (						A							):
					# initialize config
					if "resnet-50" in model_name:
										UpperCamelCase__										=      ResNetConfig.from_pretrained('''microsoft/resnet-50'''							)
					elif "resnet-101" in model_name:
										UpperCamelCase__										=      ResNetConfig.from_pretrained('''microsoft/resnet-101'''							)
					else:
										raise ValueError('''Model name should include either resnet50 or resnet101'''							)

					UpperCamelCase__										=      DetrConfig(use_timm_backbone=A ,							backbone_config=A							)

					# set label attributes
					UpperCamelCase__										=      '''panoptic''' in model_name
					if is_panoptic:
										UpperCamelCase__										=      250
					else:
										UpperCamelCase__										=      91
										UpperCamelCase__										=      '''huggingface/label-files'''
										UpperCamelCase__										=      '''coco-detection-id2label.json'''
										UpperCamelCase__										=      json.load(open(hf_hub_download(A ,							A ,							repo_type='''dataset'''							) ,							'''r'''							)							)
										UpperCamelCase__										=      {int(A							): v for k, v in idalabel.items()}
										UpperCamelCase__										=      idalabel
										UpperCamelCase__										=      {v: k for k, v in idalabel.items()}

					return config, is_panoptic







def  __UpperCamelCase    (						A							):
					# here we list all keys to be renamed (original name on the left, our name on the right)
					UpperCamelCase__										=      []

					# stem
					# fmt: off
					rename_keys.append(('''backbone.0.body.conv1.weight''', '''backbone.conv_encoder.model.embedder.embedder.convolution.weight''')							)
					rename_keys.append(('''backbone.0.body.bn1.weight''', '''backbone.conv_encoder.model.embedder.embedder.normalization.weight''')							)
					rename_keys.append(('''backbone.0.body.bn1.bias''', '''backbone.conv_encoder.model.embedder.embedder.normalization.bias''')							)
					rename_keys.append(('''backbone.0.body.bn1.running_mean''', '''backbone.conv_encoder.model.embedder.embedder.normalization.running_mean''')							)
					rename_keys.append(('''backbone.0.body.bn1.running_var''', '''backbone.conv_encoder.model.embedder.embedder.normalization.running_var''')							)
					# stages
					for stage_idx in range(len(config.backbone_config.depths							)							):
										for layer_idx in range(config.backbone_config.depths[stage_idx]							):
															# shortcut
															if layer_idx == 0:
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight",
																				    )							)
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight",
																				    )							)
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias",
																				    )							)
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean",
																				    )							)
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var",
																				    )							)
															# 3 convs
															for i in range(3							):
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight",
																				    )							)
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight",
																				    )							)
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias",
																				    )							)
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean",
																				    )							)
																				rename_keys.append(
																				    (
																				        f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var",
																				        f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var",
																				    )							)
    # fmt: on

					for i in range(config.encoder_layers							):
										# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
										rename_keys.append(
										    (
										        f"transformer.encoder.layers.{i}.self_attn.out_proj.weight",
										        f"encoder.layers.{i}.self_attn.out_proj.weight",
										    )							)
										rename_keys.append(
										    (f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")							)
										rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight")							)
										rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias")							)
										rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight")							)
										rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias")							)
										rename_keys.append(
										    (f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")							)
										rename_keys.append(
										    (f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias")							)
										rename_keys.append(
										    (f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight")							)
										rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias")							)
										# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
										rename_keys.append(
										    (
										        f"transformer.decoder.layers.{i}.self_attn.out_proj.weight",
										        f"decoder.layers.{i}.self_attn.out_proj.weight",
										    )							)
										rename_keys.append(
										    (f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")							)
										rename_keys.append(
										    (
										        f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight",
										        f"decoder.layers.{i}.encoder_attn.out_proj.weight",
										    )							)
										rename_keys.append(
										    (
										        f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias",
										        f"decoder.layers.{i}.encoder_attn.out_proj.bias",
										    )							)
										rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight")							)
										rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias")							)
										rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight")							)
										rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias")							)
										rename_keys.append(
										    (f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")							)
										rename_keys.append(
										    (f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias")							)
										rename_keys.append(
										    (f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")							)
										rename_keys.append(
										    (f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")							)
										rename_keys.append(
										    (f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight")							)
										rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias")							)

					# convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
					rename_keys.extend(
					    [
					        ('''input_proj.weight''', '''input_projection.weight'''),
					        ('''input_proj.bias''', '''input_projection.bias'''),
					        ('''query_embed.weight''', '''query_position_embeddings.weight'''),
					        ('''transformer.decoder.norm.weight''', '''decoder.layernorm.weight'''),
					        ('''transformer.decoder.norm.bias''', '''decoder.layernorm.bias'''),
					        ('''class_embed.weight''', '''class_labels_classifier.weight'''),
					        ('''class_embed.bias''', '''class_labels_classifier.bias'''),
					        ('''bbox_embed.layers.0.weight''', '''bbox_predictor.layers.0.weight'''),
					        ('''bbox_embed.layers.0.bias''', '''bbox_predictor.layers.0.bias'''),
					        ('''bbox_embed.layers.1.weight''', '''bbox_predictor.layers.1.weight'''),
					        ('''bbox_embed.layers.1.bias''', '''bbox_predictor.layers.1.bias'''),
					        ('''bbox_embed.layers.2.weight''', '''bbox_predictor.layers.2.weight'''),
					        ('''bbox_embed.layers.2.bias''', '''bbox_predictor.layers.2.bias'''),
					    ]							)

					return rename_keys







def  __UpperCamelCase    (						A ,							A ,							A							):
					UpperCamelCase__										=      state_dict.pop(A							)
					UpperCamelCase__										=      val







def  __UpperCamelCase    (						A ,							A=False							):
					UpperCamelCase__										=      ''''''
					if is_panoptic:
										UpperCamelCase__										=      '''detr.'''

					# first: transformer encoder
					for i in range(6							):
										# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
										UpperCamelCase__										=      state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight"							)
										UpperCamelCase__										=      state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias"							)
										# next, add query, keys and values (in that order) to the state dict
										UpperCamelCase__										=      in_proj_weight[:256, :]
										UpperCamelCase__										=      in_proj_bias[:256]
										UpperCamelCase__										=      in_proj_weight[256:512, :]
										UpperCamelCase__										=      in_proj_bias[256:512]
										UpperCamelCase__										=      in_proj_weight[-256:, :]
										UpperCamelCase__										=      in_proj_bias[-256:]
					# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
					for i in range(6							):
										# read in weights + bias of input projection layer of self-attention
										UpperCamelCase__										=      state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight"							)
										UpperCamelCase__										=      state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias"							)
										# next, add query, keys and values (in that order) to the state dict
										UpperCamelCase__										=      in_proj_weight[:256, :]
										UpperCamelCase__										=      in_proj_bias[:256]
										UpperCamelCase__										=      in_proj_weight[256:512, :]
										UpperCamelCase__										=      in_proj_bias[256:512]
										UpperCamelCase__										=      in_proj_weight[-256:, :]
										UpperCamelCase__										=      in_proj_bias[-256:]
										# read in weights + bias of input projection layer of cross-attention
										UpperCamelCase__										=      state_dict.pop(
										    f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight"							)
										UpperCamelCase__										=      state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias"							)
										# next, add query, keys and values (in that order) of cross-attention to the state dict
										UpperCamelCase__										=      in_proj_weight_cross_attn[:256, :]
										UpperCamelCase__										=      in_proj_bias_cross_attn[:256]
										UpperCamelCase__										=      in_proj_weight_cross_attn[256:512, :]
										UpperCamelCase__										=      in_proj_bias_cross_attn[256:512]
										UpperCamelCase__										=      in_proj_weight_cross_attn[-256:, :]
										UpperCamelCase__										=      in_proj_bias_cross_attn[-256:]







def  __UpperCamelCase    (						):
					UpperCamelCase__										=      '''http://images.cocodataset.org/val2017/000000039769.jpg'''
					UpperCamelCase__										=      Image.open(requests.get(A ,							stream=A							).raw							)

					return im







@torch.no_grad()
def  __UpperCamelCase    (						A ,							A=None ,							A=False							):
					UpperCamelCase__						,       UpperCamelCase__										=      get_detr_config(A							)

					# load original model from torch hub
					UpperCamelCase__										=      {
					    '''detr-resnet-50''': '''detr_resnet50''',
					    '''detr-resnet-101''': '''detr_resnet101''',
					}
					logger.info(f"Converting model {model_name}..."							)
					UpperCamelCase__										=      torch.hub.load('''facebookresearch/detr''' ,							model_name_to_original_name[model_name] ,							pretrained=A							).eval()
					UpperCamelCase__										=      detr.state_dict()
					# rename keys
					for src, dest in create_rename_keys(A							):
										if is_panoptic:
															UpperCamelCase__										=      '''detr.''' + src
										rename_key(A ,							A ,							A							)
					# query, key and value matrices need special treatment
					read_in_q_k_v(A ,							is_panoptic=A							)
					# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
					UpperCamelCase__										=      '''detr.model.''' if is_panoptic else '''model.'''
					for key in state_dict.copy().keys():
										if is_panoptic:
															if (
															    key.startswith('''detr'''							)
															    and not key.startswith('''class_labels_classifier'''							)
															    and not key.startswith('''bbox_predictor'''							)
															):
																				UpperCamelCase__										=      state_dict.pop(A							)
																				UpperCamelCase__										=      val
															elif "class_labels_classifier" in key or "bbox_predictor" in key:
																				UpperCamelCase__										=      state_dict.pop(A							)
																				UpperCamelCase__										=      val
															elif key.startswith('''bbox_attention'''							) or key.startswith('''mask_head'''							):
																				continue
															else:
																				UpperCamelCase__										=      state_dict.pop(A							)
																				UpperCamelCase__										=      val
										else:
															if not key.startswith('''class_labels_classifier'''							) and not key.startswith('''bbox_predictor'''							):
																				UpperCamelCase__										=      state_dict.pop(A							)
																				UpperCamelCase__										=      val

    # finally, create HuggingFace model and load state dict
					UpperCamelCase__										=      DetrForSegmentation(A							) if is_panoptic else DetrForObjectDetection(A							)
					model.load_state_dict(A							)
					model.eval()

					# verify our conversion on an image
					UpperCamelCase__										=      '''coco_panoptic''' if is_panoptic else '''coco_detection'''
					UpperCamelCase__										=      DetrImageProcessor(format=A							)

					UpperCamelCase__										=      processor(images=prepare_img() ,							return_tensors='''pt'''							)
					UpperCamelCase__										=      encoding['''pixel_values''']

					UpperCamelCase__										=      detr(A							)
					UpperCamelCase__										=      model(A							)

					assert torch.allclose(outputs.logits ,							original_outputs['''pred_logits'''] ,							atol=1e-3							)
					assert torch.allclose(outputs.pred_boxes ,							original_outputs['''pred_boxes'''] ,							atol=1e-3							)
					if is_panoptic:
										assert torch.allclose(outputs.pred_masks ,							original_outputs['''pred_masks'''] ,							atol=1e-4							)
					print('''Looks ok!'''							)

					if pytorch_dump_folder_path is not None:
										# Save model and image processor
										logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}..."							)
										Path(A							).mkdir(exist_ok=A							)
										model.save_pretrained(A							)
										processor.save_pretrained(A							)

					if push_to_hub:
										# Upload model and image processor to the hub
										logger.info('''Uploading PyTorch model and image processor to the hub...'''							)
										model.push_to_hub(f"nielsr/{model_name}"							)
										processor.push_to_hub(f"nielsr/{model_name}"							)


if __name__ == "__main__":
					__magic_name__								=argparse.ArgumentParser()

					parser.add_argument(
					    '''--model_name''',
					    default='''detr-resnet-50''',
					    type=str,
					    choices=['''detr-resnet-50''', '''detr-resnet-101'''],
					    help='''Name of the DETR model you\'d like to convert.''',
					)
					parser.add_argument(
					    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.'''
					)
					parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the model to the hub or not.''')
					__magic_name__								=parser.parse_args()
					convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)




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



