



"""simple docstring"""

import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPanoramaPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




@skip_mps
class  _UpperCAmelCase (    lowerCAmelCase__					,  lowerCAmelCase__					,  unittest.TestCase):
 _lowerCAmelCase     :    Optional[int]	      =	StableDiffusionPanoramaPipeline
 _lowerCAmelCase     :    List[str]	      =	TEXT_TO_IMAGE_PARAMS
 _lowerCAmelCase     :    Any	      =	TEXT_TO_IMAGE_BATCH_PARAMS
 _lowerCAmelCase     :    str	      =	TEXT_TO_IMAGE_IMAGE_PARAMS
 _lowerCAmelCase     :    Optional[int]	      =	TEXT_TO_IMAGE_IMAGE_PARAMS

 def 		_snake_case      (  self	: Dict       ):
     torch.manual_seed(0       )
     snake_case_				:  Any       =			UNetaDConditionModel(
         block_out_channels=(32, 64)						,  layers_per_block=1						,  sample_size=32						,  in_channels=4						,  out_channels=4						,  down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')						,  up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')						,  cross_attention_dim=32						,  )
     snake_case_				:  List[str]       =			DDIMScheduler()
     torch.manual_seed(0       )
     snake_case_				:  List[str]       =			AutoencoderKL(
         block_out_channels=[32, 64]						,  in_channels=3						,  out_channels=3						,  down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']						,  up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']						,  latent_channels=4						,  )
     torch.manual_seed(0       )
     snake_case_				:  Tuple       =			CLIPTextConfig(
         bos_token_id=0						,  eos_token_id=2						,  hidden_size=32						,  intermediate_size=37						,  layer_norm_eps=1E-05						,  num_attention_heads=4						,  num_hidden_layers=5						,  pad_token_id=1						,  vocab_size=1000						,  )
     snake_case_				:  Tuple       =			CLIPTextModel(lowercase_       )
     snake_case_				:  Optional[Any]       =			CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )

     snake_case_				:  Tuple       =			{
         '''unet''': unet,
         '''scheduler''': scheduler,
         '''vae''': vae,
         '''text_encoder''': text_encoder,
         '''tokenizer''': tokenizer,
         '''safety_checker''': None,
         '''feature_extractor''': None,
     }
     return components

 def 		_snake_case      (  self	: Optional[Any]						,  lowercase_	: str						,  lowercase_	: Optional[int]=0       ):
     snake_case_				:  Union[str, Any]       =			torch.manual_seed(lowercase_       )
     snake_case_				:  str       =			{
         '''prompt''': '''a photo of the dolomites''',
         '''generator''': generator,
         # Setting height and width to None to prevent OOMs on CPU.
         '''height''': None,
         '''width''': None,
         '''num_inference_steps''': 1,
         '''guidance_scale''': 6.0,
         '''output_type''': '''numpy''',
     }
     return inputs

 def 		_snake_case      (  self	: Dict       ):
     snake_case_				:  List[Any]       =			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     snake_case_				:  Dict       =			self.get_dummy_components()
     snake_case_				:  List[str]       =			StableDiffusionPanoramaPipeline(**lowercase_       )
     snake_case_				:  int       =			sd_pipe.to(lowercase_       )
     sd_pipe.set_progress_bar_config(disable=lowercase_       )

     snake_case_				:  str       =			self.get_dummy_inputs(lowercase_       )
     snake_case_				:  Union[str, Any]       =			sd_pipe(**lowercase_       ).images
     snake_case_				:  Optional[int]       =			image[0, -3:, -3:, -1]
     assert image.shape == (1, 64, 64, 3)

     snake_case_				:  List[Any]       =			np.array([0.61_86, 0.53_74, 0.49_15, 0.41_35, 0.41_14, 0.45_63, 0.51_28, 0.49_77, 0.47_57]       )

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2

 def 		_snake_case      (  self	: int       ):
     super().test_inference_batch_consistent(batch_sizes=[1, 2]       )

 def 		_snake_case      (  self	: Optional[int]       ):
     super().test_inference_batch_single_identical(batch_size=2						,  expected_max_diff=3.25E-3       )

 def 		_snake_case      (  self	: int       ):
     snake_case_				:  str       =			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     snake_case_				:  Any       =			self.get_dummy_components()
     snake_case_				:  List[str]       =			StableDiffusionPanoramaPipeline(**lowercase_       )
     snake_case_				:  Union[str, Any]       =			sd_pipe.to(lowercase_       )
     sd_pipe.set_progress_bar_config(disable=lowercase_       )

     snake_case_				:  Optional[Any]       =			self.get_dummy_inputs(lowercase_       )
     snake_case_				:  int       =			'''french fries'''
     snake_case_				:  List[Any]       =			sd_pipe(**lowercase_						,  negative_prompt=lowercase_       )
     snake_case_				:  List[str]       =			output.images
     snake_case_				:  List[str]       =			image[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)

     snake_case_				:  int       =			np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57]       )

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2

 def 		_snake_case      (  self	: Optional[Any]       ):
     snake_case_				:  str       =			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     snake_case_				:  Union[str, Any]       =			self.get_dummy_components()
     snake_case_				:  str       =			StableDiffusionPanoramaPipeline(**lowercase_       )
     snake_case_				:  Optional[Any]       =			sd_pipe.to(lowercase_       )
     sd_pipe.set_progress_bar_config(disable=lowercase_       )

     snake_case_				:  Optional[Any]       =			self.get_dummy_inputs(lowercase_       )
     snake_case_				:  Dict       =			sd_pipe(**lowercase_						,  view_batch_size=2       )
     snake_case_				:  Dict       =			output.images
     snake_case_				:  Tuple       =			image[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)

     snake_case_				:  Tuple       =			np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57]       )

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2

 def 		_snake_case      (  self	: int       ):
     snake_case_				:  int       =			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     snake_case_				:  Union[str, Any]       =			self.get_dummy_components()
     snake_case_				:  Optional[Any]       =			EulerAncestralDiscreteScheduler(
         beta_start=0.0_00_85						,  beta_end=0.0_12						,  beta_schedule='''scaled_linear'''       )
     snake_case_				:  Tuple       =			StableDiffusionPanoramaPipeline(**lowercase_       )
     snake_case_				:  List[str]       =			sd_pipe.to(lowercase_       )
     sd_pipe.set_progress_bar_config(disable=lowercase_       )

     snake_case_				:  Optional[Any]       =			self.get_dummy_inputs(lowercase_       )
     snake_case_				:  List[str]       =			sd_pipe(**lowercase_       ).images
     snake_case_				:  str       =			image[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)

     snake_case_				:  List[Any]       =			np.array([0.40_24, 0.65_10, 0.49_01, 0.53_78, 0.58_13, 0.56_22, 0.47_95, 0.44_67, 0.49_52]       )

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2






 def 		_snake_case      (  self	: Union[str, Any]       ):
     snake_case_				:  str       =			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     snake_case_				:  Any       =			self.get_dummy_components()
     snake_case_				:  List[str]       =			PNDMScheduler(
         beta_start=0.0_00_85						,  beta_end=0.0_12						,  beta_schedule='''scaled_linear'''						,  skip_prk_steps=lowercase_       )
     snake_case_				:  str       =			StableDiffusionPanoramaPipeline(**lowercase_       )
     snake_case_				:  str       =			sd_pipe.to(lowercase_       )
     sd_pipe.set_progress_bar_config(disable=lowercase_       )

     snake_case_				:  Optional[int]       =			self.get_dummy_inputs(lowercase_       )
     snake_case_				:  Optional[int]       =			sd_pipe(**lowercase_       ).images
     snake_case_				:  int       =			image[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)

     snake_case_				:  Any       =			np.array([0.63_91, 0.62_91, 0.48_61, 0.51_34, 0.55_52, 0.45_78, 0.50_32, 0.50_23, 0.45_39]       )

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2





