



from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


__lowerCamelCase         =			logging.get_logger(__name__)

# General docstring
__lowerCamelCase         =			'''ResNetConfig'''

# Base docstring
__lowerCamelCase         =			'''microsoft/resnet-50'''
__lowerCamelCase         =			[1, 2048, 7, 7]

# Image classification docstring
__lowerCamelCase         =			'''microsoft/resnet-50'''
__lowerCamelCase         =			'''tiger cat'''

__lowerCamelCase         =			[
    '''microsoft/resnet-50''',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]


class   snake_case_ (nn.Module  ):




       """simple docstring"""






       def __init__(     self     ,lowercase     ,lowercase     ,lowercase = 3     ,lowercase = 1     ,lowercase = "relu"):

             """simple docstring"""





             super().__init__()
             UpperCAmelCase_  :	List[str]				      =		nn.Convad(
                 lowercase     ,lowercase     ,kernel_size=lowercase     ,stride=lowercase     ,padding=kernel_size // 2     ,bias=lowercase)
             UpperCAmelCase_  :	int				      =		nn.BatchNormad(lowercase)
             UpperCAmelCase_  :	Optional[int]				      =		ACTaFN[activation] if activation is not None else nn.Identity()



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		self.convolution(lowercase)
             UpperCAmelCase_  :	Optional[Any]				      =		self.normalization(lowercase)
             UpperCAmelCase_  :	int				      =		self.activation(lowercase)
             return hidden_state


class   snake_case_ (nn.Module  ):




       """simple docstring"""






       def __init__(     self     ,lowercase):

             """simple docstring"""





             super().__init__()
             UpperCAmelCase_  :	Optional[Any]				      =		ResNetConvLayer(
                 config.num_channels     ,config.embedding_size     ,kernel_size=7     ,stride=2     ,activation=config.hidden_act)
             UpperCAmelCase_  :	List[Any]				      =		nn.MaxPoolad(kernel_size=3     ,stride=2     ,padding=1)
             UpperCAmelCase_  :	Any				      =		config.num_channels



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		pixel_values.shape[1]
             if num_channels != self.num_channels:
                   raise ValueError(
                       "Make sure that the channel dimension of the pixel values match with the one set in the configuration.")
             UpperCAmelCase_  :	str				      =		self.embedder(lowercase)
             UpperCAmelCase_  :	int				      =		self.pooler(lowercase)
             return embedding


class   snake_case_ (nn.Module  ):




       """simple docstring"""






       def __init__(     self     ,lowercase     ,lowercase     ,lowercase = 2):

             """simple docstring"""





             super().__init__()
             UpperCAmelCase_  :	str				      =		nn.Convad(lowercase     ,lowercase     ,kernel_size=1     ,stride=lowercase     ,bias=lowercase)
             UpperCAmelCase_  :	List[str]				      =		nn.BatchNormad(lowercase)



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		self.convolution(lowercase)
             UpperCAmelCase_  :	Optional[int]				      =		self.normalization(lowercase)
             return hidden_state


class   snake_case_ (nn.Module  ):




       """simple docstring"""






       def __init__(     self     ,lowercase     ,lowercase     ,lowercase = 1     ,lowercase = "relu"):

             """simple docstring"""





             super().__init__()
             UpperCAmelCase_  :	Any				      =		in_channels != out_channels or stride != 1
             UpperCAmelCase_  :	List[Any]				      =		(
                 ResNetShortCut(lowercase     ,lowercase     ,stride=lowercase) if should_apply_shortcut else nn.Identity()
             )
             UpperCAmelCase_  :	Union[str, Any]				      =		nn.Sequential(
                 ResNetConvLayer(lowercase     ,lowercase     ,stride=lowercase)     ,ResNetConvLayer(lowercase     ,lowercase     ,activation=lowercase)     ,)
             UpperCAmelCase_  :	Any				      =		ACTaFN[activation]



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	List[str]				      =		hidden_state
             UpperCAmelCase_  :	Any				      =		self.layer(lowercase)
             UpperCAmelCase_  :	str				      =		self.shortcut(lowercase)
             hidden_state += residual
             UpperCAmelCase_  :	str				      =		self.activation(lowercase)
             return hidden_state


class   snake_case_ (nn.Module  ):




       """simple docstring"""






       def __init__(     self     ,lowercase     ,lowercase     ,lowercase = 1     ,lowercase = "relu"     ,lowercase = 4):

             """simple docstring"""





             super().__init__()
             UpperCAmelCase_  :	Optional[int]				      =		in_channels != out_channels or stride != 1
             UpperCAmelCase_  :	List[str]				      =		out_channels // reduction
             UpperCAmelCase_  :	int				      =		(
                 ResNetShortCut(lowercase     ,lowercase     ,stride=lowercase) if should_apply_shortcut else nn.Identity()
             )
             UpperCAmelCase_  :	Dict				      =		nn.Sequential(
                 ResNetConvLayer(lowercase     ,lowercase     ,kernel_size=1)     ,ResNetConvLayer(lowercase     ,lowercase     ,stride=lowercase)     ,ResNetConvLayer(lowercase     ,lowercase     ,kernel_size=1     ,activation=lowercase)     ,)
             UpperCAmelCase_  :	int				      =		ACTaFN[activation]



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		hidden_state
             UpperCAmelCase_  :	Tuple				      =		self.layer(lowercase)
             UpperCAmelCase_  :	Any				      =		self.shortcut(lowercase)
             hidden_state += residual
             UpperCAmelCase_  :	Optional[Any]				      =		self.activation(lowercase)
             return hidden_state


class   snake_case_ (nn.Module  ):




       """simple docstring"""






       def __init__(     self     ,lowercase     ,lowercase     ,lowercase     ,lowercase = 2     ,lowercase = 2     ,):

             """simple docstring"""





             super().__init__()

             UpperCAmelCase_  :	Optional[int]				      =		ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer

             UpperCAmelCase_  :	Optional[Any]				      =		nn.Sequential(
                 # downsampling is done in the first layer with stride of 2
                 layer(lowercase     ,lowercase     ,stride=lowercase     ,activation=config.hidden_act)     ,*[layer(lowercase     ,lowercase     ,activation=config.hidden_act) for _ in range(depth - 1)]     ,)



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		input
             for layer in self.layers:
                   UpperCAmelCase_  :	Dict				      =		layer(lowercase)
             return hidden_state


class   snake_case_ (nn.Module  ):




       """simple docstring"""






       def __init__(     self     ,lowercase):

             """simple docstring"""





             super().__init__()
             UpperCAmelCase_  :	Dict				      =		nn.ModuleList([])
             # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
             self.stages.append(
                 ResNetStage(
                     lowercase     ,config.embedding_size     ,config.hidden_sizes[0]     ,stride=2 if config.downsample_in_first_stage else 1     ,depth=config.depths[0]     ,))
             UpperCAmelCase_  :	Optional[Any]				      =		zip(config.hidden_sizes     ,config.hidden_sizes[1:])
             for (in_channels, out_channels), depth in zip(lowercase     ,config.depths[1:]):
                   self.stages.append(ResNetStage(lowercase     ,lowercase     ,lowercase     ,depth=lowercase))



       def  A_   (     self     ,lowercase     ,lowercase = False     ,lowercase = True):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		() if output_hidden_states else None

             for stage_module in self.stages:
                   if output_hidden_states:
                         UpperCAmelCase_  :	List[str]				      =		hidden_states + (hidden_state,)

                   UpperCAmelCase_  :	Optional[int]				      =		stage_module(lowercase)

             if output_hidden_states:
                   UpperCAmelCase_  :	Tuple				      =		hidden_states + (hidden_state,)

             if not return_dict:
                   return tuple(v for v in [hidden_state, hidden_states] if v is not None)

             return BaseModelOutputWithNoAttention(
                 last_hidden_state=lowercase     ,hidden_states=lowercase     ,)


class   snake_case_ (lowercase__  ):




       """simple docstring"""






       _lowerCamelCase			    =				ResNetConfig
       _lowerCamelCase			    =				"""resnet"""
       _lowerCamelCase			    =				"""pixel_values"""
       _lowerCamelCase			    =				True



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             if isinstance(lowercase     ,nn.Convad):
                   nn.init.kaiming_normal_(module.weight     ,mode="fan_out"     ,nonlinearity="relu")
             elif isinstance(lowercase     ,(nn.BatchNormad, nn.GroupNorm)):
                   nn.init.constant_(module.weight     ,1)
                   nn.init.constant_(module.bias     ,0)



       def  A_   (     self     ,lowercase     ,lowercase=False):

             """simple docstring"""





             if isinstance(lowercase     ,lowercase):
                   UpperCAmelCase_  :	List[Any]				      =		value


__lowerCamelCase         =			R'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

__lowerCamelCase         =			R'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''


@add_start_docstrings(
    """The bare ResNet model outputting raw features without any specific head on top.""" , lowercase__ , )
class   snake_case_ (lowercase__  ):




       """simple docstring"""






       def __init__(     self     ,lowercase):

             """simple docstring"""





             super().__init__(lowercase)
             UpperCAmelCase_  :	Tuple				      =		config
             UpperCAmelCase_  :	int				      =		ResNetEmbeddings(lowercase)
             UpperCAmelCase_  :	Dict				      =		ResNetEncoder(lowercase)
             UpperCAmelCase_  :	Union[str, Any]				      =		nn.AdaptiveAvgPoolad((1, 1))
             # Initialize weights and apply final processing
             self.post_init()



       @add_start_docstrings_to_model_forward(lowercase)
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC     ,output_type=lowercase     ,config_class=_CONFIG_FOR_DOC     ,modality="vision"     ,expected_output=_EXPECTED_OUTPUT_SHAPE     ,)
       def  A_   (     self     ,lowercase     ,lowercase = None     ,lowercase = None):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             UpperCAmelCase_  :	Optional[int]				      =		return_dict if return_dict is not None else self.config.use_return_dict

             UpperCAmelCase_  :	Any				      =		self.embedder(lowercase)

             UpperCAmelCase_  :	Tuple				      =		self.encoder(
                 lowercase     ,output_hidden_states=lowercase     ,return_dict=lowercase)

             UpperCAmelCase_  :	str				      =		encoder_outputs[0]

             UpperCAmelCase_  :	Optional[Any]				      =		self.pooler(lowercase)

             if not return_dict:
                   return (last_hidden_state, pooled_output) + encoder_outputs[1:]

             return BaseModelOutputWithPoolingAndNoAttention(
                 last_hidden_state=lowercase     ,pooler_output=lowercase     ,hidden_states=encoder_outputs.hidden_states     ,)


