


"""simple docstring"""






import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


lowercase  		=			logging.get_logger(__name__)  # pylint: disable=invalid-name

lowercase  		=			"""
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""


@dataclass
class 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





							__magic_name__					:     Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]


class 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





							def __init__(						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					)   ->	Optional[int]:







								'''simple docstring'''




								super().__init__()

								self.register_modules(
								    prior=lowerCamelCase__	,					text_encoder=lowerCamelCase__	,					tokenizer=lowerCamelCase__	,					scheduler=lowerCamelCase__	,					renderer=lowerCamelCase__	,					)




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	str:







								'''simple docstring'''




								if latents is None:
									snake_case__  :						str		=      randn_tensor(lowerCamelCase__	,					generator=lowerCamelCase__	,					device=lowerCamelCase__	,					dtype=lowerCamelCase__)
								else:
									if latents.shape != shape:
										raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""")
									snake_case__  :						Union[str, Any]		=      latents.to(lowerCamelCase__)

								snake_case__  :						Optional[int]		=      latents * scheduler.init_noise_sigma
								return latents




							def        UpperCAmelCase (						self	,					lowerCamelCase__=0)   ->	Optional[int]:







								'''simple docstring'''




								if is_accelerate_available():
									from accelerate import cpu_offload
								else:
									raise ImportError("Please install accelerate via `pip install accelerate`")

								snake_case__  :						str		=      torch.device(f"""cuda:{gpu_id}""")

								snake_case__  :						str		=      [self.text_encoder, self.prior]
								for cpu_offloaded_model in models:
									if cpu_offloaded_model is not None:
										cpu_offload(lowerCamelCase__	,					lowerCamelCase__)




							def        UpperCAmelCase (						self	,					lowerCamelCase__=0)   ->	Any:







								'''simple docstring'''




								if is_accelerate_available() and is_accelerate_version(">="	,					"0.17.0.dev0"):
									from accelerate import cpu_offload_with_hook
								else:
									raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")

								snake_case__  :						Dict		=      torch.device(f"""cuda:{gpu_id}""")

								if self.device.type != "cpu":
									self.to("cpu"	,					silence_dtype_warnings=lowerCamelCase__)
									torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

								snake_case__  :						int		=      None
								for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
									snake_case__,					snake_case__  :						str		=      cpu_offload_with_hook(lowerCamelCase__	,					lowerCamelCase__	,					prev_module_hook=lowerCamelCase__)

								if self.safety_checker is not None:
									snake_case__,					snake_case__  :						Union[str, Any]		=      cpu_offload_with_hook(self.safety_checker	,					lowerCamelCase__	,					prev_module_hook=lowerCamelCase__)

								# We'll offload the last model manually.
								snake_case__  :						List[Any]		=      hook




							@property
							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								if self.device != torch.device("meta") or not hasattr(self.text_encoder	,					"_hf_hook"):
									return self.device
								for module in self.text_encoder.modules():
									if (
									    hasattr(lowerCamelCase__	,					"_hf_hook")
									    and hasattr(module._hf_hook	,					"execution_device")
									    and module._hf_hook.execution_device is not None
									):
										return torch.device(module._hf_hook.execution_device)
								return self.device




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					)   ->	Optional[Any]:







								'''simple docstring'''




								len(lowerCamelCase__) if isinstance(lowerCamelCase__	,					lowerCamelCase__) else 1

								# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
								snake_case__  :						Tuple		=      0
								# get prompt text embeddings
								snake_case__  :						Tuple		=      self.tokenizer(
								    lowerCamelCase__	,					padding="max_length"	,					max_length=self.tokenizer.model_max_length	,					truncation=lowerCamelCase__	,					return_tensors="pt"	,					)
								snake_case__  :						str		=      text_inputs.input_ids
								snake_case__  :						Union[str, Any]		=      self.tokenizer(lowerCamelCase__	,					padding="longest"	,					return_tensors="pt").input_ids

								if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						int		=      self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
									logger.warning(
									    "The following part of your input was truncated because CLIP can only handle sequences up to"
									    f""" {self.tokenizer.model_max_length} tokens: {removed_text}""")

								snake_case__  :						str		=      self.text_encoder(text_input_ids.to(lowerCamelCase__))
								snake_case__  :						Optional[int]		=      text_encoder_output.text_embeds

								snake_case__  :						str		=      prompt_embeds.repeat_interleave(lowerCamelCase__	,					dim=0)
								# in Shap-E it normalize the prompt_embeds and then later rescale it
								snake_case__  :						Optional[int]		=      prompt_embeds / torch.linalg.norm(lowerCamelCase__	,					dim=-1	,					keepdim=lowerCamelCase__)

								if do_classifier_free_guidance:
									snake_case__  :						List[str]		=      torch.zeros_like(lowerCamelCase__)

									# For classifier free guidance, we need to do two forward passes.
									# Here we concatenate the unconditional and text embeddings into a single batch
									# to avoid doing two forward passes
									snake_case__  :						Optional[int]		=      torch.cat([negative_prompt_embeds, prompt_embeds])

								# Rescale the features to have unit variance
								snake_case__  :						int		=      math.sqrt(prompt_embeds.shape[1]) * prompt_embeds

								return prompt_embeds







							@torch.no_grad()
							@replace_example_docstring(lowerCamelCase__)
							def __call__(						self	,					lowerCamelCase__	,					lowerCamelCase__ = 1	,					lowerCamelCase__ = 25	,					lowerCamelCase__ = None	,					lowerCamelCase__ = None	,					lowerCamelCase__ = 4.0	,					lowerCamelCase__ = 64	,					lowerCamelCase__ = "pil"	,					lowerCamelCase__ = True	,					)   ->	Any:







								'''simple docstring'''




								if isinstance(lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						Optional[int]		=      1
								elif isinstance(lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						Optional[Any]		=      len(lowerCamelCase__)
								else:
									raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase__)}""")

								snake_case__  :						Optional[Any]		=      self._execution_device

								snake_case__  :						int		=      batch_size * num_images_per_prompt

								snake_case__  :						int		=      guidance_scale > 1.0
								snake_case__  :						Tuple		=      self._encode_prompt(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)

								# prior

								self.scheduler.set_timesteps(lowerCamelCase__	,					device=lowerCamelCase__)
								snake_case__  :						Dict		=      self.scheduler.timesteps

								snake_case__  :						str		=      self.prior.config.num_embeddings
								snake_case__  :						Optional[Any]		=      self.prior.config.embedding_dim

								snake_case__  :						Union[str, Any]		=      self.prepare_latents(
								    (batch_size, num_embeddings * embedding_dim)	,					prompt_embeds.dtype	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					self.scheduler	,					)

								# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
								snake_case__  :						str		=      latents.reshape(latents.shape[0]	,					lowerCamelCase__	,					lowerCamelCase__)

								for i, t in enumerate(self.progress_bar(lowerCamelCase__)):
									# expand the latents if we are doing classifier free guidance
									snake_case__  :						Union[str, Any]		=      torch.cat([latents] * 2) if do_classifier_free_guidance else latents
									snake_case__  :						List[str]		=      self.scheduler.scale_model_input(lowerCamelCase__	,					lowerCamelCase__)

									snake_case__  :						Union[str, Any]		=      self.prior(
									    lowerCamelCase__	,					timestep=lowerCamelCase__	,					proj_embedding=lowerCamelCase__	,					).predicted_image_embedding

									# remove the variance
									snake_case__,					snake_case__  :						List[str]		=      noise_pred.split(
									    scaled_model_input.shape[2]	,					dim=2)  # batch_size, num_embeddings, embedding_dim

									if do_classifier_free_guidance is not None:
										snake_case__,					snake_case__  :						int		=      noise_pred.chunk(2)
										snake_case__  :						Union[str, Any]		=      noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

									snake_case__  :						int		=      self.scheduler.step(
									    lowerCamelCase__	,					timestep=lowerCamelCase__	,					sample=lowerCamelCase__	,					).prev_sample

								if output_type == "latent":
									return ShapEPipelineOutput(images=lowerCamelCase__)

								snake_case__  :						Dict		=      []
								for i, latent in enumerate(lowerCamelCase__):
									snake_case__  :						Any		=      self.renderer.decode(
									    latent[None, :]	,					lowerCamelCase__	,					size=lowerCamelCase__	,					ray_batch_size=4_096	,					n_coarse_samples=64	,					n_fine_samples=128	,					)
									images.append(lowerCamelCase__)

								snake_case__  :						Dict		=      torch.stack(lowerCamelCase__)

								if output_type not in ["np", "pil"]:
									raise ValueError(f"""Only the output types `pil` and `np` are supported not output_type={output_type}""")

								snake_case__  :						Any		=      images.cpu().numpy()

								if output_type == "pil":
									snake_case__  :						Dict		=      [self.numpy_to_pil(lowerCamelCase__) for image in images]

								# Offload last model to CPU
								if hasattr(self	,					"final_offload_hook") and self.final_offload_hook is not None:
									self.final_offload_hook.offload()

								if not return_dict:
									return (images,)

								return ShapEPipelineOutput(images=lowerCamelCase__)









"""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 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      self.config_class(**self.inputs_dict)
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"hidden_sizes"))
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"neck_hidden_sizes"))
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"num_attention_heads"))


