




"""simple docstring"""






from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...file_utils import TensorType, is_torch_available
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


lowercase__			=		logging.get_logger(__name__)

lowercase__			=		{
    '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json''',
    # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
}






class lowerCAmelCase__      (	_a		):






			'''simple docstring'''



			lowerCamelCase__ =     '''blenderbot-small'''
			lowerCamelCase__ =     ['''past_key_values''']
			lowerCamelCase__ =     {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}
			def __init__(    self    , lowercase=50265    , lowercase=512    , lowercase=8    , lowercase=2048    , lowercase=16    , lowercase=8    , lowercase=2048    , lowercase=16    , lowercase=0.0    , lowercase=0.0    , lowercase=True    , lowercase=True    , lowercase="gelu"    , lowercase=512    , lowercase=0.1    , lowercase=0.0    , lowercase=0.0    , lowercase=0.02    , lowercase=1    , lowercase=False    , lowercase=0    , lowercase=1    , lowercase=2    , lowercase=2    , **lowercase    , ):
							_lowerCamelCase	:     str       =       vocab_size
							_lowerCamelCase	:     int       =       max_position_embeddings
							_lowerCamelCase	:     str       =       d_model
							_lowerCamelCase	:     Optional[int]       =       encoder_ffn_dim
							_lowerCamelCase	:     int       =       encoder_layers
							_lowerCamelCase	:     Optional[Any]       =       encoder_attention_heads
							_lowerCamelCase	:     List[Any]       =       decoder_ffn_dim
							_lowerCamelCase	:     int       =       decoder_layers
							_lowerCamelCase	:     List[str]       =       decoder_attention_heads
							_lowerCamelCase	:     List[Any]       =       dropout
							_lowerCamelCase	:     List[Any]       =       attention_dropout
							_lowerCamelCase	:     str       =       activation_dropout
							_lowerCamelCase	:     Any       =       activation_function
							_lowerCamelCase	:     Dict       =       init_std
							_lowerCamelCase	:     str       =       encoder_layerdrop
							_lowerCamelCase	:     Any       =       decoder_layerdrop
							_lowerCamelCase	:     Union[str, Any]       =       use_cache
							_lowerCamelCase	:     List[Any]       =       encoder_layers
							_lowerCamelCase	:     Tuple       =       scale_embedding  # scale factor will be sqrt(d_model) if True

							super().__init__(
							    pad_token_id=__UpperCamelCase    , bos_token_id=__UpperCamelCase    , eos_token_id=__UpperCamelCase    , is_encoder_decoder=__UpperCamelCase    , decoder_start_token_id=__UpperCamelCase    , forced_eos_token_id=__UpperCamelCase    , **__UpperCamelCase    , )