@add_start_docstrings(
    """
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """ , lowercase__ , )
class   snake_case_ (lowercase__  ):




       """simple docstring"""






       def __init__(     self     ,lowercase):

             """simple docstring"""





             super().__init__(lowercase)
             UpperCAmelCase_  :	Optional[Any]				      =		config.num_labels
             UpperCAmelCase_  :	Union[str, Any]				      =		ResNetModel(lowercase)
             # classification head
             UpperCAmelCase_  :	Optional[int]				      =		nn.Sequential(
                 nn.Flatten()     ,nn.Linear(config.hidden_sizes[-1]     ,config.num_labels) if config.num_labels > 0 else nn.Identity()     ,)
             # initialize weights and apply final processing
             self.post_init()



       @add_start_docstrings_to_model_forward(lowercase)
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT     ,output_type=lowercase     ,config_class=_CONFIG_FOR_DOC     ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT     ,)
       def  A_   (     self     ,lowercase = None     ,lowercase = None     ,lowercase = None     ,lowercase = None     ,):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		return_dict if return_dict is not None else self.config.use_return_dict

             UpperCAmelCase_  :	str				      =		self.resnet(lowercase     ,output_hidden_states=lowercase     ,return_dict=lowercase)

             UpperCAmelCase_  :	int				      =		outputs.pooler_output if return_dict else outputs[1]

             UpperCAmelCase_  :	Any				      =		self.classifier(lowercase)

             UpperCAmelCase_  :	List[Any]				      =		None

             if labels is not None:
                   if self.config.problem_type is None:
                         if self.num_labels == 1:
                               UpperCAmelCase_  :	Any				      =		"regression"
                         elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                               UpperCAmelCase_  :	Optional[Any]				      =		"single_label_classification"
                         else:
                               UpperCAmelCase_  :	Dict				      =		"multi_label_classification"
                   if self.config.problem_type == "regression":
                         UpperCAmelCase_  :	Tuple				      =		MSELoss()
                         if self.num_labels == 1:
                               UpperCAmelCase_  :	Union[str, Any]				      =		loss_fct(logits.squeeze()     ,labels.squeeze())
                         else:
                               UpperCAmelCase_  :	Optional[int]				      =		loss_fct(lowercase     ,lowercase)
                   elif self.config.problem_type == "single_label_classification":
                         UpperCAmelCase_  :	Union[str, Any]				      =		CrossEntropyLoss()
                         UpperCAmelCase_  :	Tuple				      =		loss_fct(logits.view(-1     ,self.num_labels)     ,labels.view(-1))
                   elif self.config.problem_type == "multi_label_classification":
                         UpperCAmelCase_  :	Union[str, Any]				      =		BCEWithLogitsLoss()
                         UpperCAmelCase_  :	List[str]				      =		loss_fct(lowercase     ,lowercase)

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

             return ImageClassifierOutputWithNoAttention(loss=lowercase     ,logits=lowercase     ,hidden_states=outputs.hidden_states)