class 			SCREAMING_SNAKE_CASE_  :




							'''simple docstring'''





							def __init__(						self	,					lowerCamelCase__	,					lowerCamelCase__=13	,					lowerCamelCase__=32	,					lowerCamelCase__=2	,					lowerCamelCase__=3	,					lowerCamelCase__=640	,					lowerCamelCase__=4	,					lowerCamelCase__="silu"	,					lowerCamelCase__=3	,					lowerCamelCase__=32	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.02	,					lowerCamelCase__=True	,					lowerCamelCase__=True	,					lowerCamelCase__=10	,					lowerCamelCase__=None	,					)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      parent
								snake_case__  :						List[Any]		=      batch_size
								snake_case__  :						Any		=      image_size
								snake_case__  :						Tuple		=      patch_size
								snake_case__  :						int		=      num_channels
								snake_case__  :						Optional[Any]		=      last_hidden_size
								snake_case__  :						Union[str, Any]		=      num_attention_heads
								snake_case__  :						Tuple		=      hidden_act
								snake_case__  :						Optional[int]		=      conv_kernel_size
								snake_case__  :						int		=      output_stride
								snake_case__  :						Optional[Any]		=      hidden_dropout_prob
								snake_case__  :						str		=      attention_probs_dropout_prob
								snake_case__  :						Any		=      classifier_dropout_prob
								snake_case__  :						Tuple		=      use_labels
								snake_case__  :						Optional[Any]		=      is_training
								snake_case__  :						Dict		=      num_labels
								snake_case__  :						Dict		=      initializer_range
								snake_case__  :						List[str]		=      scope




							def        UpperCAmelCase (						self)   ->	Optional[Any]:







								'''simple docstring'''




								snake_case__  :						List[Any]		=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

								snake_case__  :						Dict		=      self.get_config()

								return config, pixel_values, labels, pixel_labels




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								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	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Tuple		=      TFMobileViTModel(config=lowerCamelCase__)
								snake_case__  :						int		=      model(lowerCamelCase__	,					training=lowerCamelCase__)
								snake_case__  :						Tuple		=      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	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Any		=      self.num_labels
								snake_case__  :						Dict		=      TFMobileViTForImageClassification(lowerCamelCase__)
								snake_case__  :						List[Any]		=      model(lowerCamelCase__	,					labels=lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_labels))




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	str:







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      self.num_labels
								snake_case__  :						Any		=      TFMobileViTForSemanticSegmentation(lowerCamelCase__)
								snake_case__  :						List[Any]		=      self.image_size // self.output_stride

								snake_case__  :						Tuple		=      model(lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(
								    result.logits.shape	,					(self.batch_size, self.num_labels, expected_height, expected_width))

								snake_case__  :						str		=      model(lowerCamelCase__	,					labels=lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(
								    result.logits.shape	,					(self.batch_size, self.num_labels, expected_height, expected_width))







							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      self.prepare_config_and_inputs()
								snake_case__,					snake_case__,					snake_case__,					snake_case__  :						List[Any]		=      config_and_inputs
								snake_case__  :						Tuple		=      {"pixel_values": pixel_values}
								return config, inputs_dict


@require_tf
class 			SCREAMING_SNAKE_CASE_  (   _lowercase	,      _lowercase	,      unittest.TestCase):




							'''simple docstring'''





							__magic_name__					:     Optional[int]				  =  (
							    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
							    if is_tf_available()
							    else ()
							)
							__magic_name__					:     str				  =  (
							    {'''feature-extraction''': TFMobileViTModel, '''image-classification''': TFMobileViTForImageClassification}
							    if is_tf_available()
							    else {}
							)

							__magic_name__					:     List[str]				  =  False
							__magic_name__					:     int				  =  False
							__magic_name__					:     Any				  =  False
							__magic_name__					:     Optional[int]				  =  False
							__magic_name__					:     Union[str, Any]				  =  False




							def        UpperCAmelCase (						self)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Any		=      TFMobileViTModelTester(self)
								snake_case__  :						Dict		=      TFMobileViTConfigTester(self	,					config_class=lowerCamelCase__	,					has_text_modality=lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	Optional[int]:







								'''simple docstring'''




								self.config_tester.run_common_tests()




							@unittest.skip(reason="MobileViT does not use inputs_embeds")
							def        UpperCAmelCase (						self)   ->	Optional[Any]:







								'''simple docstring'''




								pass




							@unittest.skip(reason="MobileViT does not support input and output embeddings")
							def        UpperCAmelCase (						self)   ->	List[Any]:







								'''simple docstring'''




								pass




							@unittest.skip(reason="MobileViT does not output attentions")
							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								pass




							def        UpperCAmelCase (						self)   ->	List[Any]:







								'''simple docstring'''




								snake_case__,					snake_case__  :						int		=      self.model_tester.prepare_config_and_inputs_for_common()

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

									snake_case__  :						Dict		=      ["pixel_values"]
									self.assertListEqual(arg_names[:1]	,					lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	Optional[Any]:







								'''simple docstring'''




								snake_case__  :						Dict		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	List[str]:







								'''simple docstring'''




								def check_hidden_states_output(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						List[Any]		=      model_class(lowerCamelCase__)

									snake_case__  :						Optional[int]		=      model(**self._prepare_for_class(lowerCamelCase__	,					lowerCamelCase__))

									snake_case__  :						List[Any]		=      outputs.hidden_states

									snake_case__  :						Union[str, Any]		=      5
									self.assertEqual(len(lowerCamelCase__)	,					lowerCamelCase__)

									# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
									# with the width and height being successively divided by 2.
									snake_case__  :						str		=      2
									for i in range(len(lowerCamelCase__)):
										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)

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

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

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

									check_hidden_states_output(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	List[str]:







								'''simple docstring'''




								snake_case__  :						Dict		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__)




							@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)   ->	Any:







								'''simple docstring'''




								super().test_dataset_conversion()




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__=2E-1	,					lowerCamelCase__=2E-1)   ->	Optional[Any]:







								'''simple docstring'''




								self.assertTrue(np.allclose(lowerCamelCase__	,					lowerCamelCase__	,					atol=lowerCamelCase__	,					rtol=lowerCamelCase__))




							@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)   ->	int:







								'''simple docstring'''




								snake_case__,					snake_case__  :						str		=      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":
										snake_case__  :						Dict		=      model_class(lowerCamelCase__)
										if getattr(lowerCamelCase__	,					"hf_compute_loss"	,					lowerCamelCase__):
											super().test_keras_fit()




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__,					snake_case__  :						List[str]		=      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":
										snake_case__  :						Any		=      5

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

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

										snake_case__  :						Optional[Any]		=      model(lowerCamelCase__	,					**lowerCamelCase__)[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
										snake_case__  :						Dict		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)
										snake_case__  :						Dict		=      {"input_ids", "pixel_values", "input_features"}
										snake_case__  :						List[Any]		=      possible_input_names.intersection(set(lowerCamelCase__)).pop()
										snake_case__  :						List[Any]		=      prepared_for_class.pop(lowerCamelCase__)
										if "labels" in prepared_for_class:
											snake_case__  :						int		=      prepared_for_class["labels"].numpy()
											if len(labels.shape) > 1 and labels.shape[1] != 1:
												# labels[0] = -100
												snake_case__  :						Union[str, Any]		=      tf.convert_to_tensor(lowerCamelCase__)
												snake_case__  :						Tuple		=      model(lowerCamelCase__	,					**lowerCamelCase__)[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
										snake_case__  :						int		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)
										snake_case__  :						Union[str, Any]		=      model(lowerCamelCase__)[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
										snake_case__  :						str		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)

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

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

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

										for index, value in sorted_tuple_index_mapping:
											snake_case__  :						Any		=      prepared_for_class[value]

										snake_case__  :						List[str]		=      tuple(lowerCamelCase__)

										# Send to model
										snake_case__  :						int		=      model(tuple_input[:-1])[0]

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







							@slow
							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									snake_case__  :						Optional[Any]		=      TFMobileViTModel.from_pretrained(lowerCamelCase__)
									self.assertIsNotNone(lowerCamelCase__)



def 			A__		(					)							->	Optional[Any]:

	'''simple docstring'''


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



@require_tf
class 			SCREAMING_SNAKE_CASE_  (   unittest.TestCase):




							'''simple docstring'''





							@slow
							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small")

								snake_case__  :						List[str]		=      MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small")
								snake_case__  :						Dict		=      prepare_img()
								snake_case__  :						List[str]		=      image_processor(images=lowerCamelCase__	,					return_tensors="tf")

								# forward pass
								snake_case__  :						Union[str, Any]		=      model(**lowerCamelCase__	,					training=lowerCamelCase__)

								# verify the logits
								snake_case__  :						str		=      tf.TensorShape((1, 1_000))
								self.assertEqual(outputs.logits.shape	,					lowerCamelCase__)

								snake_case__  :						List[Any]		=      tf.constant([-1.93_64, -1.23_27, -0.46_53])

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







							@slow
							def        UpperCAmelCase (						self)   ->	List[str]:







								'''simple docstring'''




								snake_case__  :						Dict		=      TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

								snake_case__  :						Any		=      MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

								snake_case__  :						List[str]		=      prepare_img()
								snake_case__  :						Dict		=      image_processor(images=lowerCamelCase__	,					return_tensors="tf")

								# forward pass
								snake_case__  :						str		=      model(inputs.pixel_values	,					training=lowerCamelCase__)
								snake_case__  :						Dict		=      outputs.logits

								# verify the logits
								snake_case__  :						Union[str, Any]		=      tf.TensorShape((1, 21, 32, 32))
								self.assertEqual(logits.shape	,					lowerCamelCase__)

								snake_case__  :						List[Any]		=      tf.constant(
								    [
								        [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
								        [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
								        [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
								    ])

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





