




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


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

# General docstring
_lowerCamelCase      			=						'UperNetConfig'



class       a					(       nn.Module      ):

     '''simple docstring'''





     def __init__(     self       :      Union[str, Any] ,   __snake_case       :      int ,   __snake_case       :      int ,   __snake_case       :      Union[int, Tuple[int, int]] ,   __snake_case       :      Union[int, Tuple[int, int], str] = 0 ,   __snake_case       :      bool = False ,   __snake_case       :      Union[int, Tuple[int, int]] = 1 ,   ):
         super().__init__()
         UpperCAmelCase_										=					nn.Convad(
             in_channels=__snake_case ,   out_channels=__snake_case ,   kernel_size=__snake_case ,   padding=__snake_case ,   bias=__snake_case ,   dilation=__snake_case ,   )
         UpperCAmelCase_										=					nn.BatchNormad(__snake_case    )
         UpperCAmelCase_										=					nn.ReLU()




     def   lowerCamelCase_       (     self       :      int ,   __snake_case       :      torch.Tensor    ):
         UpperCAmelCase_										=					self.conv(__snake_case    )
         UpperCAmelCase_										=					self.batch_norm(__snake_case    )
         UpperCAmelCase_										=					self.activation(__snake_case    )

         return output



class       a					(       nn.Module      ):

     '''simple docstring'''





     def __init__(     self       :      Union[str, Any] ,   __snake_case       :      int ,   __snake_case       :      int ,   __snake_case       :      int    ):
         super().__init__()
         UpperCAmelCase_										=					[
             nn.AdaptiveAvgPoolad(__snake_case    ),
             UperNetConvModule(__snake_case ,   __snake_case ,   kernel_size=1    ),
         ]
         for i, layer in enumerate(self.layers    ):
             self.add_module(str(__snake_case    ) ,   __snake_case    )




     def   lowerCamelCase_       (     self       :      List[Any] ,   __snake_case       :      torch.Tensor    ):
         UpperCAmelCase_										=					input
         for layer in self.layers:
             UpperCAmelCase_										=					layer(__snake_case    )
         return hidden_state



class       a					(       nn.Module      ):

     '''simple docstring'''





     def __init__(     self       :      Optional[Any] ,   __snake_case       :      Tuple[int, ...] ,   __snake_case       :      int ,   __snake_case       :      int ,   __snake_case       :      bool    ):
         super().__init__()
         UpperCAmelCase_										=					pool_scales
         UpperCAmelCase_										=					align_corners
         UpperCAmelCase_										=					in_channels
         UpperCAmelCase_										=					channels
         UpperCAmelCase_										=					[]
         for i, pool_scale in enumerate(__snake_case    ):
             UpperCAmelCase_										=					UperNetPyramidPoolingBlock(pool_scale=__snake_case ,   in_channels=__snake_case ,   channels=__snake_case    )
             self.blocks.append(__snake_case    )
             self.add_module(str(__snake_case    ) ,   __snake_case    )




     def   lowerCamelCase_       (     self       :      List[str] ,   __snake_case       :      torch.Tensor    ):
         UpperCAmelCase_										=					[]
         for ppm in self.blocks:
             UpperCAmelCase_										=					ppm(__snake_case    )
             UpperCAmelCase_										=					nn.functional.interpolate(
                 __snake_case ,   size=x.size()[2:] ,   mode='''bilinear''' ,   align_corners=self.align_corners    )
             ppm_outs.append(__snake_case    )
         return ppm_outs



