






'''simple docstring'''

import inspect
from typing import Callable, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import DiffusionPipeline
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import logging


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




class      A     (   UpperCAmelCase_    ):






 """simple docstring"""





 def __init__(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  ):
       super().__init__()
       self.register_modules(
           vae=_snake_case      ,  text_encoder=_snake_case      ,  tokenizer=_snake_case      ,  unet=_snake_case      ,  scheduler=_snake_case      ,  safety_checker=_snake_case      ,  feature_extractor=_snake_case      ,  )
 def 	_UpperCAmelCase							(				self      ,  __lowerCAmelCase = "auto"			):


       if slice_size == "auto":
             # half the attention head size is usually a good trade-off between
             # speed and memory
             UpperCamelCase_					: str            =				self.unet.config.attention_head_dim // 2
       self.unet.set_attention_slice(_snake_case			)
 def 	_UpperCAmelCase							(				self			):
       self.enable_attention_slicing(_snake_case			)





 @torch.no_grad()
 def __call__(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase = 5_12      ,  __lowerCAmelCase = 5_12      ,  __lowerCAmelCase = 50      ,  __lowerCAmelCase = 7.5      ,  __lowerCAmelCase = None      ,  __lowerCAmelCase = 1      ,  __lowerCAmelCase = 0.0      ,  __lowerCAmelCase = None      ,  __lowerCAmelCase = None      ,  __lowerCAmelCase = "pil"      ,  __lowerCAmelCase = True      ,  __lowerCAmelCase = None      ,  __lowerCAmelCase = 1      ,  __lowerCAmelCase = None      ,  **__lowerCAmelCase      ,  ):


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

       if height % 8 != 0 or width % 8 != 0:
             raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}."			)

       if (callback_steps is None) or (
           callback_steps is not None and (not isinstance(_snake_case      ,  _snake_case			) or callback_steps <= 0)
       ):
             raise ValueError(
                 F"`callback_steps` has to be a positive integer but is {callback_steps} of type"
                 F" {type(_snake_case			)}."			)

       # get prompt text embeddings
       UpperCamelCase_					: Optional[Any]            =				self.tokenizer(
           _snake_case      ,  padding="""max_length"""      ,  max_length=self.tokenizer.model_max_length      ,  return_tensors="""pt"""      ,  )
       UpperCamelCase_					: Dict            =				text_inputs.input_ids

       if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
             UpperCamelCase_					: str            =				self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]			)
             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}"			)
             UpperCamelCase_					: Tuple            =				text_input_ids[:, : self.tokenizer.model_max_length]

       if text_embeddings is None:
             UpperCamelCase_					: str            =				self.text_encoder(text_input_ids.to(self.device			)			)[0]

       # duplicate text embeddings for each generation per prompt, using mps friendly method
       UpperCamelCase_     ,      UpperCamelCase_     ,      UpperCamelCase_					: Dict            =				text_embeddings.shape
       UpperCamelCase_					: List[Any]            =				text_embeddings.repeat(1      ,  _snake_case      ,  1			)
       UpperCamelCase_					: List[str]            =				text_embeddings.view(bs_embed * num_images_per_prompt      ,  _snake_case      ,  -1			)

       # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
       # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
       # corresponds to doing no classifier free guidance.
       UpperCamelCase_					: List[str]            =				guidance_scale > 1.0
       # get unconditional embeddings for classifier free guidance
       if do_classifier_free_guidance:
             UpperCamelCase_					: str            =				42
             if negative_prompt is None:
                   UpperCamelCase_					: Union[str, Any]            =				[""""""]
             elif type(_snake_case			) is not type(_snake_case			):
                   raise TypeError(
                       F"`negative_prompt` should be the same type to `prompt`, but got {type(_snake_case			)} !="
                       F" {type(_snake_case			)}."			)
             elif isinstance(_snake_case      ,  _snake_case			):
                   UpperCamelCase_					: int            =				[negative_prompt]
             elif batch_size != len(_snake_case			):
                   raise ValueError(
                       F"`negative_prompt`: {negative_prompt} has batch size {len(_snake_case			)}, but `prompt`:"
                       F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                       """ the batch size of `prompt`."""			)
             else:
                   UpperCamelCase_					: Dict            =				negative_prompt

             UpperCamelCase_					: Any            =				text_input_ids.shape[-1]
             UpperCamelCase_					: List[str]            =				self.tokenizer(
                 _snake_case      ,  padding="""max_length"""      ,  max_length=_snake_case      ,  truncation=_snake_case      ,  return_tensors="""pt"""      ,  )
             UpperCamelCase_					: Dict            =				self.text_encoder(uncond_input.input_ids.to(self.device			)			)[0]

             # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
             UpperCamelCase_					: Union[str, Any]            =				uncond_embeddings.shape[1]
             UpperCamelCase_					: List[Any]            =				uncond_embeddings.repeat(_snake_case      ,  _snake_case      ,  1			)
             UpperCamelCase_					: Optional[Any]            =				uncond_embeddings.view(batch_size * num_images_per_prompt      ,  _snake_case      ,  -1			)

             # 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
             UpperCamelCase_					: Optional[int]            =				torch.cat([uncond_embeddings, text_embeddings]			)

       # get the initial random noise unless the user supplied it

       # Unlike in other pipelines, latents need to be generated in the target device
       # for 1-to-1 results reproducibility with the CompVis implementation.
       # However this currently doesn't work in `mps`.
       UpperCamelCase_					: Optional[int]            =				(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
       UpperCamelCase_					: List[str]            =				(batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64)
       UpperCamelCase_					: Optional[int]            =				text_embeddings.dtype
       if latents is None:
             if self.device.type == "mps":
                   # randn does not exist on mps
                   UpperCamelCase_					: Tuple            =				torch.randn(
                       _snake_case      ,  generator=_snake_case      ,  device="""cpu"""      ,  dtype=_snake_case			).to(self.device			)
                   UpperCamelCase_					: List[Any]            =				torch.randn(_snake_case      ,  generator=_snake_case      ,  device="""cpu"""      ,  dtype=_snake_case			).to(
                       self.device			)
             else:
                   UpperCamelCase_					: List[Any]            =				torch.randn(
                       _snake_case      ,  generator=_snake_case      ,  device=self.device      ,  dtype=_snake_case			)
                   UpperCamelCase_					: int            =				torch.randn(_snake_case      ,  generator=_snake_case      ,  device=self.device      ,  dtype=_snake_case			)
       else:
             if latents_reference.shape != latents_shape:
                   raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"			)
             UpperCamelCase_					: str            =				latents_reference.to(self.device			)
             UpperCamelCase_					: str            =				latents.to(self.device			)

       # This is the key part of the pipeline where we
       # try to ensure that the generated images w/ the same seed
       # but different sizes actually result in similar images
       UpperCamelCase_					: Dict            =				(latents_shape[3] - latents_shape_reference[3]) // 2
       UpperCamelCase_					: Optional[Any]            =				(latents_shape[2] - latents_shape_reference[2]) // 2
       UpperCamelCase_					: Optional[Any]            =				latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx
       UpperCamelCase_					: int            =				latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy
       UpperCamelCase_					: int            =				0 if dx < 0 else dx
       UpperCamelCase_					: Dict            =				0 if dy < 0 else dy
       UpperCamelCase_					: str            =				max(-dx      ,  0			)
       UpperCamelCase_					: int            =				max(-dy      ,  0			)
       # import pdb
       # pdb.set_trace()
       UpperCamelCase_					: Optional[Any]            =				latents_reference[:, :, dy : dy + h, dx : dx + w]

       # set timesteps
       self.scheduler.set_timesteps(_snake_case			)

       # Some schedulers like PNDM have timesteps as arrays
       # It's more optimized to move all timesteps to correct device beforehand
       UpperCamelCase_					: Optional[int]            =				self.scheduler.timesteps.to(self.device			)

       # scale the initial noise by the standard deviation required by the scheduler
       UpperCamelCase_					: Optional[Any]            =				latents * self.scheduler.init_noise_sigma

       # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
       # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
       # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
       # and should be between [0, 1]
       UpperCamelCase_					: Union[str, Any]            =				"""eta""" in set(inspect.signature(self.scheduler.step			).parameters.keys()			)
       UpperCamelCase_					: Any            =				{}
       if accepts_eta:
             UpperCamelCase_					: str            =				eta

       for i, t in enumerate(self.progress_bar(_snake_case			)			):
             # expand the latents if we are doing classifier free guidance
             UpperCamelCase_					: Dict            =				torch.cat([latents] * 2			) if do_classifier_free_guidance else latents
             UpperCamelCase_					: Optional[Any]            =				self.scheduler.scale_model_input(_snake_case      ,  _snake_case			)

             # predict the noise residual
             UpperCamelCase_					: Optional[Any]            =				self.unet(_snake_case      ,  _snake_case      ,  encoder_hidden_states=_snake_case			).sample

             # perform guidance
             if do_classifier_free_guidance:
                   UpperCamelCase_     ,      UpperCamelCase_					: List[Any]            =				noise_pred.chunk(2			)
                   UpperCamelCase_					: Optional[int]            =				noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

             # compute the previous noisy sample x_t -> x_t-1
             UpperCamelCase_					: Optional[int]            =				self.scheduler.step(_snake_case      ,  _snake_case      ,  _snake_case      ,  **_snake_case			).prev_sample

             # call the callback, if provided
             if callback is not None and i % callback_steps == 0:
                   callback(_snake_case      ,  _snake_case      ,  _snake_case			)

       UpperCamelCase_					: Optional[Any]            =				1 / 0.1_82_15 * latents
       UpperCamelCase_					: List[Any]            =				self.vae.decode(_snake_case			).sample

       UpperCamelCase_					: str            =				(image / 2 + 0.5).clamp(0      ,  1			)

       # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
       UpperCamelCase_					: List[str]            =				image.cpu().permute(0      ,  2      ,  3      ,  1			).float().numpy()

       if self.safety_checker is not None:
             UpperCamelCase_					: Any            =				self.feature_extractor(self.numpy_to_pil(_snake_case			)      ,  return_tensors="""pt"""			).to(
                 self.device			)
             UpperCamelCase_     ,      UpperCamelCase_					: Union[str, Any]            =				self.safety_checker(
                 images=_snake_case      ,  clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype			)			)
       else:
             UpperCamelCase_					: int            =				None

       if output_type == "pil":
             UpperCamelCase_					: List[str]            =				self.numpy_to_pil(_snake_case			)

       if not return_dict:
             return (image, has_nsfw_concept)

       return StableDiffusionPipelineOutput(images=_snake_case      ,  nsfw_content_detected=_snake_case			)











