
'''simple docstring'''


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

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


__SCREAMING_SNAKE_CASE						=      logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE						=      {
    "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/config.json",
    # See all M2M100 models at https://huggingface.co/models?filter=m2m_100
}




class     __snake_case			(    _a	):
		a_          =					"m2m_100"
		a_          =					["past_key_values"]
		a_          =					{"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}




		def __init__(  self					:Any			,    _SCREAMING_SNAKE_CASE					:Union[str, Any]=1_2_8_1_1_2			,    _SCREAMING_SNAKE_CASE					:Optional[int]=1_0_2_4			,    _SCREAMING_SNAKE_CASE					:Any=1_2			,    _SCREAMING_SNAKE_CASE					:Tuple=4_0_9_6			,    _SCREAMING_SNAKE_CASE					:Dict=1_6			,    _SCREAMING_SNAKE_CASE					:List[Any]=1_2			,    _SCREAMING_SNAKE_CASE					:Tuple=4_0_9_6			,    _SCREAMING_SNAKE_CASE					:Optional[int]=1_6			,    _SCREAMING_SNAKE_CASE					:int=0.05			,    _SCREAMING_SNAKE_CASE					:List[str]=0.05			,    _SCREAMING_SNAKE_CASE					:List[str]=True			,    _SCREAMING_SNAKE_CASE					:Union[str, Any]=True			,    _SCREAMING_SNAKE_CASE					:Union[str, Any]="relu"			,    _SCREAMING_SNAKE_CASE					:Any=1_0_2_4			,    _SCREAMING_SNAKE_CASE					:Optional[int]=0.1			,    _SCREAMING_SNAKE_CASE					:Union[str, Any]=0.1			,    _SCREAMING_SNAKE_CASE					:Optional[int]=0.0			,    _SCREAMING_SNAKE_CASE					:Tuple=0.02			,    _SCREAMING_SNAKE_CASE					:Optional[Any]=2			,    _SCREAMING_SNAKE_CASE					:str=True			,    _SCREAMING_SNAKE_CASE					:Optional[Any]=1			,    _SCREAMING_SNAKE_CASE					:str=0			,    _SCREAMING_SNAKE_CASE					:Any=2			,    **_SCREAMING_SNAKE_CASE					:Optional[int]			,    )					->			Any:






								'''simple docstring'''






								UpperCamelCase_     :	Any					     =     vocab_size
								UpperCamelCase_     :	Tuple					     =     max_position_embeddings
								UpperCamelCase_     :	Dict					     =     d_model
								UpperCamelCase_     :	List[str]					     =     encoder_ffn_dim
								UpperCamelCase_     :	Dict					     =     encoder_layers
								UpperCamelCase_     :	Any					     =     encoder_attention_heads
								UpperCamelCase_     :	Optional[Any]					     =     decoder_ffn_dim
								UpperCamelCase_     :	List[Any]					     =     decoder_layers
								UpperCamelCase_     :	str					     =     decoder_attention_heads
								UpperCamelCase_     :	List[str]					     =     dropout
								UpperCamelCase_     :	List[str]					     =     attention_dropout
								UpperCamelCase_     :	List[str]					     =     activation_dropout
								UpperCamelCase_     :	List[str]					     =     activation_function
								UpperCamelCase_     :	int					     =     init_std
								UpperCamelCase_     :	Any					     =     encoder_layerdrop
								UpperCamelCase_     :	List[str]					     =     decoder_layerdrop
								UpperCamelCase_     :	Optional[int]					     =     use_cache
								UpperCamelCase_     :	List[str]					     =     encoder_layers
								UpperCamelCase_     :	Dict					     =     scale_embedding  # scale factor will be sqrt(d_model) if True

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







class     __snake_case			(    _a	):




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






								'''simple docstring'''






								UpperCamelCase_     :	Tuple					     =     OrderedDict(
								    [
								        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
								        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
								    ])

								if self.use_past:
														UpperCamelCase_     :	List[Any]					     =     {0: """batch"""}
														UpperCamelCase_     :	Union[str, Any]					     =     {0: """batch""", 1: """past_decoder_sequence + sequence"""}
								else:
														UpperCamelCase_     :	List[Any]					     =     {0: """batch""", 1: """decoder_sequence"""}
														UpperCamelCase_     :	Union[str, Any]					     =     {0: """batch""", 1: """decoder_sequence"""}

								if self.use_past:
														self.fill_with_past_key_values_(_A			,    direction="""inputs""")
								return common_inputs




		def 	_snake_case	(  self					:List[str]			,    _SCREAMING_SNAKE_CASE					:Dict			,    _SCREAMING_SNAKE_CASE					:Any = -1			,    _SCREAMING_SNAKE_CASE					:List[str] = -1			,    _SCREAMING_SNAKE_CASE					:Union[str, Any] = False			,    _SCREAMING_SNAKE_CASE					:Optional[Any] = None			,    )					->			List[str]:






								'''simple docstring'''






								UpperCamelCase_     :	Optional[Any]					     =     compute_effective_axis_dimension(
								    _A			,    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
								UpperCamelCase_     :	Any					     =     tokenizer.num_special_tokens_to_add(_A)
								UpperCamelCase_     :	List[str]					     =     compute_effective_axis_dimension(
								    _A			,    fixed_dimension=OnnxConfig.default_fixed_sequence			,    num_token_to_add=_A)

								# Generate dummy inputs according to compute batch and sequence
								UpperCamelCase_     :	Optional[Any]					     =     [""" """.join([tokenizer.unk_token]) * seq_length] * batch_size
								UpperCamelCase_     :	Union[str, Any]					     =     dict(tokenizer(_A			,    return_tensors=_A))
								return common_inputs




		def 	_snake_case	(  self					:Optional[int]			,    _SCREAMING_SNAKE_CASE					:Any			,    _SCREAMING_SNAKE_CASE					:Any = -1			,    _SCREAMING_SNAKE_CASE					:List[Any] = -1			,    _SCREAMING_SNAKE_CASE					:Optional[int] = False			,    _SCREAMING_SNAKE_CASE					:Any = None			,    )					->			Any:






								'''simple docstring'''






								UpperCamelCase_     :	str					     =     self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
								    _A			,    _A			,    _A			,    _A			,    _A)

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

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

														UpperCamelCase_     :	Any					     =     torch.cat(
														    [common_inputs["""decoder_attention_mask"""], torch.ones(_A			,    _A)]			,    dim=1)

														UpperCamelCase_     :	List[str]					     =     []
														# If the number of encoder and decoder layers are present in the model configuration, both are considered
														UpperCamelCase_     ,UpperCamelCase_     :	Dict					     =     self.num_layers
														UpperCamelCase_     :	List[Any]					     =     min(_A			,    _A)
														UpperCamelCase_     :	Dict					     =     max(_A			,    _A) - min_num_layers
														UpperCamelCase_     :	int					     =     """encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

														for _ in range(_A):
																				common_inputs["past_key_values"].append(
																				    (
																				        torch.zeros(_A),
																				        torch.zeros(_A),
																				        torch.zeros(_A),
																				        torch.zeros(_A),
																				    ))
														# TODO: test this.
														UpperCamelCase_     :	List[str]					     =     encoder_shape if remaining_side_name == """encoder""" else decoder_shape
														for _ in range(_A			,    _A):
																				common_inputs["past_key_values"].append((torch.zeros(_A), torch.zeros(_A)))
								return common_inputs





		a_          =					_generate_dummy_inputs_for_default_and_seqaseq_lm







import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
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 PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()





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


							"""simple docstring"""





							__UpperCAmelCase      =StableDiffusionParadigmsPipeline
							__UpperCAmelCase      =TEXT_TO_IMAGE_PARAMS
							__UpperCAmelCase      =TEXT_TO_IMAGE_BATCH_PARAMS
							__UpperCAmelCase      =TEXT_TO_IMAGE_IMAGE_PARAMS
							__UpperCAmelCase      =TEXT_TO_IMAGE_IMAGE_PARAMS




							def 							A__	(			self				):
												torch.manual_seed(0				)
												__lowerCAmelCase       =				UNetaDConditionModel(
												    block_out_channels=(3_2, 6_4)       ,    layers_per_block=2       ,    sample_size=3_2       ,    in_channels=4       ,    out_channels=4       ,    down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')       ,    up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')       ,    cross_attention_dim=3_2       ,    attention_head_dim=(2, 4)       ,    use_linear_projection=_A       ,    )
												__lowerCAmelCase       =				DDIMParallelScheduler(
												    beta_start=0.0_0085       ,    beta_end=0.012       ,    beta_schedule='scaled_linear'       ,    clip_sample=_A       ,    set_alpha_to_one=_A       ,    )
												torch.manual_seed(0				)
												__lowerCAmelCase       =				AutoencoderKL(
												    block_out_channels=[3_2, 6_4]       ,    in_channels=3       ,    out_channels=3       ,    down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']       ,    up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']       ,    latent_channels=4       ,    sample_size=1_2_8       ,    )
												torch.manual_seed(0				)
												__lowerCAmelCase       =				CLIPTextConfig(
												    bos_token_id=0       ,    eos_token_id=2       ,    hidden_size=3_2       ,    intermediate_size=3_7       ,    layer_norm_eps=1e-0_5       ,    num_attention_heads=4       ,    num_hidden_layers=5       ,    pad_token_id=1       ,    vocab_size=1_0_0_0       ,    hidden_act='gelu'       ,    projection_dim=5_1_2       ,    )
												__lowerCAmelCase       =				CLIPTextModel(_A				)
												__lowerCAmelCase       =				CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'				)

												__lowerCAmelCase       =				{
												    'unet': unet,
												    'scheduler': scheduler,
												    'vae': vae,
												    'text_encoder': text_encoder,
												    'tokenizer': tokenizer,
												    'safety_checker': None,
												    'feature_extractor': None,
												}
												return components




							def 							A__	(			self       ,    _A       ,    _A=0				):
												if str(_A				).startswith('mps'				):
																	__lowerCAmelCase       =				torch.manual_seed(_A				)
												else:
																	__lowerCAmelCase       =				torch.Generator(device=_A				).manual_seed(_A				)
												__lowerCAmelCase       =				{
												    'prompt': 'a photograph of an astronaut riding a horse',
												    'generator': generator,
												    'num_inference_steps': 1_0,
												    'guidance_scale': 6.0,
												    'output_type': 'numpy',
												    'parallel': 3,
												    'debug': True,
												}
												return inputs




							def 							A__	(			self				):
												__lowerCAmelCase       =				'cpu'  # ensure determinism for the device-dependent torch.Generator
												__lowerCAmelCase       =				self.get_dummy_components()
												__lowerCAmelCase       =				StableDiffusionParadigmsPipeline(**_A				)
												__lowerCAmelCase       =				sd_pipe.to(_A				)
												sd_pipe.set_progress_bar_config(disable=_A				)

												__lowerCAmelCase       =				self.get_dummy_inputs(_A				)
												__lowerCAmelCase       =				sd_pipe(**_A				).images
												__lowerCAmelCase       =				image[0, -3:, -3:, -1]
												assert image.shape == (1, 6_4, 6_4, 3)

												__lowerCAmelCase       =				np.array([0.4773, 0.5417, 0.4723, 0.4925, 0.5631, 0.4752, 0.5240, 0.4935, 0.5023]				)

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




							def 							A__	(			self				):
												__lowerCAmelCase       =				'cpu'  # ensure determinism for the device-dependent torch.Generator
												__lowerCAmelCase       =				self.get_dummy_components()
												torch.manual_seed(0				)
												__lowerCAmelCase       =				DDPMParallelScheduler()
												torch.manual_seed(0				)
												__lowerCAmelCase       =				StableDiffusionParadigmsPipeline(**_A				)
												__lowerCAmelCase       =				sd_pipe.to(_A				)
												sd_pipe.set_progress_bar_config(disable=_A				)

												__lowerCAmelCase       =				self.get_dummy_inputs(_A				)
												__lowerCAmelCase       =				sd_pipe(**_A				).images
												__lowerCAmelCase       =				image[0, -3:, -3:, -1]
												assert image.shape == (1, 6_4, 6_4, 3)

												__lowerCAmelCase       =				np.array([0.3573, 0.4420, 0.4960, 0.4799, 0.3796, 0.3879, 0.4819, 0.4365, 0.4468]				)

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




							def 							A__	(			self				):
												super().test_inference_batch_consistent(batch_sizes=[1, 2]				)




							def 							A__	(			self				):
												super().test_inference_batch_single_identical(batch_size=2       ,    expected_max_diff=3e-3				)




							def 							A__	(			self				):
												__lowerCAmelCase       =				'cpu'  # ensure determinism for the device-dependent torch.Generator
												__lowerCAmelCase       =				self.get_dummy_components()
												__lowerCAmelCase       =				StableDiffusionParadigmsPipeline(**_A				)
												__lowerCAmelCase       =				sd_pipe.to(_A				)
												sd_pipe.set_progress_bar_config(disable=_A				)

												__lowerCAmelCase       =				self.get_dummy_inputs(_A				)
												__lowerCAmelCase       =				'french fries'
												__lowerCAmelCase       =				sd_pipe(**_A       ,    negative_prompt=_A				)
												__lowerCAmelCase       =				output.images
												__lowerCAmelCase       =				image[0, -3:, -3:, -1]

												assert image.shape == (1, 6_4, 6_4, 3)

												__lowerCAmelCase       =				np.array([0.4771, 0.5420, 0.4683, 0.4918, 0.5636, 0.4725, 0.5230, 0.4923, 0.5015]				)

												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				):
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()




							def 							A__	(			self       ,    _A=0				):
												__lowerCAmelCase       =				torch.Generator(device=_A				).manual_seed(_A				)
												__lowerCAmelCase       =				{
												    'prompt': 'a photograph of an astronaut riding a horse',
												    'generator': generator,
												    'num_inference_steps': 1_0,
												    'guidance_scale': 7.5,
												    'output_type': 'numpy',
												    'parallel': 3,
												    'debug': True,
												}
												return inputs




							def 							A__	(			self				):
												__lowerCAmelCase       =				'stabilityai/stable-diffusion-2-base'
												__lowerCAmelCase       =				DDIMParallelScheduler.from_pretrained(_A       ,    subfolder='scheduler'				)
												__lowerCAmelCase       =				StableDiffusionParadigmsPipeline.from_pretrained(_A       ,    scheduler=_A       ,    safety_checker=_A				)
												pipe.to(_A				)
												pipe.set_progress_bar_config(disable=_A				)
												pipe.enable_attention_slicing()

												__lowerCAmelCase       =				self.get_inputs()
												__lowerCAmelCase       =				pipe(**_A				).images
												__lowerCAmelCase       =				image[0, -3:, -3:, -1].flatten()

												assert image.shape == (1, 5_1_2, 5_1_2, 3)

												__lowerCAmelCase       =				np.array([0.9622, 0.9602, 0.9748, 0.9591, 0.9630, 0.9691, 0.9661, 0.9631, 0.9741]				)

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