class lowerCAmelCase__      (	_a		):






			'''simple docstring'''



			@property
			def    A_       (    self    ):
							if self.task in ["default", "seq2seq-lm"]:
											_lowerCamelCase	:     Tuple       =       OrderedDict(
											    [
											        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
											        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
											    ]    )

											if self.use_past:
															_lowerCamelCase	:     List[Any]       =       {0: 'batch'}
															_lowerCamelCase	:     List[Any]       =       {0: 'batch', 1: 'past_decoder_sequence + sequence'}
											else:
															_lowerCamelCase	:     List[str]       =       {0: 'batch', 1: 'decoder_sequence'}
															_lowerCamelCase	:     Tuple       =       {0: 'batch', 1: 'decoder_sequence'}

											if self.use_past:
															self.fill_with_past_key_values_(__UpperCamelCase    , direction='inputs'    )
							elif self.task == "causal-lm":
											# TODO: figure this case out.
											_lowerCamelCase	:     Any       =       OrderedDict(
											    [
											        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
											        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
											    ]    )
											if self.use_past:
															_lowerCamelCase,					_lowerCamelCase	:     Any       =       self.num_layers
															for i in range(__UpperCamelCase    ):
																			_lowerCamelCase	:     Optional[int]       =       {0: 'batch', 2: 'past_sequence + sequence'}
																			_lowerCamelCase	:     List[str]       =       {0: 'batch', 2: 'past_sequence + sequence'}
							else:
											_lowerCamelCase	:     Any       =       OrderedDict(
											    [
											        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
											        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
											        ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}),
											        ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}),
											    ]    )

							return common_inputs
			@property
			def    A_       (    self    ):
							if self.task in ["default", "seq2seq-lm"]:
											_lowerCamelCase	:     Optional[Any]       =       super().outputs
							else:
											_lowerCamelCase	:     Union[str, Any]       =       super(__UpperCamelCase    , self    ).outputs
											if self.use_past:
															_lowerCamelCase,					_lowerCamelCase	:     int       =       self.num_layers
															for i in range(__UpperCamelCase    ):
																			_lowerCamelCase	:     Optional[Any]       =       {0: 'batch', 2: 'past_sequence + sequence'}
																			_lowerCamelCase	:     List[str]       =       {0: 'batch', 2: 'past_sequence + sequence'}
							return common_outputs
			def    A_       (    self    , lowercase    , lowercase = -1    , lowercase = -1    , lowercase = False    , lowercase = None    , ):
							_lowerCamelCase	:     Any       =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    )

							# Generate decoder inputs
							_lowerCamelCase	:     int       =       seq_length if not self.use_past else 1
							_lowerCamelCase	:     List[str]       =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    )
							_lowerCamelCase	:     List[Any]       =       {F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
							_lowerCamelCase	:     Any       =       dict(**__UpperCamelCase    , **__UpperCamelCase    )

							if self.use_past:
											if not is_torch_available():
															raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'    )
											else:
															import torch
											_lowerCamelCase,					_lowerCamelCase	:     str       =       common_inputs['input_ids'].shape
											_lowerCamelCase	:     Tuple       =       common_inputs['decoder_input_ids'].shape[1]
											_lowerCamelCase,					_lowerCamelCase	:     Union[str, Any]       =       self.num_attention_heads
											_lowerCamelCase	:     str       =       (
											    batch,
											    num_encoder_attention_heads,
											    encoder_seq_length,
											    self._config.hidden_size // num_encoder_attention_heads,
											)
											_lowerCamelCase	:     str       =       decoder_seq_length + 3
											_lowerCamelCase	:     int       =       (
											    batch,
											    num_decoder_attention_heads,
											    decoder_past_length,
											    self._config.hidden_size // num_decoder_attention_heads,
											)

											_lowerCamelCase	:     List[Any]       =       torch.cat(
											    [common_inputs['decoder_attention_mask'], torch.ones(__UpperCamelCase    , __UpperCamelCase    )]    , dim=1    )

											_lowerCamelCase	:     List[str]       =       []
											# If the number of encoder and decoder layers are present in the model configuration, both are considered
											_lowerCamelCase,					_lowerCamelCase	:     List[str]       =       self.num_layers
											_lowerCamelCase	:     Union[str, Any]       =       min(__UpperCamelCase    , __UpperCamelCase    )
											_lowerCamelCase	:     Tuple       =       max(__UpperCamelCase    , __UpperCamelCase    ) - min_num_layers
											_lowerCamelCase	:     List[Any]       =       'encoder' if num_encoder_layers > num_decoder_layers else 'decoder'

											for _ in range(__UpperCamelCase    ):
															common_inputs["past_key_values"].append(
															    (
															        torch.zeros(__UpperCamelCase    ),
															        torch.zeros(__UpperCamelCase    ),
															        torch.zeros(__UpperCamelCase    ),
															        torch.zeros(__UpperCamelCase    ),
															    )    )
											# TODO: test this.
											_lowerCamelCase	:     Any       =       encoder_shape if remaining_side_name == 'encoder' else decoder_shape
											for _ in range(__UpperCamelCase    , __UpperCamelCase    ):
															common_inputs["past_key_values"].append((torch.zeros(__UpperCamelCase    ), torch.zeros(__UpperCamelCase    ))    )
							return common_inputs
			def    A_       (    self    , lowercase    , lowercase = -1    , lowercase = -1    , lowercase = False    , lowercase = None    , ):
							_lowerCamelCase	:     Optional[Any]       =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
							    __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    )

							if self.use_past:
											if not is_torch_available():
															raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'    )
											else:
															import torch
											_lowerCamelCase,					_lowerCamelCase	:     str       =       common_inputs['input_ids'].shape
											# Not using the same length for past_key_values
											_lowerCamelCase	:     Dict       =       seqlen + 2
											_lowerCamelCase,					_lowerCamelCase	:     Optional[int]       =       self.num_layers
											_lowerCamelCase,					_lowerCamelCase	:     int       =       self.num_attention_heads
											_lowerCamelCase	:     int       =       (
											    batch,
											    num_encoder_attention_heads,
											    past_key_values_length,
											    self._config.hidden_size // num_encoder_attention_heads,
											)

											_lowerCamelCase	:     int       =       common_inputs['attention_mask'].dtype
											_lowerCamelCase	:     List[str]       =       torch.cat(
											    [common_inputs['attention_mask'], torch.ones(__UpperCamelCase    , __UpperCamelCase    , dtype=__UpperCamelCase    )]    , dim=1    )
											_lowerCamelCase	:     List[str]       =       [
											    (torch.zeros(__UpperCamelCase    ), torch.zeros(__UpperCamelCase    )) for _ in range(__UpperCamelCase    )
											]
							return common_inputs
			def    A_       (    self    , lowercase    , lowercase = -1    , lowercase = -1    , lowercase = False    , lowercase = None    , ):
							# Copied from OnnxConfig.generate_dummy_inputs
							# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
							# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
							_lowerCamelCase	:     int       =       compute_effective_axis_dimension(
							    __UpperCamelCase    , fixed_dimension=OnnxConfig.default_fixed_batch    , num_token_to_add=0    )

							# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
							_lowerCamelCase	:     List[str]       =       tokenizer.num_special_tokens_to_add(__UpperCamelCase    )
							_lowerCamelCase	:     List[str]       =       compute_effective_axis_dimension(
							    __UpperCamelCase    , fixed_dimension=OnnxConfig.default_fixed_sequence    , num_token_to_add=__UpperCamelCase    )

							# Generate dummy inputs according to compute batch and sequence
							_lowerCamelCase	:     Optional[Any]       =       [' '.join([tokenizer.unk_token]    ) * seq_length] * batch_size
							_lowerCamelCase	:     int       =       dict(tokenizer(__UpperCamelCase    , return_tensors=__UpperCamelCase    )    )
							return common_inputs
			def    A_       (    self    , lowercase    , lowercase = -1    , lowercase = -1    , lowercase = False    , lowercase = None    , ):
							if self.task in ["default", "seq2seq-lm"]:
											_lowerCamelCase	:     Optional[int]       =       self._generate_dummy_inputs_for_default_and_seqaseq_lm(
											    __UpperCamelCase    , batch_size=__UpperCamelCase    , seq_length=__UpperCamelCase    , is_pair=__UpperCamelCase    , framework=__UpperCamelCase    )

							elif self.task == "causal-lm":
											_lowerCamelCase	:     Tuple       =       self._generate_dummy_inputs_for_causal_lm(
											    __UpperCamelCase    , batch_size=__UpperCamelCase    , seq_length=__UpperCamelCase    , is_pair=__UpperCamelCase    , framework=__UpperCamelCase    )
							else:
											_lowerCamelCase	:     str       =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
											    __UpperCamelCase    , batch_size=__UpperCamelCase    , seq_length=__UpperCamelCase    , is_pair=__UpperCamelCase    , framework=__UpperCamelCase    )

							return common_inputs






			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    ):
							if self.task in ["default", "seq2seq-lm"]:
											_lowerCamelCase	:     str       =       super()._flatten_past_key_values_(__UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    )
							else:
											_lowerCamelCase	:     Optional[Any]       =       super(__UpperCamelCase    , self    )._flatten_past_key_values_(
											    __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    )

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