import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import (
							    MODEL_MAPPING,
							    SegformerForImageClassification,
							    SegformerForSemanticSegmentation,
							    SegformerModel,
							)
							from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import SegformerImageProcessor


class   __lowerCAmelCase  (		UpperCAmelCase_   ):
					"""simple docstring"""






					def      _a				(  self       :							List[str]       ):






								"""simple docstring"""


								A__	  =     self.config_class(**self.inputs_dict       )
								self.parent.assertTrue(hasattr(_snake_case					,       'hidden_sizes'       )       )
								self.parent.assertTrue(hasattr(_snake_case					,       'num_attention_heads'       )       )
								self.parent.assertTrue(hasattr(_snake_case					,       'num_encoder_blocks'       )       )







class   __lowerCAmelCase  :
					"""simple docstring"""






					def __init__(  self       :							Any					,       _snake_case       :							str					,       _snake_case       :							Union[str, Any]=13					,       _snake_case       :							Any=64					,       _snake_case       :							Optional[Any]=3					,       _snake_case       :							Dict=4					,       _snake_case       :							Tuple=[2, 2, 2, 2]					,       _snake_case       :							str=[8, 4, 2, 1]					,       _snake_case       :							Union[str, Any]=[16, 32, 64, 1_28]					,       _snake_case       :							int=[1, 4, 8, 16]					,       _snake_case       :							List[str]=[1, 2, 4, 8]					,       _snake_case       :							int=True					,       _snake_case       :							int=True					,       _snake_case       :							Union[str, Any]="gelu"					,       _snake_case       :							Optional[int]=0.1					,       _snake_case       :							Tuple=0.1					,       _snake_case       :							Dict=0.02					,       _snake_case       :							Tuple=3					,       _snake_case       :							int=None					,       ):






								"""simple docstring"""


								A__	  =     parent
								A__	  =     batch_size
								A__	  =     image_size
								A__	  =     num_channels
								A__	  =     num_encoder_blocks
								A__	  =     sr_ratios
								A__	  =     depths
								A__	  =     hidden_sizes
								A__	  =     downsampling_rates
								A__	  =     num_attention_heads
								A__	  =     is_training
								A__	  =     use_labels
								A__	  =     hidden_act
								A__	  =     hidden_dropout_prob
								A__	  =     attention_probs_dropout_prob
								A__	  =     initializer_range
								A__	  =     num_labels
								A__	  =     scope



					def      _a				(  self       :							int       ):






								"""simple docstring"""


								A__	  =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

								A__	  =     None
								if self.use_labels:
											A__	  =     ids_tensor([self.batch_size, self.image_size, self.image_size]					,       self.num_labels       )

								A__	  =     self.get_config()
								return config, pixel_values, labels



					def      _a				(  self       :							int       ):






								"""simple docstring"""


								return SegformerConfig(
								    image_size=self.image_size					,       num_channels=self.num_channels					,       num_encoder_blocks=self.num_encoder_blocks					,       depths=self.depths					,       hidden_sizes=self.hidden_sizes					,       num_attention_heads=self.num_attention_heads					,       hidden_act=self.hidden_act					,       hidden_dropout_prob=self.hidden_dropout_prob					,       attention_probs_dropout_prob=self.attention_probs_dropout_prob					,       initializer_range=self.initializer_range					,       )



					def      _a				(  self       :							int					,       _snake_case       :							Optional[Any]					,       _snake_case       :							int					,       _snake_case       :							Any       ):






								"""simple docstring"""


								A__	  =     SegformerModel(config=_snake_case       )
								model.to(_snake_case       )
								model.eval()
								A__	  =     model(_snake_case       )
								A__	  =     A__	  =     self.image_size // (self.downsampling_rates[-1] * 2)
								self.parent.assertEqual(
								    result.last_hidden_state.shape					,       (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)       )



					def      _a				(  self       :							Union[str, Any]					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Tuple					,       _snake_case       :							Dict       ):






								"""simple docstring"""


								A__	  =     self.num_labels
								A__	  =     SegformerForSemanticSegmentation(_snake_case       )
								model.to(_snake_case       )
								model.eval()
								A__	  =     model(_snake_case       )
								self.parent.assertEqual(
								    result.logits.shape					,       (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)       )
								A__	  =     model(_snake_case					,       labels=_snake_case       )
								self.parent.assertEqual(
								    result.logits.shape					,       (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)       )
								self.parent.assertGreater(result.loss					,       0.0       )



					def      _a				(  self       :							List[str]					,       _snake_case       :							Optional[Any]					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							List[str]       ):






								"""simple docstring"""


								A__	  =     1
								A__	  =     SegformerForSemanticSegmentation(config=_snake_case       )
								model.to(_snake_case       )
								model.eval()
								A__	  =     torch.randint(0					,       1					,       (self.batch_size, self.image_size, self.image_size)       ).to(_snake_case       )
								A__	  =     model(_snake_case					,       labels=_snake_case       )
								self.parent.assertGreater(result.loss					,       0.0       )



					def      _a				(  self       :							List[Any]       ):






								"""simple docstring"""


								A__	  =     self.prepare_config_and_inputs()
								A__  ,			A__  ,			A__	  =     config_and_inputs
								A__	  =     {'pixel_values': pixel_values}
								return config, inputs_dict