@slow
@require_torch_gpu
class  _UpperCAmelCase (    unittest.TestCase):

 def 		_snake_case      (  self	: Tuple       ):
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()

 def 		_snake_case      (  self	: Dict						,  lowercase_	: List[str]=0       ):
     snake_case_				:  Any       =			torch.manual_seed(lowercase_       )
     snake_case_				:  Optional[Any]       =			{
         '''prompt''': '''a photo of the dolomites''',
         '''generator''': generator,
         '''num_inference_steps''': 3,
         '''guidance_scale''': 7.5,
         '''output_type''': '''numpy''',
     }
     return inputs

 def 		_snake_case      (  self	: Union[str, Any]       ):
     snake_case_				:  Dict       =			'''stabilityai/stable-diffusion-2-base'''
     snake_case_				:  Any       =			DDIMScheduler.from_pretrained(lowercase_						,  subfolder='''scheduler'''       )
     snake_case_				:  Dict       =			StableDiffusionPanoramaPipeline.from_pretrained(lowercase_						,  scheduler=lowercase_						,  safety_checker=lowercase_       )
     pipe.to(lowercase_       )
     pipe.set_progress_bar_config(disable=lowercase_       )
     pipe.enable_attention_slicing()

     snake_case_				:  str       =			self.get_inputs()
     snake_case_				:  Union[str, Any]       =			pipe(**lowercase_       ).images
     snake_case_				:  List[str]       =			image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 2048, 3)

     snake_case_				:  List[Any]       =			np.array(
         [
             0.36_96_83_92,
             0.27_02_53_72,
             0.32_44_67_66,
             0.28_37_93_87,
             0.36_36_32_74,
             0.30_73_33_47,
             0.27_10_00_27,
             0.27_05_41_25,
             0.25_53_60_96,
         ]       )

     assert np.abs(expected_slice - image_slice       ).max() < 1E-2

 def 		_snake_case      (  self	: int       ):
     snake_case_				:  Optional[Any]       =			StableDiffusionPanoramaPipeline.from_pretrained(
         '''stabilityai/stable-diffusion-2-base'''						,  safety_checker=lowercase_       )
     snake_case_				:  Optional[int]       =			LMSDiscreteScheduler.from_config(pipe.scheduler.config       )
     pipe.to(lowercase_       )
     pipe.set_progress_bar_config(disable=lowercase_       )
     pipe.enable_attention_slicing()

     snake_case_				:  Dict       =			self.get_inputs()
     snake_case_				:  str       =			pipe(**lowercase_       ).images
     snake_case_				:  int       =			image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 2048, 3)

     snake_case_				:  int       =			np.array(
         [
             [
                 0.0,
                 0.0,
                 0.0,
                 0.0,
                 0.0,
                 0.0,
                 0.0,
                 0.0,
                 0.0,
             ]
         ]       )

     assert np.abs(expected_slice - image_slice       ).max() < 1E-3

 def 		_snake_case      (  self	: Union[str, Any]       ):
     snake_case_				:  Any       =			0

     def callback_fn(lowercase_	: int						,  lowercase_	: int						,  lowercase_	: torch.FloatTensor       ) -> None:
         snake_case_				:  Tuple       =			True
         nonlocal number_of_steps
         number_of_steps += 1
         if step == 1:
             snake_case_				:  Any       =			latents.detach().cpu().numpy()
             assert latents.shape == (1, 4, 64, 256)
             snake_case_				:  Optional[Any]       =			latents[0, -3:, -3:, -1]

             snake_case_				:  Optional[int]       =			np.array(
                 [
                     0.18_68_18_69,
                     0.33_90_78_16,
                     0.5_36_12_76,
                     0.14_43_28_65,
                     -0.02_85_66_11,
                     -0.73_94_11_23,
                     0.23_39_79_87,
                     0.47_32_26_82,
                     -0.37_82_31_64,
                 ]       )
             assert np.abs(latents_slice.flatten() - expected_slice       ).max() < 5E-2
         elif step == 2:
             snake_case_				:  str       =			latents.detach().cpu().numpy()
             assert latents.shape == (1, 4, 64, 256)
             snake_case_				:  List[str]       =			latents[0, -3:, -3:, -1]

             snake_case_				:  Optional[Any]       =			np.array(
                 [
                     0.18_53_96_45,
                     0.33_98_72_48,
                     0.5_37_85_59,
                     0.14_43_71_42,
                     -0.02_45_52_61,
                     -0.7_33_83_17,
                     0.23_99_07_55,
                     0.47_35_62_72,
                     -0.3_78_65_05,
                 ]       )

             assert np.abs(latents_slice.flatten() - expected_slice       ).max() < 5E-2

     snake_case_				:  List[str]       =			False

     snake_case_				:  int       =			'''stabilityai/stable-diffusion-2-base'''
     snake_case_				:  Dict       =			DDIMScheduler.from_pretrained(lowercase_						,  subfolder='''scheduler'''       )
     snake_case_				:  Tuple       =			StableDiffusionPanoramaPipeline.from_pretrained(lowercase_						,  scheduler=lowercase_						,  safety_checker=lowercase_       )
     snake_case_				:  Any       =			pipe.to(lowercase_       )
     pipe.set_progress_bar_config(disable=lowercase_       )
     pipe.enable_attention_slicing()

     snake_case_				:  Dict       =			self.get_inputs()
     pipe(**lowercase_						,  callback=lowercase_						,  callback_steps=1       )
     assert callback_fn.has_been_called
     assert number_of_steps == 3






 def 		_snake_case      (  self	: List[str]       ):
     torch.cuda.empty_cache()
     torch.cuda.reset_max_memory_allocated()
     torch.cuda.reset_peak_memory_stats()

     snake_case_				:  int       =			'''stabilityai/stable-diffusion-2-base'''
     snake_case_				:  Any       =			DDIMScheduler.from_pretrained(lowercase_						,  subfolder='''scheduler'''       )
     snake_case_				:  int       =			StableDiffusionPanoramaPipeline.from_pretrained(lowercase_						,  scheduler=lowercase_						,  safety_checker=lowercase_       )
     snake_case_				:  Union[str, Any]       =			pipe.to(lowercase_       )
     pipe.set_progress_bar_config(disable=lowercase_       )
     pipe.enable_attention_slicing(1       )
     pipe.enable_sequential_cpu_offload()

     snake_case_				:  List[Any]       =			self.get_inputs()
     snake_case_				:  Union[str, Any]       =			pipe(**lowercase_       )

     snake_case_				:  Tuple       =			torch.cuda.max_memory_allocated()
     # make sure that less than 5.2 GB is allocated
     assert mem_bytes < 5.5 * 10**9





