
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   (	UpperCamelCase:     List[Any]  ):






	"""simple docstring"""


	if isinstance(UpperCamelCase			,							collections.abc.Iterable  ):
		return x
	return (x, x)

@require_flax
class       a		:







							def       UpperCAmelCase__					(						self  :  Tuple      ,				snake_case__  :  Any      ,				snake_case__  :  List[Any] ):
								"""simple docstring"""







								pass







							def       UpperCAmelCase__					(						self  :  Dict ):
								"""simple docstring"""







								pass







							def       UpperCAmelCase__					(						self  :  Any ):
								"""simple docstring"""







								pass







							def       UpperCAmelCase__					(						self  :  str      ,				snake_case__  :  np.ndarray      ,				snake_case__  :  np.ndarray      ,				snake_case__  :  float ):
								"""simple docstring"""







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







							def       UpperCAmelCase__					(						self  :  Any      ,				snake_case__  :  Any      ,				snake_case__  :  Any      ,				snake_case__  :  int      ,				snake_case__  :  Dict      ,				snake_case__  :  Any=None      ,				**snake_case__  :  str ):
								"""simple docstring"""







								__lowerCAmelCase         =							VisionTextDualEncoderConfig.from_vision_text_configs(snake_case__      ,				snake_case__ )

								__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel(snake_case__ )

								__lowerCAmelCase         =							model(input_ids=snake_case__      ,				pixel_values=snake_case__      ,				attention_mask=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       UpperCAmelCase__					(						self  :  Any      ,				snake_case__  :  List[str]      ,				snake_case__  :  Any      ,				snake_case__  :  Dict      ,				snake_case__  :  Union[str, Any]      ,				snake_case__  :  Tuple=None      ,				**snake_case__  :  Dict ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.get_vision_text_model(snake_case__      ,				snake_case__ )
								__lowerCAmelCase         =							{"vision_model": vision_model, "text_model": text_model}
								__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case__ )

								__lowerCAmelCase         =							model(input_ids=snake_case__      ,				pixel_values=snake_case__      ,				attention_mask=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       UpperCAmelCase__					(						self  :  Dict      ,				snake_case__  :  Any      ,				snake_case__  :  Tuple      ,				snake_case__  :  List[str]      ,				snake_case__  :  Dict      ,				snake_case__  :  Dict=None      ,				**snake_case__  :  Tuple ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.get_vision_text_model(snake_case__      ,				snake_case__ )
								__lowerCAmelCase         =							{"vision_model": vision_model, "text_model": text_model}
								__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case__ )

								__lowerCAmelCase         =							model(input_ids=snake_case__      ,				pixel_values=snake_case__      ,				attention_mask=snake_case__ )
								__lowerCAmelCase         =							output[0]

								with tempfile.TemporaryDirectory() as tmpdirname:
									model.save_pretrained(snake_case__ )
									__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel.from_pretrained(snake_case__ )

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







							def       UpperCAmelCase__					(						self  :  int      ,				snake_case__  :  Dict      ,				snake_case__  :  Tuple      ,				snake_case__  :  List[str]      ,				snake_case__  :  Union[str, Any]      ,				snake_case__  :  List[str]=None      ,				**snake_case__  :  int ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.get_vision_text_model(snake_case__      ,				snake_case__ )
								__lowerCAmelCase         =							{"vision_model": vision_model, "text_model": text_model}
								__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case__ )

								__lowerCAmelCase         =							model(
								    input_ids=snake_case__      ,				pixel_values=snake_case__      ,				attention_mask=snake_case__      ,				output_attentions=snake_case__ )

								__lowerCAmelCase         =							output.vision_model_output.attentions
								self.assertEqual(len(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)
								__lowerCAmelCase         =							to_atuple(vision_model.config.image_size )
								__lowerCAmelCase         =							to_atuple(vision_model.config.patch_size )
								__lowerCAmelCase         =							(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
								__lowerCAmelCase         =							num_patches + 1
								self.assertEqual(vision_attentions[0].shape[-3:]      ,				(vision_config.num_attention_heads, seq_len, seq_len) )

								__lowerCAmelCase         =							output.text_model_output.attentions
								self.assertEqual(len(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       UpperCAmelCase__					(						self  :  Union[str, Any]      ,				snake_case__  :  int      ,				snake_case__  :  str      ,				snake_case__  :  List[Any] ):
								"""simple docstring"""







								pt_model.to(snake_case__ )
								pt_model.eval()

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

								with torch.no_grad():
									__lowerCAmelCase         =							pt_model(**snake_case__ ).to_tuple()

								__lowerCAmelCase         =							fx_model(**snake_case__ ).to_tuple()
								self.assertEqual(len(snake_case__ )      ,				len(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(snake_case__      ,				pt_output.numpy()      ,				4E-2 )

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

								__lowerCAmelCase         =							fx_model_loaded(**snake_case__ ).to_tuple()
								self.assertEqual(len(snake_case__ )      ,				len(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(snake_case__      ,				pt_output.numpy()      ,				4E-2 )

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

								pt_model_loaded.to(snake_case__ )
								pt_model_loaded.eval()

								with torch.no_grad():
									__lowerCAmelCase         =							pt_model_loaded(**snake_case__ ).to_tuple()

								self.assertEqual(len(snake_case__ )      ,				len(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(snake_case__      ,				pt_output_loaded.numpy()      ,				4E-2 )







							def       UpperCAmelCase__					(						self  :  int      ,				snake_case__  :  List[Any]      ,				snake_case__  :  Tuple      ,				snake_case__  :  Dict ):
								"""simple docstring"""







								__lowerCAmelCase         =							VisionTextDualEncoderConfig.from_vision_text_configs(snake_case__      ,				snake_case__ )

								__lowerCAmelCase         =							VisionTextDualEncoderModel(snake_case__ )
								__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel(snake_case__ )

								__lowerCAmelCase         =							convert_pytorch_state_dict_to_flax(pt_model.state_dict()      ,				snake_case__ )
								__lowerCAmelCase         =							fx_state

								self.check_pt_flax_equivalence(snake_case__      ,				snake_case__      ,				snake_case__ )







							def       UpperCAmelCase__					(						self  :  str      ,				snake_case__  :  int      ,				snake_case__  :  List[Any]      ,				snake_case__  :  int ):
								"""simple docstring"""







								__lowerCAmelCase         =							VisionTextDualEncoderConfig.from_vision_text_configs(snake_case__      ,				snake_case__ )

								__lowerCAmelCase         =							VisionTextDualEncoderModel(snake_case__ )
								__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel(snake_case__ )

								__lowerCAmelCase         =							load_flax_weights_in_pytorch_model(snake_case__      ,				fx_model.params )

								self.check_pt_flax_equivalence(snake_case__      ,				snake_case__      ,				snake_case__ )







							def       UpperCAmelCase__					(						self  :  List[str] ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.prepare_config_and_inputs()
								self.check_model_from_pretrained_configs(**snake_case__ )







							def       UpperCAmelCase__					(						self  :  str ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.prepare_config_and_inputs()
								self.check_vision_text_dual_encoder_from_pretrained(**snake_case__ )







							def       UpperCAmelCase__					(						self  :  List[Any] ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.prepare_config_and_inputs()
								self.check_save_load(**snake_case__ )







							def       UpperCAmelCase__					(						self  :  str ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.prepare_config_and_inputs()
								self.check_vision_text_output_attention(**snake_case__ )







							@is_pt_flax_cross_test
							def       UpperCAmelCase__					(						self  :  Tuple ):
								"""simple docstring"""







								__lowerCAmelCase         =							self.prepare_config_and_inputs()
								__lowerCAmelCase         =							config_inputs_dict.pop("vision_config" )
								__lowerCAmelCase         =							config_inputs_dict.pop("text_config" )

								__lowerCAmelCase         =							config_inputs_dict

								self.check_equivalence_pt_to_flax(snake_case__      ,				snake_case__      ,				snake_case__ )
								self.check_equivalence_flax_to_pt(snake_case__      ,				snake_case__      ,				snake_case__ )







							@slow
							def       UpperCAmelCase__					(						self  :  int ):
								"""simple docstring"""







								__lowerCAmelCase   ,						__lowerCAmelCase         =							self.get_pretrained_model_and_inputs()

								__lowerCAmelCase         =							model_a(**snake_case__ )
								__lowerCAmelCase         =							outputs[0]

								with tempfile.TemporaryDirectory() as tmp_dirname:
									model_a.save_pretrained(snake_case__ )
									__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel.from_pretrained(snake_case__ )

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

@require_flax
class       a		(   __UpperCAmelCase      ,	unittest.TestCase					):







							def       UpperCAmelCase__					(						self  :  Union[str, Any] ):
								"""simple docstring"""







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

								return model, inputs







							def       UpperCAmelCase__					(						self  :  Any      ,				snake_case__  :  Tuple      ,				snake_case__  :  str ):
								"""simple docstring"""







								__lowerCAmelCase         =							FlaxViTModel(snake_case__ )
								__lowerCAmelCase         =							FlaxBertModel(snake_case__ )
								return vision_model, text_model







							def       UpperCAmelCase__					(						self  :  int ):
								"""simple docstring"""







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

								__lowerCAmelCase   ,						__lowerCAmelCase         =							vision_config_and_inputs

								__lowerCAmelCase   ,						__lowerCAmelCase   ,						__lowerCAmelCase   ,						__lowerCAmelCase         =							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       UpperCAmelCase__					(						self  :  List[str] ):
								"""simple docstring"""







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

								return model, inputs







							def       UpperCAmelCase__					(						self  :  List[Any]      ,				snake_case__  :  Union[str, Any]      ,				snake_case__  :  Any ):
								"""simple docstring"""







								__lowerCAmelCase         =							FlaxCLIPVisionModel(snake_case__ )
								__lowerCAmelCase         =							FlaxBertModel(snake_case__ )
								return vision_model, text_model







							def       UpperCAmelCase__					(						self  :  Any ):
								"""simple docstring"""







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

								__lowerCAmelCase   ,						__lowerCAmelCase         =							vision_config_and_inputs

								__lowerCAmelCase   ,						__lowerCAmelCase   ,						__lowerCAmelCase   ,						__lowerCAmelCase         =							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       UpperCAmelCase__					(						self  :  List[Any] ):
								"""simple docstring"""







								__lowerCAmelCase         =							FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian"      ,				logit_scale_init_value=1.0 )
								__lowerCAmelCase         =							VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" )

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

								__lowerCAmelCase         =							model(**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])      ,				)

								__lowerCAmelCase         =							np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] )

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








import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCamelCase_   	=	logging.get_logger(__name__)

UpperCamelCase_   	=	{
    "nvidia/segformer-b0-finetuned-ade-512-512": (
        "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json"
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}

class       a		(   __UpperCAmelCase					):
							lowercase_		:						Union[str, Any]   							=  'segformer'







							def __init__(						self  :  List[str]      ,				snake_case__  :  Any=3      ,				snake_case__  :  int=4      ,				snake_case__  :  Tuple=[2, 2, 2, 2]      ,				snake_case__  :  Optional[int]=[8, 4, 2, 1]      ,				snake_case__  :  Union[str, Any]=[32, 64, 160, 256]      ,				snake_case__  :  str=[7, 3, 3, 3]      ,				snake_case__  :  List[Any]=[4, 2, 2, 2]      ,				snake_case__  :  Tuple=[1, 2, 5, 8]      ,				snake_case__  :  List[str]=[4, 4, 4, 4]      ,				snake_case__  :  Optional[Any]="gelu"      ,				snake_case__  :  Optional[Any]=0.0      ,				snake_case__  :  Any=0.0      ,				snake_case__  :  str=0.1      ,				snake_case__  :  List[Any]=0.0_2      ,				snake_case__  :  Any=0.1      ,				snake_case__  :  List[Any]=1E-6      ,				snake_case__  :  Any=256      ,				snake_case__  :  Optional[Any]=255      ,				**snake_case__  :  Union[str, Any]      ,				):
								"""simple docstring"""







								super().__init__(**snake_case__ )

								if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
									warnings.warn(
									    "Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"
									    " removed, as the behaviour will default to that of reshape_last_stage = True."      ,				snake_case__      ,				)

								__lowerCAmelCase         =							num_channels
								__lowerCAmelCase         =							num_encoder_blocks
								__lowerCAmelCase         =							depths
								__lowerCAmelCase         =							sr_ratios
								__lowerCAmelCase         =							hidden_sizes
								__lowerCAmelCase         =							patch_sizes
								__lowerCAmelCase         =							strides
								__lowerCAmelCase         =							mlp_ratios
								__lowerCAmelCase         =							num_attention_heads
								__lowerCAmelCase         =							hidden_act
								__lowerCAmelCase         =							hidden_dropout_prob
								__lowerCAmelCase         =							attention_probs_dropout_prob
								__lowerCAmelCase         =							classifier_dropout_prob
								__lowerCAmelCase         =							initializer_range
								__lowerCAmelCase         =							drop_path_rate
								__lowerCAmelCase         =							layer_norm_eps
								__lowerCAmelCase         =							decoder_hidden_size
								__lowerCAmelCase         =							kwargs.get("reshape_last_stage"      ,				snake_case__ )
								__lowerCAmelCase         =							semantic_loss_ignore_index

class       a		(   __UpperCAmelCase					):
							lowercase_		:						List[str]   							=  version.parse('1.11'					)







							@property
							def       UpperCAmelCase__					(						self  :  Any ):
								"""simple docstring"""







								return OrderedDict(
								    [
								        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
								    ] )







							@property
							def       UpperCAmelCase__					(						self  :  Union[str, Any] ):
								"""simple docstring"""







								return 1E-4







							@property
							def       UpperCAmelCase__					(						self  :  Optional[Any] ):
								"""simple docstring"""







								return 12