import numpy as np
import PIL
from PIL import Image

from ...utils import (
    BaseOutput,
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_onnx_available,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)



@dataclass
class    a_ (			_a    ):
			a	:			Union[List[PIL.Image.Image], np.ndarray]
			a	:			Optional[List[bool]]


try:
		if not (is_transformers_available() and is_torch_available()):
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		from ...utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
		from .pipeline_cycle_diffusion import CycleDiffusionPipeline
		from .pipeline_stable_diffusion import StableDiffusionPipeline
		from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline
		from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline
		from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline
		from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy
		from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline
		from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline
		from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline
		from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline
		from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline
		from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline
		from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline
		from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
		from .pipeline_stable_unclip import StableUnCLIPPipeline
		from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline
		from .safety_checker import StableDiffusionSafetyChecker
		from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer

try:
		if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline
else:
		from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline


try:
		if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.26.0''')):
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		from ...utils.dummy_torch_and_transformers_objects import (
		    StableDiffusionDepthaImgPipeline,
		    StableDiffusionDiffEditPipeline,
		    StableDiffusionPixaPixZeroPipeline,
		)
else:
		from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline
		from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline
		from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline


try:
		if not (
		    is_torch_available()
		    and is_transformers_available()
		    and is_k_diffusion_available()
		    and is_k_diffusion_version('''>=''', '''0.0.12''')
		):
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
		from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline

try:
		if not (is_transformers_available() and is_onnx_available()):
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		from ...utils.dummy_onnx_objects import *  # noqa F403
else:
		from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline
		from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline
		from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline
		from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy
		from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline

if is_transformers_available() and is_flax_available():
		import flax



		@flax.struct.dataclass
		class    a_ (			_a    ):
					a	:			np.ndarray
					a	:			List[bool]







		from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState
		from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline
		from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline
		from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline
		from .safety_checker_flax import FlaxStableDiffusionSafetyChecker