class       a					(       nn.Module      ):

     '''simple docstring'''





     def __init__(     self       :      Union[str, Any] ,   __snake_case       :      Dict ,   __snake_case       :      List[str]    ):
         super().__init__()

         UpperCAmelCase_										=					config
         UpperCAmelCase_										=					config.pool_scales  # e.g. (1, 2, 3, 6)
         UpperCAmelCase_										=					in_channels
         UpperCAmelCase_										=					config.hidden_size
         UpperCAmelCase_										=					False
         UpperCAmelCase_										=					nn.Convad(self.channels ,   config.num_labels ,   kernel_size=1    )

         # PSP Module
         UpperCAmelCase_										=					UperNetPyramidPoolingModule(
             self.pool_scales ,   self.in_channels[-1] ,   self.channels ,   align_corners=self.align_corners ,   )
         UpperCAmelCase_										=					UperNetConvModule(
             self.in_channels[-1] + len(self.pool_scales    ) * self.channels ,   self.channels ,   kernel_size=3 ,   padding=1 ,   )
         # FPN Module
         UpperCAmelCase_										=					nn.ModuleList()
         UpperCAmelCase_										=					nn.ModuleList()
         for in_channels in self.in_channels[:-1]:  # skip the top layer
             UpperCAmelCase_										=					UperNetConvModule(__snake_case ,   self.channels ,   kernel_size=1    )
             UpperCAmelCase_										=					UperNetConvModule(self.channels ,   self.channels ,   kernel_size=3 ,   padding=1    )
             self.lateral_convs.append(__snake_case    )
             self.fpn_convs.append(__snake_case    )

         UpperCAmelCase_										=					UperNetConvModule(
             len(self.in_channels    ) * self.channels ,   self.channels ,   kernel_size=3 ,   padding=1 ,   )
     def   lowerCamelCase_       (     self       :      Tuple    ):
         self.apply(self._init_weights    )
     def   lowerCamelCase_       (     self       :      List[Any] ,   __snake_case       :      List[Any]    ):
         if isinstance(__snake_case ,   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] ,   __snake_case       :      int    ):
         UpperCAmelCase_										=					inputs[-1]
         UpperCAmelCase_										=					[x]
         psp_outs.extend(self.psp_modules(__snake_case    )    )
         UpperCAmelCase_										=					torch.cat(__snake_case ,   dim=1    )
         UpperCAmelCase_										=					self.bottleneck(__snake_case    )

         return output




     def   lowerCamelCase_       (     self       :      str ,   __snake_case       :      torch.Tensor    ):
         # build laterals
         UpperCAmelCase_										=					[lateral_conv(encoder_hidden_states[i]    ) for i, lateral_conv in enumerate(self.lateral_convs    )]

         laterals.append(self.psp_forward(__snake_case    )    )

         # build top-down path
         UpperCAmelCase_										=					len(__snake_case    )
         for i in range(used_backbone_levels - 1 ,   0 ,   -1    ):
             UpperCAmelCase_										=					laterals[i - 1].shape[2:]
             UpperCAmelCase_										=					laterals[i - 1] + nn.functional.interpolate(
                 laterals[i] ,   size=__snake_case ,   mode='''bilinear''' ,   align_corners=self.align_corners    )

         # build outputs
         UpperCAmelCase_										=					[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    ):
             UpperCAmelCase_										=					nn.functional.interpolate(
                 fpn_outs[i] ,   size=fpn_outs[0].shape[2:] ,   mode='''bilinear''' ,   align_corners=self.align_corners    )
         UpperCAmelCase_										=					torch.cat(__snake_case ,   dim=1    )
         UpperCAmelCase_										=					self.fpn_bottleneck(__snake_case    )
         UpperCAmelCase_										=					self.classifier(__snake_case    )

         return output



