





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  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Optional[Any]:



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

@require_flax
class      lowerCAmelCase							:
 def   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   Optional[Any]			)    ->			Dict:
     pass
 def   A_			(   self						:   Union[str, Any]			)    ->			Dict:
     pass
 def   A_			(   self						:   List[Any]			)    ->			Tuple:
     pass
 def   A_			(   self						:   Dict    ,  UpperCAmelCase						:   np.ndarray    ,  UpperCAmelCase						:   np.ndarray    ,  UpperCAmelCase						:   float			)    ->			int:
     lowerCamelCase__					:   Tuple      				=	np.abs((a - b)			).max()
     self.assertLessEqual(__UpperCamelCase    ,  __UpperCamelCase    ,  F"""Difference between torch and flax is {diff} (>= {tol})."""			)
 def   A_			(   self						:   Optional[int]    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   List[str]    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   Union[str, Any]=None    ,  **UpperCAmelCase						:   Optional[int]			)    ->			Union[str, Any]:
     lowerCamelCase__					:   Dict      				=	VisionTextDualEncoderConfig.from_vision_text_configs(__UpperCamelCase    ,  __UpperCamelCase			)

     lowerCamelCase__					:   Optional[int]      				=	FlaxVisionTextDualEncoderModel(__UpperCamelCase			)

     lowerCamelCase__					:   List[str]      				=	model(input_ids=__UpperCamelCase    ,  pixel_values=__UpperCamelCase    ,  attention_mask=__UpperCamelCase			)

     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						:   str    ,  UpperCAmelCase						:   List[str]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   List[str]=None    ,  **UpperCAmelCase						:   str			)    ->			Tuple:
     lowerCamelCase__				,							lowerCamelCase__					:   str      				=	self.get_vision_text_model(__UpperCamelCase    ,  __UpperCamelCase			)
     lowerCamelCase__					:   Dict      				=	{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__					:   List[str]      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__UpperCamelCase			)

     lowerCamelCase__					:   Dict      				=	model(input_ids=__UpperCamelCase    ,  pixel_values=__UpperCamelCase    ,  attention_mask=__UpperCamelCase			)

     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						:   str    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   List[str]=None    ,  **UpperCAmelCase						:   List[Any]			)    ->			Tuple:
     lowerCamelCase__				,							lowerCamelCase__					:   List[Any]      				=	self.get_vision_text_model(__UpperCamelCase    ,  __UpperCamelCase			)
     lowerCamelCase__					:   str      				=	{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__					:   Optional[Any]      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__UpperCamelCase			)

     lowerCamelCase__					:   str      				=	model(input_ids=__UpperCamelCase    ,  pixel_values=__UpperCamelCase    ,  attention_mask=__UpperCamelCase			)
     lowerCamelCase__					:   Any      				=	output[0]

     with tempfile.TemporaryDirectory() as tmpdirname:
         model.save_pretrained(__UpperCamelCase			)
         lowerCamelCase__					:   int      				=	FlaxVisionTextDualEncoderModel.from_pretrained(__UpperCamelCase			)

         lowerCamelCase__					:   str      				=	model(input_ids=__UpperCamelCase    ,  pixel_values=__UpperCamelCase    ,  attention_mask=__UpperCamelCase			)
         lowerCamelCase__					:   Optional[Any]      				=	after_output[0]
         lowerCamelCase__					:   Optional[Any]      				=	np.amax(np.abs(out_a - out_a			)			)
         self.assertLessEqual(__UpperCamelCase    ,  1e-3			)
 def   A_			(   self						:   Any    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   List[str]=None    ,  **UpperCAmelCase						:   int			)    ->			Optional[Any]:
     lowerCamelCase__				,							lowerCamelCase__					:   Tuple      				=	self.get_vision_text_model(__UpperCamelCase    ,  __UpperCamelCase			)
     lowerCamelCase__					:   Dict      				=	{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__					:   Optional[int]      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__UpperCamelCase			)

     lowerCamelCase__					:   str      				=	model(
         input_ids=__UpperCamelCase    ,  pixel_values=__UpperCamelCase    ,  attention_mask=__UpperCamelCase    ,  output_attentions=__UpperCamelCase			)

     lowerCamelCase__					:   Tuple      				=	output.vision_model_output.attentions
     self.assertEqual(len(__UpperCamelCase			)    ,  vision_config.num_hidden_layers			)

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

     lowerCamelCase__					:   str      				=	output.text_model_output.attentions
     self.assertEqual(len(__UpperCamelCase			)    ,  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						:   int    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   List[str]			)    ->			Any:
     pt_model.to(__UpperCamelCase			)
     pt_model.eval()

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

     with torch.no_grad():
         lowerCamelCase__					:   Union[str, Any]      				=	pt_model(**__UpperCamelCase			).to_tuple()

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

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

     lowerCamelCase__					:   Union[str, Any]      				=	fx_model_loaded(**__UpperCamelCase			).to_tuple()
     self.assertEqual(len(__UpperCamelCase			)    ,  len(__UpperCamelCase			)    ,  '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(__UpperCamelCase    ,  pt_output.numpy()    ,  4e-2			)

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

     pt_model_loaded.to(__UpperCamelCase			)
     pt_model_loaded.eval()

     with torch.no_grad():
         lowerCamelCase__					:   Tuple      				=	pt_model_loaded(**__UpperCamelCase			).to_tuple()

     self.assertEqual(len(__UpperCamelCase			)    ,  len(__UpperCamelCase			)    ,  '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(__UpperCamelCase    ,  pt_output_loaded.numpy()    ,  4e-2			)
 def   A_			(   self						:   List[Any]    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Any			)    ->			List[Any]:
     lowerCamelCase__					:   str      				=	VisionTextDualEncoderConfig.from_vision_text_configs(__UpperCamelCase    ,  __UpperCamelCase			)

     lowerCamelCase__					:   Union[str, Any]      				=	VisionTextDualEncoderModel(__UpperCamelCase			)
     lowerCamelCase__					:   str      				=	FlaxVisionTextDualEncoderModel(__UpperCamelCase			)

     lowerCamelCase__					:   Union[str, Any]      				=	convert_pytorch_state_dict_to_flax(pt_model.state_dict()    ,  __UpperCamelCase			)
     lowerCamelCase__					:   Optional[Any]      				=	fx_state

     self.check_pt_flax_equivalence(__UpperCamelCase    ,  __UpperCamelCase    ,  __UpperCamelCase			)
 def   A_			(   self						:   str    ,  UpperCAmelCase						:   List[str]    ,  UpperCAmelCase						:   List[str]    ,  UpperCAmelCase						:   Optional[int]			)    ->			Union[str, Any]:
     lowerCamelCase__					:   int      				=	VisionTextDualEncoderConfig.from_vision_text_configs(__UpperCamelCase    ,  __UpperCamelCase			)

     lowerCamelCase__					:   int      				=	VisionTextDualEncoderModel(__UpperCamelCase			)
     lowerCamelCase__					:   Union[str, Any]      				=	FlaxVisionTextDualEncoderModel(__UpperCamelCase			)

     lowerCamelCase__					:   Union[str, Any]      				=	load_flax_weights_in_pytorch_model(__UpperCamelCase    ,  fx_model.params			)

     self.check_pt_flax_equivalence(__UpperCamelCase    ,  __UpperCamelCase    ,  __UpperCamelCase			)
 def   A_			(   self						:   List[Any]			)    ->			Optional[Any]:
     lowerCamelCase__					:   Optional[int]      				=	self.prepare_config_and_inputs()
     self.check_model_from_pretrained_configs(**__UpperCamelCase			)
 def   A_			(   self						:   Optional[Any]			)    ->			List[Any]:
     lowerCamelCase__					:   Union[str, Any]      				=	self.prepare_config_and_inputs()
     self.check_vision_text_dual_encoder_from_pretrained(**__UpperCamelCase			)
 def   A_			(   self						:   int			)    ->			List[str]:
     lowerCamelCase__					:   List[str]      				=	self.prepare_config_and_inputs()
     self.check_save_load(**__UpperCamelCase			)
 def   A_			(   self						:   Dict			)    ->			Optional[int]:
     lowerCamelCase__					:   int      				=	self.prepare_config_and_inputs()
     self.check_vision_text_output_attention(**__UpperCamelCase			)
 @is_pt_flax_cross_test
 def   A_			(   self						:   List[str]			)    ->			Optional[int]:
     lowerCamelCase__					:   Any      				=	self.prepare_config_and_inputs()
     lowerCamelCase__					:   Dict      				=	config_inputs_dict.pop('vision_config'			)
     lowerCamelCase__					:   Optional[int]      				=	config_inputs_dict.pop('text_config'			)

     lowerCamelCase__					:   Optional[int]      				=	config_inputs_dict

     self.check_equivalence_pt_to_flax(__UpperCamelCase    ,  __UpperCamelCase    ,  __UpperCamelCase			)
     self.check_equivalence_flax_to_pt(__UpperCamelCase    ,  __UpperCamelCase    ,  __UpperCamelCase			)







 @slow
 def   A_			(   self						:   List[str]			)    ->			List[Any]:
     lowerCamelCase__				,							lowerCamelCase__					:   Union[str, Any]      				=	self.get_pretrained_model_and_inputs()

     lowerCamelCase__					:   Optional[int]      				=	model_a(**__UpperCamelCase			)
     lowerCamelCase__					:   str      				=	outputs[0]

     with tempfile.TemporaryDirectory() as tmp_dirname:
         model_a.save_pretrained(__UpperCamelCase			)
         lowerCamelCase__					:   Dict      				=	FlaxVisionTextDualEncoderModel.from_pretrained(__UpperCamelCase			)

         lowerCamelCase__					:   List[Any]      				=	model_a(**__UpperCamelCase			)
         lowerCamelCase__					:   Optional[int]      				=	after_outputs[0]
         lowerCamelCase__					:   Dict      				=	np.amax(np.abs(out_a - out_a			)			)
         self.assertLessEqual(__UpperCamelCase    ,  1e-5			)


@require_flax
class      lowerCAmelCase							(      __UpperCamelCase,						unittest.TestCase    ):
 def   A_			(   self						:   Tuple			)    ->			List[Any]:
     lowerCamelCase__					:   List[Any]      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
         'hf-internal-testing/tiny-random-vit'    ,  'hf-internal-testing/tiny-bert'    ,  vision_from_pt=__UpperCamelCase    ,  text_from_pt=__UpperCamelCase    ,  )
     lowerCamelCase__					:   str      				=	13
     lowerCamelCase__					:   Optional[Any]      				=	floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ]			)
     lowerCamelCase__					:   Any      				=	ids_tensor([batch_size, 4]    ,  model.config.text_config.vocab_size			)
     lowerCamelCase__					:   Tuple      				=	random_attention_mask([batch_size, 4]			)
     lowerCamelCase__					:   Tuple      				=	{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

     return model, inputs
 def   A_			(   self						:   List[Any]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   Any			)    ->			List[Any]:
     lowerCamelCase__					:   int      				=	FlaxViTModel(__UpperCamelCase			)
     lowerCamelCase__					:   Any      				=	FlaxBertModel(__UpperCamelCase			)
     return vision_model, text_model







 def   A_			(   self						:   List[str]			)    ->			List[Any]:
     lowerCamelCase__					:   Tuple      				=	FlaxViTModelTester(self			)
     lowerCamelCase__					:   str      				=	FlaxBertModelTester(self			)
     lowerCamelCase__					:   Optional[Any]      				=	vit_model_tester.prepare_config_and_inputs()
     lowerCamelCase__					:   List[str]      				=	bert_model_tester.prepare_config_and_inputs()

     lowerCamelCase__				,							lowerCamelCase__					:   List[Any]      				=	vision_config_and_inputs

     lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__					:   Optional[Any]      				=	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      lowerCAmelCase							(      __UpperCamelCase,						unittest.TestCase    ):
 def   A_			(   self						:   Any			)    ->			Optional[Any]:
     lowerCamelCase__					:   Optional[Any]      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
         'hf-internal-testing/tiny-random-clip'    ,  'hf-internal-testing/tiny-bert'    ,  vision_from_pt=__UpperCamelCase    ,  text_from_pt=__UpperCamelCase    ,  )
     lowerCamelCase__					:   List[Any]      				=	13
     lowerCamelCase__					:   str      				=	floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ]			)
     lowerCamelCase__					:   Any      				=	ids_tensor([batch_size, 4]    ,  model.config.text_config.vocab_size			)
     lowerCamelCase__					:   List[str]      				=	random_attention_mask([batch_size, 4]			)
     lowerCamelCase__					:   Any      				=	{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

     return model, inputs
 def   A_			(   self						:   List[Any]    ,  UpperCAmelCase						:   int    ,  UpperCAmelCase						:   List[Any]			)    ->			Optional[int]:
     lowerCamelCase__					:   Dict      				=	FlaxCLIPVisionModel(__UpperCamelCase			)
     lowerCamelCase__					:   List[str]      				=	FlaxBertModel(__UpperCamelCase			)
     return vision_model, text_model







 def   A_			(   self						:   Optional[Any]			)    ->			int:
     lowerCamelCase__					:   Dict      				=	FlaxCLIPVisionModelTester(self			)
     lowerCamelCase__					:   List[Any]      				=	FlaxBertModelTester(self			)
     lowerCamelCase__					:   Optional[int]      				=	clip_model_tester.prepare_config_and_inputs()
     lowerCamelCase__					:   List[str]      				=	bert_model_tester.prepare_config_and_inputs()

     lowerCamelCase__				,							lowerCamelCase__					:   Optional[int]      				=	vision_config_and_inputs

     lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__					:   Union[str, Any]      				=	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      lowerCAmelCase							(      unittest.TestCase    ):
 @slow
 def   A_			(   self						:   Any			)    ->			List[Any]:
     lowerCamelCase__					:   Any      				=	FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'    ,  logit_scale_init_value=1.0			)
     lowerCamelCase__					:   Optional[Any]      				=	VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'			)

     lowerCamelCase__					:   Any      				=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
     lowerCamelCase__					:   List[str]      				=	processor(
         text=['una foto di un gatto', 'una foto di un cane']    ,  images=__UpperCamelCase    ,  padding=__UpperCamelCase    ,  return_tensors='np'			)

     lowerCamelCase__					:   Any      				=	model(**__UpperCamelCase			)

     # 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__					:   List[Any]      				=	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    ,  __UpperCamelCase    ,  atol=1e-3			)			)












import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
    import jax
    import jax.numpy as jnp

    from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor

class      lowerCAmelCase							(      unittest.TestCase    ):
 def __init__(   self						:   List[Any]    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Optional[Any]=3    ,  UpperCAmelCase						:   str=32    ,  UpperCAmelCase						:   Union[str, Any]=3    ,  UpperCAmelCase						:   Dict=10    ,  UpperCAmelCase						:   List[str]=[10, 20, 30, 40]    ,  UpperCAmelCase						:   Any=[1, 1, 2, 1]    ,  UpperCAmelCase						:   List[str]=True    ,  UpperCAmelCase						:   List[str]=True    ,  UpperCAmelCase						:   Dict="relu"    ,  UpperCAmelCase						:   Tuple=3    ,  UpperCAmelCase						:   Dict=None    ,  )    ->			Optional[Any]:
     lowerCamelCase__					:   Union[str, Any]      				=	parent
     lowerCamelCase__					:   Optional[Any]      				=	batch_size
     lowerCamelCase__					:   Dict      				=	image_size
     lowerCamelCase__					:   int      				=	num_channels
     lowerCamelCase__					:   int      				=	embeddings_size
     lowerCamelCase__					:   str      				=	hidden_sizes
     lowerCamelCase__					:   Any      				=	depths
     lowerCamelCase__					:   str      				=	is_training
     lowerCamelCase__					:   List[Any]      				=	use_labels
     lowerCamelCase__					:   Union[str, Any]      				=	hidden_act
     lowerCamelCase__					:   Dict      				=	num_labels
     lowerCamelCase__					:   Dict      				=	scope
     lowerCamelCase__					:   List[str]      				=	len(UpperCAmelCase			)
 def   A_			(   self						:   Optional[int]			)    ->			Optional[int]:
     lowerCamelCase__					:   int      				=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

     lowerCamelCase__					:   str      				=	self.get_config()

     return config, pixel_values
 def   A_			(   self						:   Optional[int]			)    ->			Dict:
     return RegNetConfig(
         num_channels=self.num_channels    ,  embeddings_size=self.embeddings_size    ,  hidden_sizes=self.hidden_sizes    ,  depths=self.depths    ,  hidden_act=self.hidden_act    ,  num_labels=self.num_labels    ,  image_size=self.image_size    ,  )
 def   A_			(   self						:   str    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Any			)    ->			Optional[Any]:
     lowerCamelCase__					:   Optional[Any]      				=	FlaxRegNetModel(config=UpperCAmelCase			)
     lowerCamelCase__					:   Optional[Any]      				=	model(UpperCAmelCase			)

     # Output shape (b, c, h, w)
     self.parent.assertEqual(
         result.last_hidden_state.shape    ,  (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)    ,  )
 def   A_			(   self						:   str    ,  UpperCAmelCase						:   int    ,  UpperCAmelCase						:   Tuple			)    ->			Tuple:
     lowerCamelCase__					:   List[str]      				=	self.num_labels
     lowerCamelCase__					:   str      				=	FlaxRegNetForImageClassification(config=UpperCAmelCase			)
     lowerCamelCase__					:   Union[str, Any]      				=	model(UpperCAmelCase			)
     self.parent.assertEqual(result.logits.shape    ,  (self.batch_size, self.num_labels)			)







 def   A_			(   self						:   Dict			)    ->			str:
     lowerCamelCase__					:   Optional[int]      				=	self.prepare_config_and_inputs()
     lowerCamelCase__				,							lowerCamelCase__					:   Any      				=	config_and_inputs
     lowerCamelCase__					:   Dict      				=	{'pixel_values': pixel_values}
     return config, inputs_dict


@require_flax
class      lowerCAmelCase							(      __UpperCamelCase,						unittest.TestCase    ):
 UpperCAmelCase__									=	(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

 UpperCAmelCase__									=	False
 UpperCAmelCase__									=	False
 UpperCAmelCase__									=	False
 def   A_			(   self						:   List[Any]			)    ->			None:
     lowerCamelCase__					:   List[Any]      				=	FlaxRegNetModelTester(self			)
     lowerCamelCase__					:   Union[str, Any]      				=	ConfigTester(self    ,  config_class=UpperCAmelCase    ,  has_text_modality=UpperCAmelCase			)
 def   A_			(   self						:   int			)    ->			Tuple:
     self.create_and_test_config_common_properties()
     self.config_tester.create_and_test_config_to_json_string()
     self.config_tester.create_and_test_config_to_json_file()
     self.config_tester.create_and_test_config_from_and_save_pretrained()
     self.config_tester.create_and_test_config_with_num_labels()
     self.config_tester.check_config_can_be_init_without_params()
     self.config_tester.check_config_arguments_init()
 def   A_			(   self						:   Any			)    ->			str:
     return
 def   A_			(   self						:   Optional[Any]			)    ->			Optional[Any]:
     lowerCamelCase__					:   Union[str, Any]      				=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*UpperCAmelCase			)
 def   A_			(   self						:   Dict			)    ->			Optional[Any]:
     lowerCamelCase__					:   Any      				=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase			)
 @unittest.skip(reason='RegNet does not use inputs_embeds'			)
 def   A_			(   self						:   Dict			)    ->			Dict:
     pass
 @unittest.skip(reason='RegNet does not support input and output embeddings'			)
 def   A_			(   self						:   Any			)    ->			Tuple:
     pass
 def   A_			(   self						:   Union[str, Any]			)    ->			Union[str, Any]:
     lowerCamelCase__				,							lowerCamelCase__					:   Tuple      				=	self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         lowerCamelCase__					:   Optional[int]      				=	model_class(UpperCAmelCase			)
         lowerCamelCase__					:   Optional[Any]      				=	inspect.signature(model.__call__			)
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         lowerCamelCase__					:   List[Any]      				=	[*signature.parameters.keys()]

         lowerCamelCase__					:   int      				=	['pixel_values']
         self.assertListEqual(arg_names[:1]    ,  UpperCAmelCase			)
 def   A_			(   self						:   int			)    ->			List[str]:
     def check_hidden_states_output(UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   List[str]    ,  UpperCAmelCase						:   Optional[Any]			):
         lowerCamelCase__					:   Any      				=	model_class(UpperCAmelCase			)

         lowerCamelCase__					:   Optional[Any]      				=	model(**self._prepare_for_class(UpperCAmelCase    ,  UpperCAmelCase			)			)

         lowerCamelCase__					:   Union[str, Any]      				=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         lowerCamelCase__					:   Optional[int]      				=	self.model_tester.num_stages
         self.assertEqual(len(UpperCAmelCase			)    ,  expected_num_stages + 1			)

     lowerCamelCase__				,							lowerCamelCase__					:   Optional[Any]      				=	self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         lowerCamelCase__					:   List[str]      				=	True
         check_hidden_states_output(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         lowerCamelCase__					:   List[Any]      				=	True

         check_hidden_states_output(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)







 def   A_			(   self						:   Dict			)    ->			int:
     lowerCamelCase__				,							lowerCamelCase__					:   int      				=	self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         with self.subTest(model_class.__name__			):
             lowerCamelCase__					:   int      				=	self._prepare_for_class(UpperCAmelCase    ,  UpperCAmelCase			)
             lowerCamelCase__					:   Tuple      				=	model_class(UpperCAmelCase			)

             @jax.jit
             def model_jitted(UpperCAmelCase						:   Tuple    ,  **UpperCAmelCase						:   Tuple			):
                 return model(pixel_values=UpperCAmelCase    ,  **UpperCAmelCase			)

             with self.subTest('JIT Enabled'			):
                 lowerCamelCase__					:   Dict      				=	model_jitted(**UpperCAmelCase			).to_tuple()

             with self.subTest('JIT Disabled'			):
                 with jax.disable_jit():
                     lowerCamelCase__					:   Optional[int]      				=	model_jitted(**UpperCAmelCase			).to_tuple()

             self.assertEqual(len(UpperCAmelCase			)    ,  len(UpperCAmelCase			)			)
             for jitted_output, output in zip(UpperCAmelCase    ,  UpperCAmelCase			):
                 self.assertEqual(jitted_output.shape    ,  output.shape			)


def  SCREAMING_SNAKE_CASE   ( )    ->  Optional[Any]:
    lowerCamelCase__					:   Optional[int]      				=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
    return image


@require_flax
class      lowerCAmelCase							(      unittest.TestCase    ):
 @cached_property
 def   A_			(   self						:   Any			)    ->			List[Any]:
     return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'			) if is_vision_available() else None







 @slow
 def   A_			(   self						:   Dict			)    ->			Tuple:
     lowerCamelCase__					:   Union[str, Any]      				=	FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'			)

     lowerCamelCase__					:   Dict      				=	self.default_image_processor
     lowerCamelCase__					:   List[Any]      				=	prepare_img()
     lowerCamelCase__					:   List[str]      				=	image_processor(images=UpperCAmelCase    ,  return_tensors='np'			)

     lowerCamelCase__					:   List[Any]      				=	model(**UpperCAmelCase			)

     # verify the logits
     lowerCamelCase__					:   Union[str, Any]      				=	(1, 1000)
     self.assertEqual(outputs.logits.shape    ,  UpperCAmelCase			)

     lowerCamelCase__					:   Tuple      				=	jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]			)

     self.assertTrue(jnp.allclose(outputs.logits[0, :3]    ,  UpperCAmelCase    ,  atol=1e-4			)			)





