


'''simple docstring'''


import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput







def       snake_case_       (  SCREAMING_SNAKE_CASE__							,				SCREAMING_SNAKE_CASE__=0.9_9_9							,				SCREAMING_SNAKE_CASE__="cosine"							,				):







				"""simple docstring"""





				if alpha_transform_type == "cosine":

								def alpha_bar_fn(SCREAMING_SNAKE_CASE__					):
												return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2					) ** 2

				elif alpha_transform_type == "exp":

								def alpha_bar_fn(SCREAMING_SNAKE_CASE__					):
												return math.exp(t * -1_2.0					)

				else:
								raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}"""					)

				_SCREAMING_SNAKE_CASE			:	Optional[int]							=				[]
				for i in range(SCREAMING_SNAKE_CASE__					):
								_SCREAMING_SNAKE_CASE			:	Any							=				i / num_diffusion_timesteps
								_SCREAMING_SNAKE_CASE			:	List[str]							=				(i + 1) / num_diffusion_timesteps
								betas.append(min(1 - alpha_bar_fn(SCREAMING_SNAKE_CASE__					) / alpha_bar_fn(SCREAMING_SNAKE_CASE__					)							,				SCREAMING_SNAKE_CASE__					)					)
				return torch.tensor(SCREAMING_SNAKE_CASE__							,				dtype=torch.floataa					)







class    lowercase__  (						_snake_case					,					_snake_case ):





							'''simple docstring'''


							A_							:				Any				     =  [e.name for e in KarrasDiffusionSchedulers]
							A_							:				List[Any]				     =  2






							@register_to_config
							def __init__(   self   , __snake_case = 1000   , __snake_case = 0.00085   , __snake_case = 0.012   , __snake_case = "linear"   , __snake_case = None   , __snake_case = "epsilon"   , __snake_case = "linspace"   , __snake_case = 0   , ):
											if trained_betas is not None:
															_SCREAMING_SNAKE_CASE			:	Optional[int]							=				torch.tensor(__snake_case   , dtype=torch.floataa  )
											elif beta_schedule == "linear":
															_SCREAMING_SNAKE_CASE			:	Any							=				torch.linspace(__snake_case   , __snake_case   , __snake_case   , dtype=torch.floataa  )
											elif beta_schedule == "scaled_linear":
															# this schedule is very specific to the latent diffusion model.
															_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				(
															    torch.linspace(beta_start**0.5   , beta_end**0.5   , __snake_case   , dtype=torch.floataa  ) ** 2
															)
											elif beta_schedule == "squaredcos_cap_v2":
															# Glide cosine schedule
															_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				betas_for_alpha_bar(__snake_case  )
											else:
															raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}"""  )

											_SCREAMING_SNAKE_CASE			:	Dict							=				1.0 - self.betas
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				torch.cumprod(self.alphas   , dim=0  )

											#  set all values
											self.set_timesteps(__snake_case   , __snake_case   , __snake_case  )






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case=None  ):
											if schedule_timesteps is None:
															_SCREAMING_SNAKE_CASE			:	Optional[int]							=				self.timesteps

											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				(schedule_timesteps == timestep).nonzero()

											# The sigma index that is taken for the **very** first `step`
											# is always the second index (or the last index if there is only 1)
											# This way we can ensure we don't accidentally skip a sigma in
											# case we start in the middle of the denoising schedule (e.g. for image-to-image)
											if len(self._index_counter  ) == 0:
															_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				1 if len(__snake_case  ) > 1 else 0
											else:
															_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				timestep.cpu().item() if torch.is_tensor(__snake_case  ) else timestep
															_SCREAMING_SNAKE_CASE			:	List[str]							=				self._index_counter[timestep_int]

											return indices[pos].item()






							@property
							def UpperCAmelCase_     (   self  ):
											# standard deviation of the initial noise distribution
											if self.config.timestep_spacing in ["linspace", "trailing"]:
															return self.sigmas.max()

											return (self.sigmas.max() ** 2 + 1) ** 0.5






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case   , ):
											_SCREAMING_SNAKE_CASE			:	str							=				self.index_for_timestep(__snake_case  )

											if self.state_in_first_order:
															_SCREAMING_SNAKE_CASE			:	List[str]							=				self.sigmas[step_index]
											else:
															_SCREAMING_SNAKE_CASE			:	Optional[int]							=				self.sigmas_interpol[step_index - 1]

											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				sample / ((sigma**2 + 1) ** 0.5)
											return sample






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case = None   , __snake_case = None   , ):
											_SCREAMING_SNAKE_CASE			:	List[str]							=				num_inference_steps

											_SCREAMING_SNAKE_CASE			:	List[str]							=				num_train_timesteps or self.config.num_train_timesteps

											# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
											if self.config.timestep_spacing == "linspace":
															_SCREAMING_SNAKE_CASE			:	str							=				np.linspace(0   , num_train_timesteps - 1   , __snake_case   , dtype=__snake_case  )[::-1].copy()
											elif self.config.timestep_spacing == "leading":
															_SCREAMING_SNAKE_CASE			:	List[Any]							=				num_train_timesteps // self.num_inference_steps
															# creates integer timesteps by multiplying by ratio
															# casting to int to avoid issues when num_inference_step is power of 3
															_SCREAMING_SNAKE_CASE			:	List[Any]							=				(np.arange(0   , __snake_case  ) * step_ratio).round()[::-1].copy().astype(__snake_case  )
															timesteps += self.config.steps_offset
											elif self.config.timestep_spacing == "trailing":
															_SCREAMING_SNAKE_CASE			:	Any							=				num_train_timesteps / self.num_inference_steps
															# creates integer timesteps by multiplying by ratio
															# casting to int to avoid issues when num_inference_step is power of 3
															_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				(np.arange(__snake_case   , 0   , -step_ratio  )).round().copy().astype(__snake_case  )
															timesteps -= 1
											else:
															raise ValueError(
															    f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."""  )

											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5  )
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				torch.from_numpy(np.log(__snake_case  )  ).to(__snake_case  )

											_SCREAMING_SNAKE_CASE			:	List[Any]							=				np.interp(__snake_case   , np.arange(0   , len(__snake_case  )  )   , __snake_case  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				np.concatenate([sigmas, [0.0]]  ).astype(np.floataa  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				torch.from_numpy(__snake_case  ).to(device=__snake_case  )

											# compute up and down sigmas
											_SCREAMING_SNAKE_CASE			:	Any							=				sigmas.roll(-1  )
											_SCREAMING_SNAKE_CASE			:	Any							=				0.0
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				(sigmas_next**2 * (sigmas**2 - sigmas_next**2) / sigmas**2) ** 0.5
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				(sigmas_next**2 - sigmas_up**2) ** 0.5
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				0.0

											# compute interpolated sigmas
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				sigmas.log().lerp(sigmas_down.log()   , 0.5  ).exp()
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				0.0

											# set sigmas
											_SCREAMING_SNAKE_CASE			:	Any							=				torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2  ), sigmas[-1:]]  )
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				torch.cat(
											    [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2  ), sigmas_interpol[-1:]]  )
											_SCREAMING_SNAKE_CASE			:	Any							=				torch.cat([sigmas_up[:1], sigmas_up[1:].repeat_interleave(2  ), sigmas_up[-1:]]  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				torch.cat([sigmas_down[:1], sigmas_down[1:].repeat_interleave(2  ), sigmas_down[-1:]]  )

											if str(__snake_case  ).startswith("""mps"""  ):
															# mps does not support float64
															_SCREAMING_SNAKE_CASE			:	Tuple							=				torch.from_numpy(__snake_case  ).to(__snake_case   , dtype=torch.floataa  )
											else:
															_SCREAMING_SNAKE_CASE			:	Optional[int]							=				torch.from_numpy(__snake_case  ).to(__snake_case  )

											_SCREAMING_SNAKE_CASE			:	List[Any]							=				self.sigma_to_t(__snake_case  ).to(__snake_case   , dtype=timesteps.dtype  )
											_SCREAMING_SNAKE_CASE			:	str							=				torch.stack((timesteps_interpol[:-2, None], timesteps[1:, None])   , dim=-1  ).flatten()

											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				torch.cat([timesteps[:1], interleaved_timesteps]  )

											_SCREAMING_SNAKE_CASE			:	Tuple							=				None

											# for exp beta schedules, such as the one for `pipeline_shap_e.py`
											# we need an index counter
											_SCREAMING_SNAKE_CASE			:	Any							=				defaultdict(__snake_case  )






							def UpperCAmelCase_     (   self   , __snake_case  ):
											# get log sigma
											_SCREAMING_SNAKE_CASE			:	Tuple							=				sigma.log()

											# get distribution
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				log_sigma - self.log_sigmas[:, None]

											# get sigmas range
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				dists.ge(0  ).cumsum(dim=0  ).argmax(dim=0  ).clamp(max=self.log_sigmas.shape[0] - 2  )
											_SCREAMING_SNAKE_CASE			:	Any							=				low_idx + 1

											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				self.log_sigmas[low_idx]
											_SCREAMING_SNAKE_CASE			:	Dict							=				self.log_sigmas[high_idx]

											# interpolate sigmas
											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				(low - log_sigma) / (low - high)
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				w.clamp(0   , 1  )

											# transform interpolation to time range
											_SCREAMING_SNAKE_CASE			:	str							=				(1 - w) * low_idx + w * high_idx
											_SCREAMING_SNAKE_CASE			:	Any							=				t.view(sigma.shape  )
											return t






							@property
							def UpperCAmelCase_     (   self  ):
											return self.sample is None






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case   , __snake_case   , __snake_case = None   , __snake_case = True   , ):
											_SCREAMING_SNAKE_CASE			:	Dict							=				self.index_for_timestep(__snake_case  )

											# advance index counter by 1
											_SCREAMING_SNAKE_CASE			:	Any							=				timestep.cpu().item() if torch.is_tensor(__snake_case  ) else timestep
											self._index_counter[timestep_int] += 1

											if self.state_in_first_order:
															_SCREAMING_SNAKE_CASE			:	str							=				self.sigmas[step_index]
															_SCREAMING_SNAKE_CASE			:	str							=				self.sigmas_interpol[step_index]
															_SCREAMING_SNAKE_CASE			:	List[str]							=				self.sigmas_up[step_index]
															_SCREAMING_SNAKE_CASE			:	Any							=				self.sigmas_down[step_index - 1]
											else:
															# 2nd order / KPDM2's method
															_SCREAMING_SNAKE_CASE			:	str							=				self.sigmas[step_index - 1]
															_SCREAMING_SNAKE_CASE			:	Optional[int]							=				self.sigmas_interpol[step_index - 1]
															_SCREAMING_SNAKE_CASE			:	Tuple							=				self.sigmas_up[step_index - 1]
															_SCREAMING_SNAKE_CASE			:	Optional[int]							=				self.sigmas_down[step_index - 1]

											# currently only gamma=0 is supported. This usually works best anyways.
											# We can support gamma in the future but then need to scale the timestep before
											# passing it to the model which requires a change in API
											_SCREAMING_SNAKE_CASE			:	str							=				0
											_SCREAMING_SNAKE_CASE			:	Dict							=				sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				model_output.device
											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				randn_tensor(model_output.shape   , dtype=model_output.dtype   , device=__snake_case   , generator=__snake_case  )

											# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
											if self.config.prediction_type == "epsilon":
															_SCREAMING_SNAKE_CASE			:	int							=				sigma_hat if self.state_in_first_order else sigma_interpol
															_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				sample - sigma_input * model_output
											elif self.config.prediction_type == "v_prediction":
															_SCREAMING_SNAKE_CASE			:	List[Any]							=				sigma_hat if self.state_in_first_order else sigma_interpol
															_SCREAMING_SNAKE_CASE			:	str							=				model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
															    sample / (sigma_input**2 + 1)
															)
											elif self.config.prediction_type == "sample":
															raise NotImplementedError("""prediction_type not implemented yet: sample"""  )
											else:
															raise ValueError(
															    f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"""  )

											if self.state_in_first_order:
															# 2. Convert to an ODE derivative for 1st order
															_SCREAMING_SNAKE_CASE			:	int							=				(sample - pred_original_sample) / sigma_hat
															# 3. delta timestep
															_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				sigma_interpol - sigma_hat

															# store for 2nd order step
															_SCREAMING_SNAKE_CASE			:	Tuple							=				sample
															_SCREAMING_SNAKE_CASE			:	str							=				dt
															_SCREAMING_SNAKE_CASE			:	Any							=				sample + derivative * dt
											else:
															# DPM-Solver-2
															# 2. Convert to an ODE derivative for 2nd order
															_SCREAMING_SNAKE_CASE			:	Dict							=				(sample - pred_original_sample) / sigma_interpol
															# 3. delta timestep
															_SCREAMING_SNAKE_CASE			:	Tuple							=				sigma_down - sigma_hat

															_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				self.sample
															_SCREAMING_SNAKE_CASE			:	List[Any]							=				None

															_SCREAMING_SNAKE_CASE			:	str							=				sample + derivative * dt
															_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				prev_sample + noise * sigma_up

											if not return_dict:
															return (prev_sample,)

											return SchedulerOutput(prev_sample=__snake_case  )






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case   , __snake_case   , ):
											# Make sure sigmas and timesteps have the same device and dtype as original_samples
											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				self.sigmas.to(device=original_samples.device   , dtype=original_samples.dtype  )
											if original_samples.device.type == "mps" and torch.is_floating_point(__snake_case  ):
															# mps does not support float64
															_SCREAMING_SNAKE_CASE			:	Any							=				self.timesteps.to(original_samples.device   , dtype=torch.floataa  )
															_SCREAMING_SNAKE_CASE			:	int							=				timesteps.to(original_samples.device   , dtype=torch.floataa  )
											else:
															_SCREAMING_SNAKE_CASE			:	int							=				self.timesteps.to(original_samples.device  )
															_SCREAMING_SNAKE_CASE			:	Optional[int]							=				timesteps.to(original_samples.device  )

											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				[self.index_for_timestep(__snake_case   , __snake_case  ) for t in timesteps]

											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				sigmas[step_indices].flatten()
											while len(sigma.shape  ) < len(original_samples.shape  ):
															_SCREAMING_SNAKE_CASE			:	str							=				sigma.unsqueeze(-1  )

											_SCREAMING_SNAKE_CASE			:	Dict							=				original_samples + noise * sigma
											return noisy_samples






							def __len__(   self  ):
											return self.config.num_train_timesteps