class       a					(       nn.Module      ):

     '''simple docstring'''





     def __init__(     self       :      Any ,   __snake_case       :      int ,   __snake_case       :      int = 2 ,   __snake_case       :      int = 3 ,   __snake_case       :      Union[int, Tuple[int, int]] = 1    ):
         super().__init__()

         UpperCAmelCase_										=					config
         UpperCAmelCase_										=					config.auxiliary_in_channels
         UpperCAmelCase_										=					config.auxiliary_channels
         UpperCAmelCase_										=					config.auxiliary_num_convs
         UpperCAmelCase_										=					config.auxiliary_concat_input
         UpperCAmelCase_										=					in_index

         UpperCAmelCase_										=					(kernel_size // 2) * dilation
         UpperCAmelCase_										=					[]
         convs.append(
             UperNetConvModule(
                 self.in_channels ,   self.channels ,   kernel_size=__snake_case ,   padding=__snake_case ,   dilation=__snake_case    )    )
         for i in range(self.num_convs - 1    ):
             convs.append(
                 UperNetConvModule(
                     self.channels ,   self.channels ,   kernel_size=__snake_case ,   padding=__snake_case ,   dilation=__snake_case    )    )
         if self.num_convs == 0:
             UpperCAmelCase_										=					nn.Identity()
         else:
             UpperCAmelCase_										=					nn.Sequential(*__snake_case    )
         if self.concat_input:
             UpperCAmelCase_										=					UperNetConvModule(
                 self.in_channels + self.channels ,   self.channels ,   kernel_size=__snake_case ,   padding=kernel_size // 2    )

         UpperCAmelCase_										=					nn.Convad(self.channels ,   config.num_labels ,   kernel_size=1    )
     def   lowerCamelCase_       (     self       :      Tuple    ):
         self.apply(self._init_weights    )
     def   lowerCamelCase_       (     self       :      Union[str, Any] ,   __snake_case       :      Tuple    ):
         if isinstance(__snake_case ,   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[str] ,   __snake_case       :      torch.Tensor    ):
         # just take the relevant feature maps
         UpperCAmelCase_										=					encoder_hidden_states[self.in_index]
         UpperCAmelCase_										=					self.convs(__snake_case    )
         if self.concat_input:
             UpperCAmelCase_										=					self.conv_cat(torch.cat([hidden_states, output] ,   dim=1    )    )
         UpperCAmelCase_										=					self.classifier(__snake_case    )
         return output



class       a					(       _A      ):

     '''simple docstring'''





     lowerCAmelCase    :	Tuple       		=  UperNetConfig
     lowerCAmelCase    :	Tuple       		=  'pixel_values'
     lowerCAmelCase    :	Tuple       		=  True
     def   lowerCamelCase_       (     self       :      List[str] ,   __snake_case       :      int    ):
         if isinstance(__snake_case ,   __snake_case    ):
             module.backbone.init_weights()
             module.decode_head.init_weights()
             module.auxiliary_head.init_weights()
     def   lowerCamelCase_       (     self       :      List[str]    ):
         self.backbone.init_weights()
         self.decode_head.init_weights()
         self.auxiliary_head.init_weights()




     def   lowerCamelCase_       (     self       :      Union[str, Any] ,   __snake_case       :      Dict ,   __snake_case       :      int=False    ):
         if isinstance(__snake_case ,   __snake_case    ):
             UpperCAmelCase_										=					value


_lowerCamelCase      			=						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'

_lowerCamelCase      			=						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      ):

     '''simple docstring'''





     def __init__(     self       :      Dict ,   __snake_case       :      Any    ):
         super().__init__(__snake_case    )

         UpperCAmelCase_										=					AutoBackbone.from_config(config.backbone_config    )

         # Semantic segmentation head(s)
         UpperCAmelCase_										=					UperNetHead(__snake_case ,   in_channels=self.backbone.channels    )
         UpperCAmelCase_										=					UperNetFCNHead(__snake_case    ) 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=__snake_case ,   config_class=_CONFIG_FOR_DOC    )
     def   lowerCamelCase_       (     self       :      Union[str, Any] ,   __snake_case       :      Optional[torch.Tensor] = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[torch.Tensor] = None ,   __snake_case       :      Optional[bool] = None ,   ):
         UpperCAmelCase_										=					return_dict if return_dict is not None else self.config.use_return_dict
         UpperCAmelCase_										=					(
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         UpperCAmelCase_										=					output_attentions if output_attentions is not None else self.config.output_attentions

         UpperCAmelCase_										=					self.backbone.forward_with_filtered_kwargs(
             __snake_case ,   output_hidden_states=__snake_case ,   output_attentions=__snake_case    )
         UpperCAmelCase_										=					outputs.feature_maps

         UpperCAmelCase_										=					self.decode_head(__snake_case    )
         UpperCAmelCase_										=					nn.functional.interpolate(__snake_case ,   size=pixel_values.shape[2:] ,   mode='''bilinear''' ,   align_corners=__snake_case    )

         UpperCAmelCase_										=					None
         if self.auxiliary_head is not None:
             UpperCAmelCase_										=					self.auxiliary_head(__snake_case    )
             UpperCAmelCase_										=					nn.functional.interpolate(
                 __snake_case ,   size=pixel_values.shape[2:] ,   mode='''bilinear''' ,   align_corners=__snake_case    )

         UpperCAmelCase_										=					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
                 UpperCAmelCase_										=					CrossEntropyLoss(ignore_index=self.config.loss_ignore_index    )
                 UpperCAmelCase_										=					loss_fct(__snake_case ,   __snake_case    )
                 UpperCAmelCase_										=					loss_fct(__snake_case ,   __snake_case    )
                 UpperCAmelCase_										=					main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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

         return SemanticSegmenterOutput(
             loss=__snake_case ,   logits=__snake_case ,   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


_lowerCamelCase      			=						False



class       a					(       unittest.TestCase      ):

     '''simple docstring'''





     def   lowerCamelCase_       (     self       :      str    ):
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()
     @property
     def   lowerCamelCase_       (     self       :      Any    ):
         return 12
     @property
     def   lowerCamelCase_       (     self       :      Union[str, Any]    ):
         return 12
     @property
     def   lowerCamelCase_       (     self       :      Optional[Any]    ):
         return 32
     @property
     def   lowerCamelCase_       (     self       :      List[Any]    ):
         torch.manual_seed(0    )
         UpperCAmelCase_										=					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       :      Tuple    ):
         UpperCAmelCase_										=					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    )
         return tokenizer
     @property
     def   lowerCamelCase_       (     self       :      int    ):
         torch.manual_seed(0    )
         UpperCAmelCase_										=					CLIPTextConfig(
             bos_token_id=0 ,   eos_token_id=2 ,   hidden_size=self.text_embedder_hidden_size ,   intermediate_size=37 ,   layer_norm_eps=1E-05 ,   num_attention_heads=4 ,   num_hidden_layers=5 ,   pad_token_id=1 ,   vocab_size=10_00 ,   )
         return CLIPTextModel(__snake_case    )
     @property
     def   lowerCamelCase_       (     self       :      Union[str, Any]    ):
         torch.manual_seed(0    )

         UpperCAmelCase_										=					12
         UpperCAmelCase_										=					12

         UpperCAmelCase_										=					{
             '''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''',
         }

         UpperCAmelCase_										=					TransformeraDModel(**__snake_case    )
         return model
     def   lowerCamelCase_       (     self       :      int    ):
         UpperCAmelCase_										=					'''cpu'''

         UpperCAmelCase_										=					self.dummy_vqvae
         UpperCAmelCase_										=					self.dummy_text_encoder
         UpperCAmelCase_										=					self.dummy_tokenizer
         UpperCAmelCase_										=					self.dummy_transformer
         UpperCAmelCase_										=					VQDiffusionScheduler(self.num_embed    )
         UpperCAmelCase_										=					LearnedClassifierFreeSamplingEmbeddings(learnable=__snake_case    )

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

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

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

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

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

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

         UpperCAmelCase_										=					np.array([0.6_551, 0.6_168, 0.5_008, 0.5_676, 0.5_659, 0.4_295, 0.6_073, 0.5_599, 0.4_992]    )

         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       :      str    ):
         UpperCAmelCase_										=					'''cpu'''

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

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

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

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

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

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

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

         UpperCAmelCase_										=					np.array([0.6_693, 0.6_075, 0.4_959, 0.5_701, 0.5_583, 0.4_333, 0.6_171, 0.5_684, 0.4_988]    )

         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       a					(       unittest.TestCase      ):

     '''simple docstring'''





     def   lowerCamelCase_       (     self       :      Optional[int]    ):
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




     def   lowerCamelCase_       (     self       :      Optional[int]    ):
         UpperCAmelCase_										=					load_numpy(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy'''    )

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

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

         UpperCAmelCase_										=					output.images[0]

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