@require_torch
class   __lowerCAmelCase  (		UpperCAmelCase_				,  UpperCAmelCase_				,  unittest.TestCase   ):
					"""simple docstring"""






					A__					:		Optional[int]      							=     (
					    (
					        SegformerModel,
					        SegformerForSemanticSegmentation,
					        SegformerForImageClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					A__					:		Union[str, Any]      							=     (
					    {
					        "feature-extraction": SegformerModel,
					        "image-classification": SegformerForImageClassification,
					        "image-segmentation": SegformerForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					A__					:		Optional[Any]      							=     True
					A__					:		str      							=     False
					A__					:		Tuple      							=     False
					A__					:		Dict      							=     False



					def      _a				(  self       :							Union[str, Any]       ):






								"""simple docstring"""


								A__	  =     SegformerModelTester(self       )
								A__	  =     SegformerConfigTester(self					,       config_class=_snake_case       )



					def      _a				(  self       :							Optional[int]       ):






								"""simple docstring"""


								self.config_tester.run_common_tests()



					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case       )



					def      _a				(  self       :							List[Any]       ):






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_binary_image_segmentation(*_snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_segmentation(*_snake_case       )



					@unittest.skip('SegFormer does not use inputs_embeds'       )
					def      _a				(  self       :							List[Any]       ):






								"""simple docstring"""


								pass



					@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'       )
					def      _a				(  self       :							Dict       ):






								"""simple docstring"""


								pass



					def      _a				(  self       :							Dict       ):






								"""simple docstring"""


								A__  ,			A__	  =     self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											A__	  =     model_class(_snake_case       )
											A__	  =     inspect.signature(model.forward       )
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											A__	  =     [*signature.parameters.keys()]

											A__	  =     ['pixel_values']
											self.assertListEqual(arg_names[:1]					,       _snake_case       )



					def      _a				(  self       :							Dict       ):






								"""simple docstring"""


								A__  ,			A__	  =     self.model_tester.prepare_config_and_inputs_for_common()
								A__	  =     True

								for model_class in self.all_model_classes:
											A__	  =     True
											A__	  =     False
											A__	  =     True
											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.eval()
											with torch.no_grad():
														A__	  =     model(**self._prepare_for_class(_snake_case					,       _snake_case       )       )
											A__	  =     outputs.attentions

											A__	  =     sum(self.model_tester.depths       )
											self.assertEqual(len(_snake_case       )					,       _snake_case       )

											# check that output_attentions also work using config
											del inputs_dict["output_attentions"]
											A__	  =     True
											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.eval()
											with torch.no_grad():
														A__	  =     model(**self._prepare_for_class(_snake_case					,       _snake_case       )       )
											A__	  =     outputs.attentions

											self.assertEqual(len(_snake_case       )					,       _snake_case       )

											# verify the first attentions (first block, first layer)
											A__	  =     (self.model_tester.image_size // 4) ** 2
											A__	  =     (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
											self.assertListEqual(
											    list(attentions[0].shape[-3:]       )					,       [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]					,       )

											# verify the last attentions (last block, last layer)
											A__	  =     (self.model_tester.image_size // 32) ** 2
											A__	  =     (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
											self.assertListEqual(
											    list(attentions[-1].shape[-3:]       )					,       [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]					,       )
											A__	  =     len(_snake_case       )

											# Check attention is always last and order is fine
											A__	  =     True
											A__	  =     True
											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.eval()
											with torch.no_grad():
														A__	  =     model(**self._prepare_for_class(_snake_case					,       _snake_case       )       )

											self.assertEqual(out_len + 1					,       len(_snake_case       )       )

											A__	  =     outputs.attentions

											self.assertEqual(len(_snake_case       )					,       _snake_case       )
											# verify the first attentions (first block, first layer)
											A__	  =     (self.model_tester.image_size // 4) ** 2
											A__	  =     (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
											self.assertListEqual(
											    list(self_attentions[0].shape[-3:]       )					,       [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]					,       )



					def      _a				(  self       :							Union[str, Any]       ):






								"""simple docstring"""


								def check_hidden_states_output(_snake_case       :							Dict					,       _snake_case       :							int					,       _snake_case       :							List[Any]       ):
											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.eval()

											with torch.no_grad():
														A__	  =     model(**self._prepare_for_class(_snake_case					,       _snake_case       )       )

											A__	  =     outputs.hidden_states

											A__	  =     self.model_tester.num_encoder_blocks
											self.assertEqual(len(_snake_case       )					,       _snake_case       )

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

								A__  ,			A__	  =     self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											A__	  =     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"]
											A__	  =     True

											check_hidden_states_output(_snake_case					,       _snake_case					,       _snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								if not self.model_tester.is_training:
											return

								A__  ,			A__	  =     self.model_tester.prepare_config_and_inputs_for_common()
								A__	  =     True

								for model_class in self.all_model_classes:
											if model_class in get_values(_snake_case       ):
														continue

											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.train()
											A__	  =     self._prepare_for_class(_snake_case					,       _snake_case					,       return_labels=_snake_case       )
											A__	  =     model(**_snake_case       ).loss
											loss.backward()



					@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'       )
					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								pass



					@slow
					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											A__	  =     SegformerModel.from_pretrained(_snake_case       )
											self.assertIsNotNone(_snake_case       )







def A    (							)    ->   str:
			A__	  =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
			return image






@require_torch
class   __lowerCAmelCase  (		unittest.TestCase   ):
					"""simple docstring"""






					@slow
					def      _a				(  self       :							Dict       ):






								"""simple docstring"""


								A__	  =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)					,       keep_ratio=_snake_case					,       align=_snake_case					,       do_random_crop=_snake_case       )
								A__	  =     SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'       ).to(
								    _snake_case       )

								A__	  =     prepare_img()
								A__	  =     image_processor(images=_snake_case					,       return_tensors='pt'       )
								A__	  =     encoded_inputs.pixel_values.to(_snake_case       )

								with torch.no_grad():
											A__	  =     model(_snake_case       )

								A__	  =     torch.Size((1, model.config.num_labels, 1_28, 1_28)       )
								self.assertEqual(outputs.logits.shape					,       _snake_case       )

								A__	  =     torch.tensor(
								    [
								        [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
								        [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
								        [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
								    ]       ).to(_snake_case       )
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]					,       _snake_case					,       atol=1E-4       )       )



					@slow
					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								A__	  =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)					,       keep_ratio=_snake_case					,       align=_snake_case					,       do_random_crop=_snake_case       )
								A__	  =     SegformerForSemanticSegmentation.from_pretrained(
								    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'       ).to(_snake_case       )

								A__	  =     prepare_img()
								A__	  =     image_processor(images=_snake_case					,       return_tensors='pt'       )
								A__	  =     encoded_inputs.pixel_values.to(_snake_case       )

								with torch.no_grad():
											A__	  =     model(_snake_case       )

								A__	  =     torch.Size((1, model.config.num_labels, 1_28, 1_28)       )
								self.assertEqual(outputs.logits.shape					,       _snake_case       )

								A__	  =     torch.tensor(
								    [
								        [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
								        [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
								        [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
								    ]       ).to(_snake_case       )
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]					,       _snake_case					,       atol=1E-1       )       )



					@slow
					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								A__	  =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)					,       keep_ratio=_snake_case					,       align=_snake_case					,       do_random_crop=_snake_case       )
								A__	  =     SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'       ).to(
								    _snake_case       )

								A__	  =     prepare_img()
								A__	  =     image_processor(images=_snake_case					,       return_tensors='pt'       )
								A__	  =     encoded_inputs.pixel_values.to(_snake_case       )

								with torch.no_grad():
											A__	  =     model(_snake_case       )

								A__	  =     outputs.logits.detach().cpu()

								A__	  =     image_processor.post_process_semantic_segmentation(outputs=_snake_case					,       target_sizes=[(5_00, 3_00)]       )
								A__	  =     torch.Size((5_00, 3_00)       )
								self.assertEqual(segmentation[0].shape					,       _snake_case       )

								A__	  =     image_processor.post_process_semantic_segmentation(outputs=_snake_case       )
								A__	  =     torch.Size((1_28, 1_28)       )
								self.assertEqual(segmentation[0].shape					,       _snake_case       )




