





from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


_a     :    int         =						[
    'openmmlab/upernet-convnext-tiny',
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
_a     :    List[str]         =						'UperNetConfig'
class   a_ (			nn.Module      ):

			def __init__(   self   :  Optional[int]     , UpperCAmelCase__   :  int     , UpperCAmelCase__   :  int     , UpperCAmelCase__   :  Union[int, Tuple[int, int]]     , UpperCAmelCase__   :  Union[int, Tuple[int, int], str] = 0     , UpperCAmelCase__   :  bool = False     , UpperCAmelCase__   :  Union[int, Tuple[int, int]] = 1     , ):






							"""simple docstring"""
							super().__init__()
							snake_case   :					Dict    						=				nn.Convad(
							    in_channels=__UpperCAmelCase     , out_channels=__UpperCAmelCase     , kernel_size=__UpperCAmelCase     , padding=__UpperCAmelCase     , bias=__UpperCAmelCase     , dilation=__UpperCAmelCase     , )
							snake_case   :					Tuple    						=				nn.BatchNormad(__UpperCAmelCase						)
							snake_case   :					Any    						=				nn.ReLU()



			def      lowerCAmelCase(   self   :  List[str]     , UpperCAmelCase__   :  torch.Tensor						):






							"""simple docstring"""
							snake_case   :					Any    						=				self.conv(__UpperCAmelCase						)
							snake_case   :					Dict    						=				self.batch_norm(__UpperCAmelCase						)
							snake_case   :					Tuple    						=				self.activation(__UpperCAmelCase						)

							return output
class   a_ (			nn.Module      ):

			def __init__(   self   :  Union[str, Any]     , UpperCAmelCase__   :  int     , UpperCAmelCase__   :  int     , UpperCAmelCase__   :  int						):






							"""simple docstring"""
							super().__init__()
							snake_case   :					Optional[Any]    						=				[
							    nn.AdaptiveAvgPoolad(__UpperCAmelCase						),
							    UperNetConvModule(__UpperCAmelCase     , __UpperCAmelCase     , kernel_size=1						),
							]
							for i, layer in enumerate(self.layers						):
											self.add_module(str(__UpperCAmelCase						)     , __UpperCAmelCase						)



			def      lowerCAmelCase(   self   :  List[Any]     , UpperCAmelCase__   :  torch.Tensor						):






							"""simple docstring"""
							snake_case   :					Dict    						=				input
							for layer in self.layers:
											snake_case   :					List[Any]    						=				layer(__UpperCAmelCase						)
							return hidden_state
class   a_ (			nn.Module      ):

			def __init__(   self   :  Dict     , UpperCAmelCase__   :  Tuple[int, ...]     , UpperCAmelCase__   :  int     , UpperCAmelCase__   :  int     , UpperCAmelCase__   :  bool						):






							"""simple docstring"""
							super().__init__()
							snake_case   :					Tuple    						=				pool_scales
							snake_case   :					int    						=				align_corners
							snake_case   :					Any    						=				in_channels
							snake_case   :					int    						=				channels
							snake_case   :					Union[str, Any]    						=				[]
							for i, pool_scale in enumerate(__UpperCAmelCase						):
											snake_case   :					Tuple    						=				UperNetPyramidPoolingBlock(pool_scale=__UpperCAmelCase     , in_channels=__UpperCAmelCase     , channels=__UpperCAmelCase						)
											self.blocks.append(__UpperCAmelCase						)
											self.add_module(str(__UpperCAmelCase						)     , __UpperCAmelCase						)



			def      lowerCAmelCase(   self   :  List[Any]     , UpperCAmelCase__   :  torch.Tensor						):






							"""simple docstring"""
							snake_case   :					Optional[Any]    						=				[]
							for ppm in self.blocks:
											snake_case   :					Tuple    						=				ppm(__UpperCAmelCase						)
											snake_case   :					List[str]    						=				nn.functional.interpolate(
											    __UpperCAmelCase     , size=x.size()[2:]     , mode='''bilinear'''     , align_corners=self.align_corners						)
											ppm_outs.append(__UpperCAmelCase						)
							return ppm_outs
class   a_ (			nn.Module      ):

			def __init__(   self   :  Dict     , UpperCAmelCase__   :  Tuple     , UpperCAmelCase__   :  List[Any]						):






							"""simple docstring"""
							super().__init__()

							snake_case   :					str    						=				config
							snake_case   :					str    						=				config.pool_scales  # e.g. (1, 2, 3, 6)
							snake_case   :					List[Any]    						=				in_channels
							snake_case   :					Any    						=				config.hidden_size
							snake_case   :					Optional[Any]    						=				False
							snake_case   :					Any    						=				nn.Convad(self.channels     , config.num_labels     , kernel_size=1						)

							# PSP Module
							snake_case   :					Dict    						=				UperNetPyramidPoolingModule(
							    self.pool_scales     , self.in_channels[-1]     , self.channels     , align_corners=self.align_corners     , )
							snake_case   :					List[str]    						=				UperNetConvModule(
							    self.in_channels[-1] + len(self.pool_scales						) * self.channels     , self.channels     , kernel_size=3     , padding=1     , )
							# FPN Module
							snake_case   :					Tuple    						=				nn.ModuleList()
							snake_case   :					int    						=				nn.ModuleList()
							for in_channels in self.in_channels[:-1]:  # skip the top layer
											snake_case   :					Optional[int]    						=				UperNetConvModule(__UpperCAmelCase     , self.channels     , kernel_size=1						)
											snake_case   :					Optional[Any]    						=				UperNetConvModule(self.channels     , self.channels     , kernel_size=3     , padding=1						)
											self.lateral_convs.append(__UpperCAmelCase						)
											self.fpn_convs.append(__UpperCAmelCase						)

							snake_case   :					List[Any]    						=				UperNetConvModule(
							    len(self.in_channels						) * self.channels     , self.channels     , kernel_size=3     , padding=1     , )

			def      lowerCAmelCase(   self   :  str						):






							"""simple docstring"""
							self.apply(self._init_weights						)

			def      lowerCAmelCase(   self   :  Dict     , UpperCAmelCase__   :  Optional[int]						):






							"""simple docstring"""


							if isinstance(__UpperCAmelCase     , nn.Convad						):
											module.weight.data.normal_(mean=0.0     , std=self.config.initializer_range						)
											if module.bias is not None:
															module.bias.data.zero_()

			def      lowerCAmelCase(   self   :  Optional[int]     , UpperCAmelCase__   :  Tuple						):






							"""simple docstring"""
							snake_case   :					List[Any]    						=				inputs[-1]
							snake_case   :					List[Any]    						=				[x]
							psp_outs.extend(self.psp_modules(__UpperCAmelCase						)						)
							snake_case   :					int    						=				torch.cat(__UpperCAmelCase     , dim=1						)
							snake_case   :					Union[str, Any]    						=				self.bottleneck(__UpperCAmelCase						)

							return output



			def      lowerCAmelCase(   self   :  Tuple     , UpperCAmelCase__   :  torch.Tensor						):






							"""simple docstring"""
							snake_case   :					str    						=				[lateral_conv(encoder_hidden_states[i]						) for i, lateral_conv in enumerate(self.lateral_convs						)]

							laterals.append(self.psp_forward(__UpperCAmelCase						)						)

							# build top-down path
							snake_case   :					Optional[int]    						=				len(__UpperCAmelCase						)
							for i in range(used_backbone_levels - 1     , 0     , -1						):
											snake_case   :					Any    						=				laterals[i - 1].shape[2:]
											snake_case   :					List[str]    						=				laterals[i - 1] + nn.functional.interpolate(
											    laterals[i]     , size=__UpperCAmelCase     , mode='''bilinear'''     , align_corners=self.align_corners						)

							# build outputs
							snake_case   :					Union[str, Any]    						=				[self.fpn_convs[i](laterals[i]						) for i in range(used_backbone_levels - 1						)]
							# append psp feature
							fpn_outs.append(laterals[-1]						)

							for i in range(used_backbone_levels - 1     , 0     , -1						):
											snake_case   :					int    						=				nn.functional.interpolate(
											    fpn_outs[i]     , size=fpn_outs[0].shape[2:]     , mode='''bilinear'''     , align_corners=self.align_corners						)
							snake_case   :					int    						=				torch.cat(__UpperCAmelCase     , dim=1						)
							snake_case   :					List[str]    						=				self.fpn_bottleneck(__UpperCAmelCase						)
							snake_case   :					List[Any]    						=				self.classifier(__UpperCAmelCase						)

							return output
class   a_ (			nn.Module      ):

			def __init__(   self   :  List[str]     , UpperCAmelCase__   :  Optional[int]     , UpperCAmelCase__   :  int = 2     , UpperCAmelCase__   :  int = 3     , UpperCAmelCase__   :  Union[int, Tuple[int, int]] = 1						):






							"""simple docstring"""
							super().__init__()

							snake_case   :					List[Any]    						=				config
							snake_case   :					Tuple    						=				config.auxiliary_in_channels
							snake_case   :					str    						=				config.auxiliary_channels
							snake_case   :					List[str]    						=				config.auxiliary_num_convs
							snake_case   :					Any    						=				config.auxiliary_concat_input
							snake_case   :					int    						=				in_index

							snake_case   :					List[str]    						=				(kernel_size // 2) * dilation
							snake_case   :					str    						=				[]
							convs.append(
							    UperNetConvModule(
							        self.in_channels     , self.channels     , kernel_size=__UpperCAmelCase     , padding=__UpperCAmelCase     , dilation=__UpperCAmelCase						)						)
							for i in range(self.num_convs - 1						):
											convs.append(
											    UperNetConvModule(
											        self.channels     , self.channels     , kernel_size=__UpperCAmelCase     , padding=__UpperCAmelCase     , dilation=__UpperCAmelCase						)						)
							if self.num_convs == 0:
											snake_case   :					Dict    						=				nn.Identity()
							else:
											snake_case   :					List[str]    						=				nn.Sequential(*__UpperCAmelCase						)
							if self.concat_input:
											snake_case   :					Optional[int]    						=				UperNetConvModule(
											    self.in_channels + self.channels     , self.channels     , kernel_size=__UpperCAmelCase     , padding=kernel_size // 2						)

							snake_case   :					Dict    						=				nn.Convad(self.channels     , config.num_labels     , kernel_size=1						)

			def      lowerCAmelCase(   self   :  Tuple						):






							"""simple docstring"""
							self.apply(self._init_weights						)

			def      lowerCAmelCase(   self   :  Dict     , UpperCAmelCase__   :  Optional[Any]						):






							"""simple docstring"""


							if isinstance(__UpperCAmelCase     , nn.Convad						):
											module.weight.data.normal_(mean=0.0     , std=self.config.initializer_range						)
											if module.bias is not None:
															module.bias.data.zero_()



			def      lowerCAmelCase(   self   :  List[Any]     , UpperCAmelCase__   :  torch.Tensor						):






							"""simple docstring"""
							snake_case   :					List[Any]    						=				encoder_hidden_states[self.in_index]
							snake_case   :					Optional[int]    						=				self.convs(__UpperCAmelCase						)
							if self.concat_input:
											snake_case   :					Optional[int]    						=				self.conv_cat(torch.cat([hidden_states, output]     , dim=1						)						)
							snake_case   :					List[Any]    						=				self.classifier(__UpperCAmelCase						)
							return output
class   a_ (			a      ):
			A__      :			Optional[int]       	=  UperNetConfig
			A__      :			Dict       	=  'pixel_values'
			A__      :			Tuple       	=  True

			def      lowerCAmelCase(   self   :  List[Any]     , UpperCAmelCase__   :  str						):






							"""simple docstring"""


							if isinstance(__UpperCAmelCase     , __UpperCAmelCase						):
											module.backbone.init_weights()
											module.decode_head.init_weights()
											module.auxiliary_head.init_weights()

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






							"""simple docstring"""
							self.backbone.init_weights()
							self.decode_head.init_weights()
							self.auxiliary_head.init_weights()



			def      lowerCAmelCase(   self   :  Optional[int]     , UpperCAmelCase__   :  List[str]     , UpperCAmelCase__   :  str=False						):






							"""simple docstring"""


							if isinstance(__UpperCAmelCase     , __UpperCAmelCase						):
											snake_case   :					int    						=				value
_a     :    Union[str, Any]         =						R'\n    Parameters:\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

_a     :    List[Any]         =						R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n            `attentions` under returned tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n            returned tensors for more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'
@add_start_docstrings(
    'UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.'		,							a		,							)
class   a_ (			a      ):

			def __init__(   self   :  Tuple     , UpperCAmelCase__   :  Dict						):






							"""simple docstring"""
							super().__init__(__UpperCAmelCase						)

							snake_case   :					Optional[int]    						=				AutoBackbone.from_config(config.backbone_config						)

							# Semantic segmentation head(s)
							snake_case   :					List[str]    						=				UperNetHead(__UpperCAmelCase     , in_channels=self.backbone.channels						)
							snake_case   :					str    						=				UperNetFCNHead(__UpperCAmelCase						) if config.use_auxiliary_head else None

							# Initialize weights and apply final processing
							self.post_init()



			@add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('''batch_size, sequence_length'''						)						)
			@replace_return_docstrings(output_type=__UpperCAmelCase     , config_class=_CONFIG_FOR_DOC						)
			def      lowerCAmelCase(   self   :  Any     , UpperCAmelCase__   :  Optional[torch.Tensor] = None     , UpperCAmelCase__   :  Optional[bool] = None     , UpperCAmelCase__   :  Optional[bool] = None     , UpperCAmelCase__   :  Optional[torch.Tensor] = None     , UpperCAmelCase__   :  Optional[bool] = None     , ):






							"""simple docstring"""
							snake_case   :					str    						=				return_dict if return_dict is not None else self.config.use_return_dict
							snake_case   :					Any    						=				(
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							snake_case   :					Optional[int]    						=				output_attentions if output_attentions is not None else self.config.output_attentions

							snake_case   :					Optional[Any]    						=				self.backbone.forward_with_filtered_kwargs(
							    __UpperCAmelCase     , output_hidden_states=__UpperCAmelCase     , output_attentions=__UpperCAmelCase						)
							snake_case   :					Optional[Any]    						=				outputs.feature_maps

							snake_case   :					List[str]    						=				self.decode_head(__UpperCAmelCase						)
							snake_case   :					int    						=				nn.functional.interpolate(__UpperCAmelCase     , size=pixel_values.shape[2:]     , mode='''bilinear'''     , align_corners=__UpperCAmelCase						)

							snake_case   :					Union[str, Any]    						=				None
							if self.auxiliary_head is not None:
											snake_case   :					int    						=				self.auxiliary_head(__UpperCAmelCase						)
											snake_case   :					int    						=				nn.functional.interpolate(
											    __UpperCAmelCase     , size=pixel_values.shape[2:]     , mode='''bilinear'''     , align_corners=__UpperCAmelCase						)

							snake_case   :					int    						=				None
							if labels is not None:
											if self.config.num_labels == 1:
															raise ValueError('''The number of labels should be greater than one'''						)
											else:
															# compute weighted loss
															snake_case   :					List[Any]    						=				CrossEntropyLoss(ignore_index=self.config.loss_ignore_index						)
															snake_case   :					Dict    						=				loss_fct(__UpperCAmelCase     , __UpperCAmelCase						)
															snake_case   :					Union[str, Any]    						=				loss_fct(__UpperCAmelCase     , __UpperCAmelCase						)
															snake_case   :					Union[str, Any]    						=				main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

							if not return_dict:
											if output_hidden_states:
															snake_case   :					int    						=				(logits,) + outputs[1:]
											else:
															snake_case   :					str    						=				(logits,) + outputs[2:]
											return ((loss,) + output) if loss is not None else output

							return SemanticSegmenterOutput(
							    loss=__UpperCAmelCase     , logits=__UpperCAmelCase     , hidden_states=outputs.hidden_states     , attentions=outputs.attentions     , )








import gc
import unittest

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

from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel
from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings
from diffusers.utils import load_numpy, slow, torch_device
from diffusers.utils.testing_utils import require_torch_gpu


UpperCAmelCase__							  =						False






class 						lowercase_   (      unittest.TestCase  ):






      '''simple docstring'''




      def  __lowerCAmelCase   ( self :		Dict    )       ->str:




       """simple docstring"""


       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()







      @property
      def  __lowerCAmelCase   ( self :		List[str]    )       ->Any:




       """simple docstring"""


       return 12







      @property
      def  __lowerCAmelCase   ( self :		Optional[Any]    )       ->Dict:




       """simple docstring"""


       return 12







      @property
      def  __lowerCAmelCase   ( self :		Any    )       ->Any:




       """simple docstring"""


       return 32







      @property
      def  __lowerCAmelCase   ( self :		int    )       ->List[str]:




       """simple docstring"""


       torch.manual_seed(0    )
       a						    = VQModel(
           block_out_channels=[32, 64]					,   in_channels=3					,   out_channels=3					,   down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']					,   up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']					,   latent_channels=3					,   num_vq_embeddings=self.num_embed					,   vq_embed_dim=3					,   )
       return model







      @property
      def  __lowerCAmelCase   ( self :		str    )       ->str:




       """simple docstring"""


       a						    = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    )
       return tokenizer







      @property
      def  __lowerCAmelCase   ( self :		str    )       ->Union[str, Any]:




       """simple docstring"""


       torch.manual_seed(0    )
       a						    = CLIPTextConfig(
           bos_token_id=0					,   eos_token_id=2					,   hidden_size=self.text_embedder_hidden_size					,   intermediate_size=37					,   layer_norm_eps=1e-0_5					,   num_attention_heads=4					,   num_hidden_layers=5					,   pad_token_id=1					,   vocab_size=1_000					,   )
       return CLIPTextModel(__UpperCAmelCase    )







      @property
      def  __lowerCAmelCase   ( self :		Any    )       ->Tuple:




       """simple docstring"""


       torch.manual_seed(0    )

       a						    = 12
       a						    = 12

       a						    = {
           '''attention_bias''': True,
           '''cross_attention_dim''': 32,
           '''attention_head_dim''': height * width,
           '''num_attention_heads''': 1,
           '''num_vector_embeds''': self.num_embed,
           '''num_embeds_ada_norm''': self.num_embeds_ada_norm,
           '''norm_num_groups''': 32,
           '''sample_size''': width,
           '''activation_fn''': '''geglu-approximate''',
       }

       a						    = TransformeraDModel(**__UpperCAmelCase    )
       return model







      def  __lowerCAmelCase   ( self :		Dict    )       ->Any:




       """simple docstring"""


       a						    = '''cpu'''

       a						    = self.dummy_vqvae
       a						    = self.dummy_text_encoder
       a						    = self.dummy_tokenizer
       a						    = self.dummy_transformer
       a						    = VQDiffusionScheduler(self.num_embed    )
       a						    = LearnedClassifierFreeSamplingEmbeddings(learnable=__UpperCAmelCase    )

       a						    = VQDiffusionPipeline(
           vqvae=__UpperCAmelCase					,   text_encoder=__UpperCAmelCase					,   tokenizer=__UpperCAmelCase					,   transformer=__UpperCAmelCase					,   scheduler=__UpperCAmelCase					,   learned_classifier_free_sampling_embeddings=__UpperCAmelCase					,   )
       a						    = pipe.to(__UpperCAmelCase    )
       pipe.set_progress_bar_config(disable=__UpperCAmelCase    )

       a						    = '''teddy bear playing in the pool'''

       a						    = torch.Generator(device=__UpperCAmelCase    ).manual_seed(0    )
       a						    = pipe([prompt]					,   generator=__UpperCAmelCase					,   num_inference_steps=2					,   output_type='''np'''    )
       a						    = output.images

       a						    = torch.Generator(device=__UpperCAmelCase    ).manual_seed(0    )
       a						    = pipe(
           [prompt]					,   generator=__UpperCAmelCase					,   output_type='''np'''					,   return_dict=__UpperCAmelCase					,   num_inference_steps=2    )[0]

       a						    = image[0, -3:, -3:, -1]
       a						    = image_from_tuple[0, -3:, -3:, -1]

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

       a						    = np.array([0.6551, 0.6168, 0.5008, 0.5676, 0.5659, 0.4295, 0.6073, 0.5599, 0.4992]    )

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







      def  __lowerCAmelCase   ( self :		Tuple    )       ->str:




       """simple docstring"""


       a						    = '''cpu'''

       a						    = self.dummy_vqvae
       a						    = self.dummy_text_encoder
       a						    = self.dummy_tokenizer
       a						    = self.dummy_transformer
       a						    = VQDiffusionScheduler(self.num_embed    )
       a						    = LearnedClassifierFreeSamplingEmbeddings(
           learnable=__UpperCAmelCase					,   hidden_size=self.text_embedder_hidden_size					,   length=tokenizer.model_max_length    )

       a						    = VQDiffusionPipeline(
           vqvae=__UpperCAmelCase					,   text_encoder=__UpperCAmelCase					,   tokenizer=__UpperCAmelCase					,   transformer=__UpperCAmelCase					,   scheduler=__UpperCAmelCase					,   learned_classifier_free_sampling_embeddings=__UpperCAmelCase					,   )
       a						    = pipe.to(__UpperCAmelCase    )
       pipe.set_progress_bar_config(disable=__UpperCAmelCase    )

       a						    = '''teddy bear playing in the pool'''

       a						    = torch.Generator(device=__UpperCAmelCase    ).manual_seed(0    )
       a						    = pipe([prompt]					,   generator=__UpperCAmelCase					,   num_inference_steps=2					,   output_type='''np'''    )
       a						    = output.images

       a						    = torch.Generator(device=__UpperCAmelCase    ).manual_seed(0    )
       a						    = pipe(
           [prompt]					,   generator=__UpperCAmelCase					,   output_type='''np'''					,   return_dict=__UpperCAmelCase					,   num_inference_steps=2    )[0]

       a						    = image[0, -3:, -3:, -1]
       a						    = image_from_tuple[0, -3:, -3:, -1]

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

       a						    = np.array([0.6693, 0.6075, 0.4959, 0.5701, 0.5583, 0.4333, 0.6171, 0.5684, 0.4988]    )

       assert np.abs(image_slice.flatten() - expected_slice    ).max() < 2.0
       assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 1e-2






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






      '''simple docstring'''




      def  __lowerCAmelCase   ( self :		Union[str, Any]    )       ->Union[str, Any]:




       """simple docstring"""


       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()







      def  __lowerCAmelCase   ( self :		Dict    )       ->int:




       """simple docstring"""


       a						    = load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy'''    )

       a						    = VQDiffusionPipeline.from_pretrained('''microsoft/vq-diffusion-ithq'''    )
       a						    = pipeline.to(__UpperCAmelCase    )
       pipeline.set_progress_bar_config(disable=__UpperCAmelCase    )

       # requires GPU generator for gumbel softmax
       # don't use GPU generator in tests though
       a						    = torch.Generator(device=__UpperCAmelCase    ).manual_seed(0    )
       a						    = pipeline(
           '''teddy bear playing in the pool'''					,   num_images_per_prompt=1					,   generator=__UpperCAmelCase					,   output_type='''np'''					,   )

       a						    = output.images[0]

       assert image.shape == (256, 256, 3)
       assert np.abs(expected_image - image    ).max() < 2.0