'''simple docstring'''


from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

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 numpy as np
				import tensorflow as tf

				from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
				from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import MobileViTImageProcessor





class    lowercase__  (						_snake_case ):





							'''simple docstring'''


							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				self.config_class(**self.inputs_dict  )
											self.parent.assertTrue(hasattr(__snake_case   , """hidden_sizes"""  )  )
											self.parent.assertTrue(hasattr(__snake_case   , """neck_hidden_sizes"""  )  )
											self.parent.assertTrue(hasattr(__snake_case   , """num_attention_heads"""  )  )





class    lowercase__  :





							'''simple docstring'''


							def __init__(   self   , __snake_case   , __snake_case=13   , __snake_case=32   , __snake_case=2   , __snake_case=3   , __snake_case=640   , __snake_case=4   , __snake_case="silu"   , __snake_case=3   , __snake_case=32   , __snake_case=0.1   , __snake_case=0.1   , __snake_case=0.1   , __snake_case=0.02   , __snake_case=True   , __snake_case=True   , __snake_case=10   , __snake_case=None   , ):
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				parent
											_SCREAMING_SNAKE_CASE			:	Any							=				batch_size
											_SCREAMING_SNAKE_CASE			:	str							=				image_size
											_SCREAMING_SNAKE_CASE			:	str							=				patch_size
											_SCREAMING_SNAKE_CASE			:	Any							=				num_channels
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				last_hidden_size
											_SCREAMING_SNAKE_CASE			:	Any							=				num_attention_heads
											_SCREAMING_SNAKE_CASE			:	Any							=				hidden_act
											_SCREAMING_SNAKE_CASE			:	Any							=				conv_kernel_size
											_SCREAMING_SNAKE_CASE			:	int							=				output_stride
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				hidden_dropout_prob
											_SCREAMING_SNAKE_CASE			:	int							=				attention_probs_dropout_prob
											_SCREAMING_SNAKE_CASE			:	Any							=				classifier_dropout_prob
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				use_labels
											_SCREAMING_SNAKE_CASE			:	List[str]							=				is_training
											_SCREAMING_SNAKE_CASE			:	Dict							=				num_labels
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				initializer_range
											_SCREAMING_SNAKE_CASE			:	List[str]							=				scope






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

											_SCREAMING_SNAKE_CASE			:	str							=				None
											_SCREAMING_SNAKE_CASE			:	int							=				None
											if self.use_labels:
															_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				ids_tensor([self.batch_size]   , self.num_labels  )
															_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				ids_tensor([self.batch_size, self.image_size, self.image_size]   , self.num_labels  )

											_SCREAMING_SNAKE_CASE			:	Dict							=				self.get_config()

											return config, pixel_values, labels, pixel_labels






							def UpperCAmelCase_     (   self  ):
											return MobileViTConfig(
											    image_size=self.image_size   , patch_size=self.patch_size   , num_channels=self.num_channels   , num_attention_heads=self.num_attention_heads   , hidden_act=self.hidden_act   , conv_kernel_size=self.conv_kernel_size   , output_stride=self.output_stride   , hidden_dropout_prob=self.hidden_dropout_prob   , attention_probs_dropout_prob=self.attention_probs_dropout_prob   , classifier_dropout_prob=self.classifier_dropout_prob   , initializer_range=self.initializer_range   , )






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case   , __snake_case   , __snake_case  ):
											_SCREAMING_SNAKE_CASE			:	Any							=				TFMobileViTModel(config=__snake_case  )
											_SCREAMING_SNAKE_CASE			:	Any							=				model(__snake_case   , training=__snake_case  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				self.image_size // self.output_stride
											self.parent.assertEqual(
											    result.last_hidden_state.shape   , (self.batch_size, self.last_hidden_size, expected_height, expected_width)  )






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case   , __snake_case   , __snake_case  ):
											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				self.num_labels
											_SCREAMING_SNAKE_CASE			:	Any							=				TFMobileViTForImageClassification(__snake_case  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				model(__snake_case   , labels=__snake_case   , training=__snake_case  )
											self.parent.assertEqual(result.logits.shape   , (self.batch_size, self.num_labels)  )






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case   , __snake_case   , __snake_case  ):
											_SCREAMING_SNAKE_CASE			:	Tuple							=				self.num_labels
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				TFMobileViTForSemanticSegmentation(__snake_case  )
											_SCREAMING_SNAKE_CASE			:	Tuple							=				self.image_size // self.output_stride

											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				model(__snake_case   , training=__snake_case  )
											self.parent.assertEqual(
											    result.logits.shape   , (self.batch_size, self.num_labels, expected_height, expected_width)  )

											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				model(__snake_case   , labels=__snake_case   , training=__snake_case  )
											self.parent.assertEqual(
											    result.logits.shape   , (self.batch_size, self.num_labels, expected_height, expected_width)  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	str							=				self.prepare_config_and_inputs()
											_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE			:	int							=				config_and_inputs
											_SCREAMING_SNAKE_CASE			:	Tuple							=				{"""pixel_values""": pixel_values}
											return config, inputs_dict





@require_tf
class    lowercase__  (						_snake_case					,					_snake_case					,					unittest.TestCase ):





							'''simple docstring'''


							A_							:				List[Any]				     =  (
							    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
							    if is_tf_available()
							    else ()
							)
							A_							:				List[str]				     =  (
							    {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
							    if is_tf_available()
							    else {}
							)

							A_							:				str				     =  False
							A_							:				int				     =  False
							A_							:				Union[str, Any]				     =  False
							A_							:				List[str]				     =  False
							A_							:				str				     =  False






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				TFMobileViTModelTester(self  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				TFMobileViTConfigTester(self   , config_class=__snake_case   , has_text_modality=__snake_case  )






							def UpperCAmelCase_     (   self  ):
											self.config_tester.run_common_tests()






							@unittest.skip(reason="""MobileViT does not use inputs_embeds"""  )
							def UpperCAmelCase_     (   self  ):
											pass






							@unittest.skip(reason="""MobileViT does not support input and output embeddings"""  )
							def UpperCAmelCase_     (   self  ):
											pass






							@unittest.skip(reason="""MobileViT does not output attentions"""  )
							def UpperCAmelCase_     (   self  ):
											pass






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE			:	str							=				self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				model_class(__snake_case  )
															_SCREAMING_SNAKE_CASE			:	int							=				inspect.signature(model.call  )
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															_SCREAMING_SNAKE_CASE			:	str							=				[*signature.parameters.keys()]

															_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				["""pixel_values"""]
															self.assertListEqual(arg_names[:1]   , __snake_case  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__snake_case  )






							def UpperCAmelCase_     (   self  ):
											def check_hidden_states_output(__snake_case   , __snake_case   , __snake_case  ):
															_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				model_class(__snake_case  )

															_SCREAMING_SNAKE_CASE			:	List[str]							=				model(**self._prepare_for_class(__snake_case   , __snake_case  )  )

															_SCREAMING_SNAKE_CASE			:	Optional[int]							=				outputs.hidden_states

															_SCREAMING_SNAKE_CASE			:	Dict							=				5
															self.assertEqual(len(__snake_case  )   , __snake_case  )

															# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
															# with the width and height being successively divided by 2.
															_SCREAMING_SNAKE_CASE			:	int							=				2
															for i in range(len(__snake_case  )  ):
																			self.assertListEqual(
																			    list(hidden_states[i].shape[-2:]  )   , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]   , )
																			divisor *= 2

															self.assertEqual(self.model_tester.output_stride   , divisor // 2  )

											_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE			:	List[Any]							=				True
															check_hidden_states_output(__snake_case   , __snake_case   , __snake_case  )

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				True

															check_hidden_states_output(__snake_case   , __snake_case   , __snake_case  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	List[str]							=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__snake_case  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*__snake_case  )






							@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 UpperCAmelCase_     (   self  ):
											super().test_dataset_conversion()






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case   , __snake_case=2e-1   , __snake_case=2e-1  ):
											self.assertTrue(np.allclose(__snake_case   , __snake_case   , atol=__snake_case   , rtol=__snake_case  )  )






							@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 UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE			:	Optional[int]							=				self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															# Since `TFMobileViTModel` cannot operate with the default `fit()` method.
															if model_class.__name__ != "TFMobileViTModel":
																			_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				model_class(__snake_case  )
																			if getattr(__snake_case   , """hf_compute_loss"""   , __snake_case  ):
																							super().test_keras_fit()






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE			:	Dict							=				self.model_tester.prepare_config_and_inputs_for_common()
											for model_class in self.all_model_classes:
															# set an ignore index to correctly test the masked loss used in
															# `TFMobileViTForSemanticSegmentation`.
															if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
																			_SCREAMING_SNAKE_CASE			:	int							=				5

															_SCREAMING_SNAKE_CASE			:	Dict							=				model_class(__snake_case  )
															if getattr(__snake_case   , """hf_compute_loss"""   , __snake_case  ):
																			# The number of elements in the loss should be the same as the number of elements in the label
																			_SCREAMING_SNAKE_CASE			:	Optional[int]							=				self._prepare_for_class(inputs_dict.copy()   , __snake_case   , return_labels=__snake_case  )
																			_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				prepared_for_class[
																			    sorted(prepared_for_class.keys() - inputs_dict.keys()   , reverse=__snake_case  )[0]
																			]
																			_SCREAMING_SNAKE_CASE			:	List[Any]							=				added_label.shape.as_list()[:1]

																			# Test that model correctly compute the loss with kwargs
																			_SCREAMING_SNAKE_CASE			:	int							=				self._prepare_for_class(inputs_dict.copy()   , __snake_case   , return_labels=__snake_case  )
																			_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				{"""input_ids""", """pixel_values""", """input_features"""}
																			_SCREAMING_SNAKE_CASE			:	List[str]							=				possible_input_names.intersection(set(__snake_case  )  ).pop()
																			_SCREAMING_SNAKE_CASE			:	int							=				prepared_for_class.pop(__snake_case  )

																			_SCREAMING_SNAKE_CASE			:	List[Any]							=				model(__snake_case   , **__snake_case  )[0]
																			self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

																			# Test that model correctly compute the loss when we mask some positions
																			_SCREAMING_SNAKE_CASE			:	List[Any]							=				self._prepare_for_class(inputs_dict.copy()   , __snake_case   , return_labels=__snake_case  )
																			_SCREAMING_SNAKE_CASE			:	Dict							=				{"""input_ids""", """pixel_values""", """input_features"""}
																			_SCREAMING_SNAKE_CASE			:	Tuple							=				possible_input_names.intersection(set(__snake_case  )  ).pop()
																			_SCREAMING_SNAKE_CASE			:	List[str]							=				prepared_for_class.pop(__snake_case  )
																			if "labels" in prepared_for_class:
																							_SCREAMING_SNAKE_CASE			:	int							=				prepared_for_class["""labels"""].numpy()
																							if len(labels.shape  ) > 1 and labels.shape[1] != 1:
																											# labels[0] = -100
																											_SCREAMING_SNAKE_CASE			:	int							=				tf.convert_to_tensor(__snake_case  )
																											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				model(__snake_case   , **__snake_case  )[0]
																											self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )
																											self.assertTrue(not np.any(np.isnan(loss.numpy()  )  )  )

                # Test that model correctly compute the loss with a dict
																			_SCREAMING_SNAKE_CASE			:	int							=				self._prepare_for_class(inputs_dict.copy()   , __snake_case   , return_labels=__snake_case  )
																			_SCREAMING_SNAKE_CASE			:	List[Any]							=				model(__snake_case  )[0]
																			self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

																			# Test that model correctly compute the loss with a tuple
																			_SCREAMING_SNAKE_CASE			:	Optional[int]							=				self._prepare_for_class(inputs_dict.copy()   , __snake_case   , return_labels=__snake_case  )

																			# Get keys that were added with the _prepare_for_class function
																			_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				prepared_for_class.keys() - inputs_dict.keys()
																			_SCREAMING_SNAKE_CASE			:	Any							=				inspect.signature(model.call  ).parameters
																			_SCREAMING_SNAKE_CASE			:	Dict							=				list(signature.keys()  )

																			# Create a dictionary holding the location of the tensors in the tuple
																			_SCREAMING_SNAKE_CASE			:	str							=				{0: input_name}
																			for label_key in label_keys:
																							_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				signature_names.index(__snake_case  )
																							_SCREAMING_SNAKE_CASE			:	int							=				label_key
																			_SCREAMING_SNAKE_CASE			:	List[str]							=				sorted(tuple_index_mapping.items()  )
																			# Initialize a list with their default values, update the values and convert to a tuple
																			_SCREAMING_SNAKE_CASE			:	List[str]							=				[]

																			for name in signature_names:
																							if name != "kwargs":
																											list_input.append(signature[name].default  )

																			for index, value in sorted_tuple_index_mapping:
																							_SCREAMING_SNAKE_CASE			:	List[str]							=				prepared_for_class[value]

																			_SCREAMING_SNAKE_CASE			:	Optional[int]							=				tuple(__snake_case  )

																			# Send to model
																			_SCREAMING_SNAKE_CASE			:	List[Any]							=				model(tuple_input[:-1]  )[0]

																			self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )






							@slow
							def UpperCAmelCase_     (   self  ):
											for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE			:	List[Any]							=				TFMobileViTModel.from_pretrained(__snake_case  )
															self.assertIsNotNone(__snake_case  )