"""simple docstring"""

from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import TFCvtForImageClassification, TFCvtModel
     from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor




class  _UpperCAmelCase (    lowerCAmelCase__):

 def 		_snake_case      (  self	: int       ):
     snake_case_				:  Any       =			self.config_class(**self.inputs_dict       )
     self.parent.assertTrue(hasattr(lowercase_						,  '''embed_dim'''       )       )
     self.parent.assertTrue(hasattr(lowercase_						,  '''num_heads'''       )       )





class  _UpperCAmelCase :

 def __init__(  self	: List[str]						,  lowercase_	: Optional[Any]						,  lowercase_	: int=13						,  lowercase_	: Optional[int]=64						,  lowercase_	: Any=3						,  lowercase_	: Any=[16, 48, 96]						,  lowercase_	: List[Any]=[1, 3, 6]						,  lowercase_	: Union[str, Any]=[1, 2, 10]						,  lowercase_	: Optional[Any]=[7, 3, 3]						,  lowercase_	: Union[str, Any]=[4, 2, 2]						,  lowercase_	: Tuple=[2, 1, 1]						,  lowercase_	: List[str]=[2, 2, 2]						,  lowercase_	: Union[str, Any]=[False, False, True]						,  lowercase_	: Optional[int]=[0.0, 0.0, 0.0]						,  lowercase_	: str=0.02						,  lowercase_	: Optional[Any]=1E-12						,  lowercase_	: Optional[int]=True						,  lowercase_	: Optional[int]=True						,  lowercase_	: Optional[Any]=2						,  ):
     snake_case_				:  List[Any]       =			parent
     snake_case_				:  int       =			batch_size
     snake_case_				:  Union[str, Any]       =			image_size
     snake_case_				:  Tuple       =			patch_sizes
     snake_case_				:  List[Any]       =			patch_stride
     snake_case_				:  Dict       =			patch_padding
     snake_case_				:  Any       =			is_training
     snake_case_				:  Any       =			use_labels
     snake_case_				:  str       =			num_labels
     snake_case_				:  Optional[Any]       =			num_channels
     snake_case_				:  Optional[Any]       =			embed_dim
     snake_case_				:  int       =			num_heads
     snake_case_				:  List[str]       =			stride_kv
     snake_case_				:  Any       =			depth
     snake_case_				:  Dict       =			cls_token
     snake_case_				:  Dict       =			attention_drop_rate
     snake_case_				:  int       =			initializer_range
     snake_case_				:  Tuple       =			layer_norm_eps

 def 		_snake_case      (  self	: Dict       ):
     snake_case_				:  str       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

     snake_case_				:  str       =			None
     if self.use_labels:
         # create a random int32 tensor of given shape
         snake_case_				:  Union[str, Any]       =			ids_tensor([self.batch_size]						,  self.num_labels       )

     snake_case_				:  Dict       =			self.get_config()
     return config, pixel_values, labels

 def 		_snake_case      (  self	: int       ):
     return CvtConfig(
         image_size=self.image_size						,  num_labels=self.num_labels						,  num_channels=self.num_channels						,  embed_dim=self.embed_dim						,  num_heads=self.num_heads						,  patch_sizes=self.patch_sizes						,  patch_padding=self.patch_padding						,  patch_stride=self.patch_stride						,  stride_kv=self.stride_kv						,  depth=self.depth						,  cls_token=self.cls_token						,  attention_drop_rate=self.attention_drop_rate						,  initializer_range=self.initializer_range						,  )

 def 		_snake_case      (  self	: int						,  lowercase_	: List[str]						,  lowercase_	: Optional[Any]						,  lowercase_	: Union[str, Any]       ):
     snake_case_				:  Tuple       =			TFCvtModel(config=lowercase_       )
     snake_case_				:  Tuple       =			model(lowercase_						,  training=lowercase_       )
     snake_case_				:  int       =			(self.image_size, self.image_size)
     snake_case_,			snake_case_				:  List[str]       =			image_size[0], image_size[1]
     for i in range(len(self.depth       )       ):
         snake_case_				:  str       =			floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
         snake_case_				:  str       =			floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
     self.parent.assertEqual(result.last_hidden_state.shape						,  (self.batch_size, self.embed_dim[-1], height, width)       )

 def 		_snake_case      (  self	: Dict						,  lowercase_	: Tuple						,  lowercase_	: Union[str, Any]						,  lowercase_	: List[str]       ):
     snake_case_				:  int       =			self.num_labels
     snake_case_				:  Any       =			TFCvtForImageClassification(lowercase_       )
     snake_case_				:  List[Any]       =			model(lowercase_						,  labels=lowercase_						,  training=lowercase_       )
     self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels)       )






 def 		_snake_case      (  self	: Any       ):
     snake_case_				:  Tuple       =			self.prepare_config_and_inputs()
     snake_case_,			snake_case_,			snake_case_				:  List[str]       =			config_and_inputs
     snake_case_				:  Any       =			{'''pixel_values''': pixel_values}
     return config, inputs_dict