@add_start_docstrings(
    """
    ResNet backbone, to be used with frameworks like DETR and MaskFormer.
    """ , lowercase__ , )
class   snake_case_ (lowercase__ , lowercase__  ):




       """simple docstring"""






       def __init__(     self     ,lowercase):

             """simple docstring"""





             super().__init__(lowercase)
             super()._init_backbone(lowercase)

             UpperCAmelCase_  :	Optional[Any]				      =		[config.embedding_size] + config.hidden_sizes
             UpperCAmelCase_  :	str				      =		ResNetEmbeddings(lowercase)
             UpperCAmelCase_  :	Tuple				      =		ResNetEncoder(lowercase)

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



       @add_start_docstrings_to_model_forward(lowercase)
       @replace_return_docstrings(output_type=lowercase     ,config_class=_CONFIG_FOR_DOC)
       def  A_   (     self     ,lowercase     ,lowercase = None     ,lowercase = None):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		return_dict if return_dict is not None else self.config.use_return_dict
             UpperCAmelCase_  :	Optional[int]				      =		(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )

             UpperCAmelCase_  :	Optional[int]				      =		self.embedder(lowercase)

             UpperCAmelCase_  :	List[str]				      =		self.encoder(lowercase     ,output_hidden_states=lowercase     ,return_dict=lowercase)

             UpperCAmelCase_  :	List[str]				      =		outputs.hidden_states

             UpperCAmelCase_  :	Union[str, Any]				      =		()
             for idx, stage in enumerate(self.stage_names):
                   if stage in self.out_features:
                         feature_maps += (hidden_states[idx],)

             if not return_dict:
                   UpperCAmelCase_  :	Union[str, Any]				      =		(feature_maps,)
                   if output_hidden_states:
                         output += (outputs.hidden_states,)
                   return output

             return BackboneOutput(
                 feature_maps=lowercase     ,hidden_states=outputs.hidden_states if output_hidden_states else None     ,attentions=lowercase     ,)