def       snake_case_       (  ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE			:	Tuple							=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
				return image







@require_tf
class    lowercase__  (						unittest.TestCase ):





							'''simple docstring'''


							@slow
							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Dict							=				TFMobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""  )

											_SCREAMING_SNAKE_CASE			:	List[Any]							=				MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""  )
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				prepare_img()
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				image_processor(images=__snake_case   , return_tensors="""tf"""  )

											# forward pass
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				model(**__snake_case   , training=__snake_case  )

											# verify the logits
											_SCREAMING_SNAKE_CASE			:	int							=				tf.TensorShape((1, 1000)  )
											self.assertEqual(outputs.logits.shape   , __snake_case  )

											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				tf.constant([-1.9364, -1.2327, -0.4653]  )

											tf.debugging.assert_near(outputs.logits[0, :3]   , __snake_case   , atol=1e-4   , rtol=1e-04  )






							@slow
							def UpperCAmelCase_     (   self  ):
											# `from_pt` will be removed
											_SCREAMING_SNAKE_CASE			:	Tuple							=				TFMobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""  )

											_SCREAMING_SNAKE_CASE			:	int							=				MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""  )

											_SCREAMING_SNAKE_CASE			:	Dict							=				prepare_img()
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				image_processor(images=__snake_case   , return_tensors="""tf"""  )

											# forward pass
											_SCREAMING_SNAKE_CASE			:	Any							=				model(inputs.pixel_values   , training=__snake_case  )
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				outputs.logits

											# verify the logits
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				tf.TensorShape((1, 21, 32, 32)  )
											self.assertEqual(logits.shape   , __snake_case  )

											_SCREAMING_SNAKE_CASE			:	List[Any]							=				tf.constant(
											    [
											        [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
											        [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
											        [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
											    ]  )

											tf.debugging.assert_near(logits[0, :3, :3, :3]   , __snake_case   , rtol=1e-4   , atol=1e-4  )