@require_tf
class  _UpperCAmelCase (    lowerCAmelCase__					,  lowerCAmelCase__					,  unittest.TestCase):
 _lowerCAmelCase     :    Optional[int]	      =	(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
 _lowerCAmelCase     :    str	      =	(
     {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
     if is_tf_available()
     else {}
 )
 _lowerCAmelCase     :    str	      =	False
 _lowerCAmelCase     :    int	      =	False
 _lowerCAmelCase     :    Tuple	      =	False
 _lowerCAmelCase     :    int	      =	False
 _lowerCAmelCase     :    int	      =	False

 def 		_snake_case      (  self	: int       ):
     snake_case_				:  Optional[int]       =			TFCvtModelTester(self       )
     snake_case_				:  str       =			TFCvtConfigTester(self						,  config_class=lowercase_						,  has_text_modality=lowercase_						,  hidden_size=37       )

 def 		_snake_case      (  self	: int       ):
     self.config_tester.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()

 @unittest.skip(reason='''Cvt does not output attentions'''       )
 def 		_snake_case      (  self	: Any       ):
     pass

 @unittest.skip(reason='''Cvt does not use inputs_embeds'''       )
 def 		_snake_case      (  self	: str       ):
     pass

 @unittest.skip(reason='''Cvt does not support input and output embeddings'''       )
 def 		_snake_case      (  self	: Union[str, Any]       ):
     pass

 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''       )       ) == 0						,  reason='''TF does not support backprop for grouped convolutions on CPU.'''						,  )
 def 		_snake_case      (  self	: Tuple       ):
     super().test_dataset_conversion()

 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''       )       ) == 0						,  reason='''TF does not support backprop for grouped convolutions on CPU.'''						,  )
 @slow
 def 		_snake_case      (  self	: Tuple       ):
     super().test_keras_fit()

 @unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8'''       )
 def 		_snake_case      (  self	: List[str]       ):
     snake_case_				:  Optional[Any]       =			tf.keras.mixed_precision.Policy('''mixed_float16'''       )
     tf.keras.mixed_precision.set_global_policy(lowercase_       )
     super().test_keras_fit()
     tf.keras.mixed_precision.set_global_policy('''float32'''       )

 def 		_snake_case      (  self	: int       ):
     snake_case_,			snake_case_				:  List[str]       =			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_				:  Dict       =			model_class(lowercase_       )
         snake_case_				:  str       =			inspect.signature(model.call       )
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         snake_case_				:  List[str]       =			[*signature.parameters.keys()]

         snake_case_				:  int       =			['''pixel_values''']
         self.assertListEqual(arg_names[:1]						,  lowercase_       )

 def 		_snake_case      (  self	: List[str]       ):
     def check_hidden_states_output(lowercase_	: Optional[int]						,  lowercase_	: Union[str, Any]						,  lowercase_	: str       ):
         snake_case_				:  Any       =			model_class(lowercase_       )

         snake_case_				:  Optional[Any]       =			model(**self._prepare_for_class(lowercase_						,  lowercase_       )       )
         snake_case_				:  Tuple       =			outputs.hidden_states

         snake_case_				:  str       =			len(self.model_tester.depth       )
         self.assertEqual(len(lowercase_       )						,  lowercase_       )

         # verify the first hidden states (first block)
         self.assertListEqual(
             list(hidden_states[0].shape[-3:]       )						,  [
                 self.model_tester.embed_dim[0],
                 self.model_tester.image_size // 4,
                 self.model_tester.image_size // 4,
             ]						,  )

     snake_case_,			snake_case_				:  List[Any]       =			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_				:  Dict       =			True
         check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_       )

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         snake_case_				:  Tuple       =			True

         check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_       )

 def 		_snake_case      (  self	: str       ):
     snake_case_				:  Dict       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_       )

 def 		_snake_case      (  self	: List[Any]       ):
     snake_case_				:  str       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_       )






 @slow
 def 		_snake_case      (  self	: Optional[Any]       ):
     for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_				:  int       =			TFCvtModel.from_pretrained(lowercase_       )
         self.assertIsNotNone(lowercase_       )





def __lowercase    (							):
    snake_case_				:  Tuple       =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
    return image






@require_tf
@require_vision
class  _UpperCAmelCase (    unittest.TestCase):

 @cached_property
 def 		_snake_case      (  self	: List[Any]       ):
     return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )






 @slow
 def 		_snake_case      (  self	: Tuple       ):
     snake_case_				:  int       =			TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

     snake_case_				:  Any       =			self.default_image_processor
     snake_case_				:  Union[str, Any]       =			prepare_img()
     snake_case_				:  int       =			image_processor(images=lowercase_						,  return_tensors='''tf'''       )

     # forward pass
     snake_case_				:  Tuple       =			model(**lowercase_       )

     # verify the logits
     snake_case_				:  Optional[Any]       =			tf.TensorShape((1, 1000)       )
     self.assertEqual(outputs.logits.shape						,  lowercase_       )

     snake_case_				:  Tuple       =			tf.constant([0.92_85, 0.90_15, -0.31_50]       )
     self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()						,  lowercase_						,  atol=1E-4       )       )