import gc
import unittest

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

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


class   snake_case_ (lowercase__ , lowercase__ , lowercase__ , unittest.TestCase  ):




       """simple docstring"""






       _lowerCamelCase			    =				AltDiffusionPipeline
       _lowerCamelCase			    =				TEXT_TO_IMAGE_PARAMS
       _lowerCamelCase			    =				TEXT_TO_IMAGE_BATCH_PARAMS
       _lowerCamelCase			    =				TEXT_TO_IMAGE_IMAGE_PARAMS
       _lowerCamelCase			    =				TEXT_TO_IMAGE_IMAGE_PARAMS



       def  A_   (     self):

             """simple docstring"""





             torch.manual_seed(0)
             UpperCAmelCase_  :	Optional[Any]				      =		UNetaDConditionModel(
                 block_out_channels=(32, 64)     ,layers_per_block=2     ,sample_size=32     ,in_channels=4     ,out_channels=4     ,down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")     ,up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")     ,cross_attention_dim=32     ,)
             UpperCAmelCase_  :	Any				      =		DDIMScheduler(
                 beta_start=0.0_0085     ,beta_end=0.012     ,beta_schedule="scaled_linear"     ,clip_sample=lowercase     ,set_alpha_to_one=lowercase     ,)
             torch.manual_seed(0)
             UpperCAmelCase_  :	Any				      =		AutoencoderKL(
                 block_out_channels=[32, 64]     ,in_channels=3     ,out_channels=3     ,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]     ,up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]     ,latent_channels=4     ,)

             # TODO: address the non-deterministic text encoder (fails for save-load tests)
             # torch.manual_seed(0)
             # text_encoder_config = RobertaSeriesConfig(
             #     hidden_size=32,
             #     project_dim=32,
             #     intermediate_size=37,
             #     layer_norm_eps=1e-05,
             #     num_attention_heads=4,
             #     num_hidden_layers=5,
             #     vocab_size=5002,
             # )
             # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

             torch.manual_seed(0)
             UpperCAmelCase_  :	Tuple				      =		CLIPTextConfig(
                 bos_token_id=0     ,eos_token_id=2     ,hidden_size=32     ,projection_dim=32     ,intermediate_size=37     ,layer_norm_eps=1E-05     ,num_attention_heads=4     ,num_hidden_layers=5     ,pad_token_id=1     ,vocab_size=5002     ,)
             UpperCAmelCase_  :	Dict				      =		CLIPTextModel(lowercase)

             UpperCAmelCase_  :	List[Any]				      =		XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta")
             UpperCAmelCase_  :	List[str]				      =		77

             UpperCAmelCase_  :	Union[str, Any]				      =		{
                 "unet": unet,
                 "scheduler": scheduler,
                 "vae": vae,
                 "text_encoder": text_encoder,
                 "tokenizer": tokenizer,
                 "safety_checker": None,
                 "feature_extractor": None,
             }
             return components



       def  A_   (     self     ,lowercase     ,lowercase=0):

             """simple docstring"""





             if str(lowercase).startswith("mps"):
                   UpperCAmelCase_  :	Any				      =		torch.manual_seed(lowercase)
             else:
                   UpperCAmelCase_  :	Dict				      =		torch.Generator(device=lowercase).manual_seed(lowercase)
             UpperCAmelCase_  :	Optional[int]				      =		{
                 "prompt": "A painting of a squirrel eating a burger",
                 "generator": generator,
                 "num_inference_steps": 2,
                 "guidance_scale": 6.0,
                 "output_type": "numpy",
             }
             return inputs



       def  A_   (     self):

             """simple docstring"""





             super().test_attention_slicing_forward_pass(expected_max_diff=3E-3)



       def  A_   (     self):

             """simple docstring"""





             super().test_inference_batch_single_identical(expected_max_diff=3E-3)



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[Any]				      =		"cpu"  # ensure determinism for the device-dependent torch.Generator

             UpperCAmelCase_  :	Any				      =		self.get_dummy_components()
             torch.manual_seed(0)
             UpperCAmelCase_  :	List[Any]				      =		RobertaSeriesConfig(
                 hidden_size=32     ,project_dim=32     ,intermediate_size=37     ,layer_norm_eps=1E-05     ,num_attention_heads=4     ,num_hidden_layers=5     ,vocab_size=5002     ,)
             # TODO: remove after fixing the non-deterministic text encoder
             UpperCAmelCase_  :	Any				      =		RobertaSeriesModelWithTransformation(lowercase)
             UpperCAmelCase_  :	Optional[Any]				      =		text_encoder

             UpperCAmelCase_  :	List[Any]				      =		AltDiffusionPipeline(**lowercase)
             UpperCAmelCase_  :	Union[str, Any]				      =		alt_pipe.to(lowercase)
             alt_pipe.set_progress_bar_config(disable=lowercase)

             UpperCAmelCase_  :	Tuple				      =		self.get_dummy_inputs(lowercase)
             UpperCAmelCase_  :	Optional[Any]				      =		"A photo of an astronaut"
             UpperCAmelCase_  :	str				      =		alt_pipe(**lowercase)
             UpperCAmelCase_  :	List[str]				      =		output.images
             UpperCAmelCase_  :	Dict				      =		image[0, -3:, -3:, -1]

             assert image.shape == (1, 64, 64, 3)
             UpperCAmelCase_  :	Optional[Any]				      =		np.array(
                 [0.574_8162, 0.6044_7145, 0.4882_1217, 0.5010_0636, 0.543_1185, 0.4576_3683, 0.4965_7696, 0.4813_2733, 0.4757_3093])

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



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	List[str]				      =		"cpu"  # ensure determinism for the device-dependent torch.Generator

             UpperCAmelCase_  :	int				      =		self.get_dummy_components()
             UpperCAmelCase_  :	Optional[Any]				      =		PNDMScheduler(skip_prk_steps=lowercase)
             torch.manual_seed(0)
             UpperCAmelCase_  :	Any				      =		RobertaSeriesConfig(
                 hidden_size=32     ,project_dim=32     ,intermediate_size=37     ,layer_norm_eps=1E-05     ,num_attention_heads=4     ,num_hidden_layers=5     ,vocab_size=5002     ,)
             # TODO: remove after fixing the non-deterministic text encoder
             UpperCAmelCase_  :	Union[str, Any]				      =		RobertaSeriesModelWithTransformation(lowercase)
             UpperCAmelCase_  :	Dict				      =		text_encoder
             UpperCAmelCase_  :	Optional[int]				      =		AltDiffusionPipeline(**lowercase)
             UpperCAmelCase_  :	List[Any]				      =		alt_pipe.to(lowercase)
             alt_pipe.set_progress_bar_config(disable=lowercase)

             UpperCAmelCase_  :	str				      =		self.get_dummy_inputs(lowercase)
             UpperCAmelCase_  :	Union[str, Any]				      =		alt_pipe(**lowercase)
             UpperCAmelCase_  :	int				      =		output.images
             UpperCAmelCase_  :	Dict				      =		image[0, -3:, -3:, -1]

             assert image.shape == (1, 64, 64, 3)
             UpperCAmelCase_  :	Tuple				      =		np.array(
                 [0.5160_5093, 0.570_7241, 0.4736_5507, 0.5057_8886, 0.563_3877, 0.464_2503, 0.518_2081, 0.4876_3484, 0.4908_4237])

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


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




       """simple docstring"""






       def  A_   (     self):

             """simple docstring"""





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



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	str				      =		AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion"     ,safety_checker=lowercase)
             UpperCAmelCase_  :	Any				      =		alt_pipe.to(lowercase)
             alt_pipe.set_progress_bar_config(disable=lowercase)

             UpperCAmelCase_  :	Any				      =		"A painting of a squirrel eating a burger"
             UpperCAmelCase_  :	Any				      =		torch.manual_seed(0)
             UpperCAmelCase_  :	Optional[int]				      =		alt_pipe([prompt]     ,generator=lowercase     ,guidance_scale=6.0     ,num_inference_steps=20     ,output_type="np")

             UpperCAmelCase_  :	Dict				      =		output.images

             UpperCAmelCase_  :	List[str]				      =		image[0, -3:, -3:, -1]

             assert image.shape == (1, 512, 512, 3)
             UpperCAmelCase_  :	Dict				      =		np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586])

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



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Union[str, Any]				      =		DDIMScheduler.from_pretrained("BAAI/AltDiffusion"     ,subfolder="scheduler")

             UpperCAmelCase_  :	Optional[int]				      =		AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion"     ,scheduler=lowercase     ,safety_checker=lowercase)
             UpperCAmelCase_  :	List[str]				      =		alt_pipe.to(lowercase)
             alt_pipe.set_progress_bar_config(disable=lowercase)

             UpperCAmelCase_  :	str				      =		"A painting of a squirrel eating a burger"
             UpperCAmelCase_  :	Optional[Any]				      =		torch.manual_seed(0)

             UpperCAmelCase_  :	List[str]				      =		alt_pipe([prompt]     ,generator=lowercase     ,num_inference_steps=2     ,output_type="numpy")
             UpperCAmelCase_  :	int				      =		output.images

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

             assert image.shape == (1, 512, 512, 3)
             UpperCAmelCase_  :	List[Any]				      =		np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323])

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