



'''simple docstring'''



import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
		from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder



def   _A       (   _lowerCAmelCase  ,   _lowerCAmelCase  ,   _lowerCAmelCase  ,   _lowerCAmelCase=None  ,   _lowerCAmelCase=None  ,   _lowerCAmelCase=None  ,   _lowerCAmelCase=None  ,   _lowerCAmelCase=None  ,   ):



							"""simple docstring"""



							if attention_mask is None:
														__lowercase       	=input_ids.ne(config.pad_token_id					)
							if decoder_attention_mask is None:
														__lowercase       	=decoder_input_ids.ne(config.pad_token_id					)
							if head_mask is None:
														__lowercase       	=torch.ones(config.encoder_layers  ,   config.encoder_attention_heads  ,   device=_lowerCAmelCase					)
							if decoder_head_mask is None:
														__lowercase       	=torch.ones(config.decoder_layers  ,   config.decoder_attention_heads  ,   device=_lowerCAmelCase					)
							if cross_attn_head_mask is None:
														__lowercase       	=torch.ones(config.decoder_layers  ,   config.decoder_attention_heads  ,   device=_lowerCAmelCase					)
							return {
							    "input_ids": input_ids,
							    "decoder_input_ids": decoder_input_ids,
							    "attention_mask": attention_mask,
							    "decoder_attention_mask": attention_mask,
							    "head_mask": head_mask,
							    "decoder_head_mask": decoder_head_mask,
							    "cross_attn_head_mask": cross_attn_head_mask,
							}





class __SCREAMING_SNAKE_CASE		:





				'''simple docstring'''





				def __init__(							self  :  List[Any]  ,       _lowerCAmelCase  :  Dict  ,       _lowerCAmelCase  :  int=1_3  ,       _lowerCAmelCase  :  Union[str, Any]=7  ,       _lowerCAmelCase  :  Optional[int]=True  ,       _lowerCAmelCase  :  Any=False  ,       _lowerCAmelCase  :  List[str]=9_9  ,       _lowerCAmelCase  :  List[str]=1_6  ,       _lowerCAmelCase  :  Any=2  ,       _lowerCAmelCase  :  Dict=4  ,       _lowerCAmelCase  :  int=4  ,       _lowerCAmelCase  :  Dict="relu"  ,       _lowerCAmelCase  :  List[Any]=0.1  ,       _lowerCAmelCase  :  str=0.1  ,       _lowerCAmelCase  :  Tuple=0.0  ,       _lowerCAmelCase  :  Any=0.0  ,       _lowerCAmelCase  :  str=2_0  ,       _lowerCAmelCase  :  List[str]=2  ,       _lowerCAmelCase  :  str=1  ,       _lowerCAmelCase  :  Tuple=0  ,       ):







											'''simple docstring'''

											__lowercase       	=parent
											__lowercase       	=batch_size
											__lowercase       	=seq_length
											__lowercase       	=is_training
											__lowercase       	=use_labels
											__lowercase       	=vocab_size
											__lowercase       	=hidden_size
											__lowercase       	=num_hidden_layers
											__lowercase       	=num_attention_heads
											__lowercase       	=intermediate_size
											__lowercase       	=hidden_act
											__lowercase       	=hidden_dropout_prob
											__lowercase       	=attention_probs_dropout_prob
											__lowercase       	=encoder_layerdrop
											__lowercase       	=decoder_layerdrop
											__lowercase       	=max_position_embeddings
											__lowercase       	=eos_token_id
											__lowercase       	=pad_token_id
											__lowercase       	=bos_token_id

				def 				__lowerCamelCase     (							self  :  Optional[Any]):







											'''simple docstring'''

											__lowercase       	=ids_tensor([self.batch_size, self.seq_length]  ,       self.vocab_size)
											__lowercase       	=self.eos_token_id  # Eos Token
											__lowercase       	=ids_tensor([self.batch_size, self.seq_length]  ,       self.vocab_size)

											# we need to clamp the input ids here to avoid having pad token in between
											# this is because for M2M100 the position_ids are prepared such that
											# all pad tokens have pos id = 2 and rest are between 2..seq_length
											# and the seq_length here is seq_length - num_pad_tokens
											# but when using past, there is no way of knowing if the past input ids had
											# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
											# position_ids being off by num_pad_tokens in past input
											__lowercase       	=input_ids.clamp(self.pad_token_id + 1)
											__lowercase       	=decoder_input_ids.clamp(self.pad_token_id + 1)

											__lowercase       	=self.get_config()
											__lowercase       	=prepare_mam_aaa_inputs_dict(_lowerCAmelCase  ,       _lowerCAmelCase  ,       _lowerCAmelCase)
											return config, inputs_dict

				def 				__lowerCamelCase     (							self  :  Dict):







											'''simple docstring'''

											return MaMaaaConfig(
											    vocab_size=self.vocab_size  ,       d_model=self.hidden_size  ,       encoder_layers=self.num_hidden_layers  ,       decoder_layers=self.num_hidden_layers  ,       encoder_attention_heads=self.num_attention_heads  ,       decoder_attention_heads=self.num_attention_heads  ,       encoder_ffn_dim=self.intermediate_size  ,       decoder_ffn_dim=self.intermediate_size  ,       dropout=self.hidden_dropout_prob  ,       attention_dropout=self.attention_probs_dropout_prob  ,       encoder_layerdrop=self.encoder_layerdrop  ,       decoder_layerdrop=self.decoder_layerdrop  ,       max_position_embeddings=self.max_position_embeddings  ,       eos_token_id=self.eos_token_id  ,       bos_token_id=self.bos_token_id  ,       pad_token_id=self.pad_token_id  ,       )

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







											'''simple docstring'''

											__lowercase	,				__lowercase       	=self.prepare_config_and_inputs()
											return config, inputs_dict

				def 				__lowerCamelCase     (							self  :  Dict  ,       _lowerCAmelCase  :  Tuple  ,       _lowerCAmelCase  :  List[Any]):







											'''simple docstring'''

											__lowercase       	=MaMaaaModel(config=_lowerCAmelCase).get_decoder().to(_lowerCAmelCase).eval()
											__lowercase       	=inputs_dict['input_ids']
											__lowercase       	=inputs_dict['attention_mask']
											__lowercase       	=inputs_dict['head_mask']

											# first forward pass
											__lowercase       	=model(_lowerCAmelCase  ,       attention_mask=_lowerCAmelCase  ,       head_mask=_lowerCAmelCase  ,       use_cache=_lowerCAmelCase)

											__lowercase	,				__lowercase       	=outputs.to_tuple()

											# create hypothetical multiple next token and extent to next_input_ids
											__lowercase       	=ids_tensor((self.batch_size, 3)  ,       config.vocab_size)
											__lowercase       	=ids_tensor((self.batch_size, 3)  ,       2)

											# append to next input_ids and
											__lowercase       	=torch.cat([input_ids, next_tokens]  ,       dim=-1)
											__lowercase       	=torch.cat([attention_mask, next_attn_mask]  ,       dim=-1)

											__lowercase       	=model(_lowerCAmelCase  ,       attention_mask=_lowerCAmelCase)['last_hidden_state']
											__lowercase       	=model(_lowerCAmelCase  ,       attention_mask=_lowerCAmelCase  ,       past_key_values=_lowerCAmelCase)[
											    'last_hidden_state'
											]

											# select random slice
											__lowercase       	=ids_tensor((1,)  ,       output_from_past.shape[-1]).item()
											__lowercase       	=output_from_no_past[:, -3:, random_slice_idx].detach()
											__lowercase       	=output_from_past[:, :, random_slice_idx].detach()

											self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])

											# test that outputs are equal for slice
											self.parent.assertTrue(torch.allclose(_lowerCAmelCase  ,       _lowerCAmelCase  ,       atol=1e-2))

				def 				__lowerCamelCase     (							self  :  Any  ,       _lowerCAmelCase  :  List[Any]  ,       _lowerCAmelCase  :  str):







											'''simple docstring'''

											__lowercase       	=MaMaaaModel(config=_lowerCAmelCase).to(_lowerCAmelCase).eval()
											__lowercase       	=model(**_lowerCAmelCase)

											__lowercase       	=outputs.encoder_last_hidden_state
											__lowercase       	=outputs.last_hidden_state

											with tempfile.TemporaryDirectory() as tmpdirname:
																		__lowercase       	=model.get_encoder()
																		encoder.save_pretrained(_lowerCAmelCase)
																		__lowercase       	=MaMaaaEncoder.from_pretrained(_lowerCAmelCase).to(_lowerCAmelCase)

											__lowercase       	=encoder(inputs_dict['input_ids']  ,       attention_mask=inputs_dict['attention_mask'])[
											    0
											]

											self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3)

											with tempfile.TemporaryDirectory() as tmpdirname:
																		__lowercase       	=model.get_decoder()
																		decoder.save_pretrained(_lowerCAmelCase)
																		__lowercase       	=MaMaaaDecoder.from_pretrained(_lowerCAmelCase).to(_lowerCAmelCase)

											__lowercase       	=decoder(
											    input_ids=inputs_dict['decoder_input_ids']  ,       attention_mask=inputs_dict['decoder_attention_mask']  ,       encoder_hidden_states=_lowerCAmelCase  ,       encoder_attention_mask=inputs_dict['attention_mask']  ,       )[0]

											self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3)





@require_torch
class __SCREAMING_SNAKE_CASE		(     A      ,       A      ,       A      ,       unittest.TestCase		):





				'''simple docstring'''





				lowerCAmelCase__					    =    (
				    (
				        MaMaaaModel,
				        MaMaaaForConditionalGeneration,
				    )
				    if is_torch_available()
				    else ()
				)
				lowerCAmelCase__					    =    (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
				lowerCAmelCase__					    =    (
				    {
				        """conversational""": MaMaaaForConditionalGeneration,
				        """feature-extraction""": MaMaaaModel,
				        """summarization""": MaMaaaForConditionalGeneration,
				        """text2text-generation""": MaMaaaForConditionalGeneration,
				        """translation""": MaMaaaForConditionalGeneration,
				    }
				    if is_torch_available()
				    else {}
				)
				lowerCAmelCase__					    =    True
				lowerCAmelCase__					    =    True
				lowerCAmelCase__					    =    False
				lowerCAmelCase__					    =    False

				def 				__lowerCamelCase     (							self  :  Union[str, Any]  ,       _lowerCAmelCase  :  Optional[Any]  ,       _lowerCAmelCase  :  Tuple  ,       _lowerCAmelCase  :  Any  ,       _lowerCAmelCase  :  Optional[int]  ,       _lowerCAmelCase  :  List[Any]):







											'''simple docstring'''

											if pipeline_test_casse_name == "TranslationPipelineTests":
																		# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
																		# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
																		return True

											return False

				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											__lowercase       	=MaMaaaModelTester(self)
											__lowercase       	=ConfigTester(self  ,       config_class=_lowerCAmelCase)

				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											self.config_tester.run_common_tests()

				def 				__lowerCamelCase     (							self  :  Tuple):







											'''simple docstring'''

											__lowercase	,				__lowercase       	=self.model_tester.prepare_config_and_inputs()
											for model_class in self.all_model_classes:
																		__lowercase       	=model_class(_lowerCAmelCase)

																		with tempfile.TemporaryDirectory() as tmpdirname:
																									model.save_pretrained(_lowerCAmelCase)
																									__lowercase	,				__lowercase       	=model_class.from_pretrained(_lowerCAmelCase  ,       output_loading_info=_lowerCAmelCase)
																		self.assertEqual(info['missing_keys']  ,       [])

				def 				__lowerCamelCase     (							self  :  Tuple):







											'''simple docstring'''

											__lowercase       	=self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_decoder_model_past_large_inputs(*_lowerCAmelCase)

				def 				__lowerCamelCase     (							self  :  List[str]):







											'''simple docstring'''

											__lowercase       	=self.model_tester.prepare_config_and_inputs_for_common()
											self.model_tester.check_encoder_decoder_model_standalone(*_lowerCAmelCase)

				def 				__lowerCamelCase     (							self  :  Tuple):







											'''simple docstring'''

											__lowercase	,				__lowercase       	=self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
																		__lowercase       	=model_class(_lowerCAmelCase)
																		model.to(_lowerCAmelCase)
																		model.eval()

																		__lowercase       	=copy.deepcopy(self._prepare_for_class(_lowerCAmelCase  ,       _lowerCAmelCase))

																		if not self.is_encoder_decoder:
																									__lowercase       	=inputs['input_ids']
																									del inputs["input_ids"]
																		else:
																									__lowercase       	=inputs['input_ids']
																									__lowercase       	=inputs.get('decoder_input_ids'  ,       _lowerCAmelCase)
																									del inputs["input_ids"]
																									inputs.pop('decoder_input_ids'  ,       _lowerCAmelCase)

																		__lowercase       	=model.get_input_embeddings()
																		if not self.is_encoder_decoder:
																									__lowercase       	=wte(_lowerCAmelCase)
																		else:
																									__lowercase       	=wte(_lowerCAmelCase)
																									__lowercase       	=wte(_lowerCAmelCase)

																		with torch.no_grad():
																									model(**_lowerCAmelCase)[0]

				def 				__lowerCamelCase     (							self  :  Optional[Any]):







											'''simple docstring'''

											__lowercase	,				__lowercase       	=self.model_tester.prepare_config_and_inputs()
											__lowercase       	=input_dict['input_ids']
											__lowercase       	=input_ids.ne(1).to(_lowerCAmelCase)
											__lowercase       	=MaMaaaForConditionalGeneration(_lowerCAmelCase).eval().to(_lowerCAmelCase)
											if torch_device == "cuda":
																		model.half()
											model.generate(_lowerCAmelCase  ,       attention_mask=_lowerCAmelCase)
											model.generate(num_beams=4  ,       do_sample=_lowerCAmelCase  ,       early_stopping=_lowerCAmelCase  ,       num_return_sequences=3)



def   _A       (   _lowerCAmelCase					):



							"""simple docstring"""



							return torch.tensor(_lowerCAmelCase  ,   dtype=torch.long  ,   device=_lowerCAmelCase					)


lowerCamelCase	 =       1e-4





@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class __SCREAMING_SNAKE_CASE		(     unittest.TestCase		):





				'''simple docstring'''





				@cached_property
				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M')

				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											__lowercase       	=MaMaaaModel.from_pretrained('facebook/m2m100_418M').to(_lowerCAmelCase)
											__lowercase       	=_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]])
											__lowercase       	=_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]])
											__lowercase       	=prepare_mam_aaa_inputs_dict(model.config  ,       _lowerCAmelCase  ,       _lowerCAmelCase)
											with torch.no_grad():
																		__lowercase       	=model(**_lowerCAmelCase)[0]
											__lowercase       	=torch.Size((1, 1_1, 1_0_2_4))
											self.assertEqual(output.shape  ,       _lowerCAmelCase)
											# change to expected output here
											__lowercase       	=torch.tensor(
											    [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]  ,       device=_lowerCAmelCase)
											self.assertTrue(torch.allclose(output[:, :3, :3]  ,       _lowerCAmelCase  ,       atol=_lowerCAmelCase))

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







											'''simple docstring'''

											__lowercase       	=MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M').to(_lowerCAmelCase)

											# change to intended input
											__lowercase       	=_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]])
											__lowercase       	=_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]])
											__lowercase       	=prepare_mam_aaa_inputs_dict(model.config  ,       _lowerCAmelCase  ,       _lowerCAmelCase)
											with torch.no_grad():
																		__lowercase       	=model(**_lowerCAmelCase)[0]
											__lowercase       	=torch.Size((1, 1_1, model.config.vocab_size))
											self.assertEqual(output.shape  ,       _lowerCAmelCase)
											# change to expected output here
											__lowercase       	=torch.tensor(
											    [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]  ,       device=_lowerCAmelCase)
											self.assertTrue(torch.allclose(output[:, :3, :3]  ,       _lowerCAmelCase  ,       atol=_lowerCAmelCase))

				def 				__lowerCamelCase     (							self  :  List[Any]):







											'''simple docstring'''

											__lowercase       	=MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M').to(_lowerCAmelCase)
											__lowercase       	=MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'  ,       src_lang='fr'  ,       tgt_lang='en')

											__lowercase       	=[
											    'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
											    'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
											    'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'
											    ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'
											    ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.',
											]

											# The below article tests that we don't add any hypotheses outside of the top n_beams
											__lowercase       	=tokenizer(_lowerCAmelCase  ,       padding=_lowerCAmelCase  ,       return_tensors='pt')

											__lowercase       	=model.generate(
											    input_ids=dct['input_ids'].to(_lowerCAmelCase)  ,       attention_mask=dct['attention_mask'].to(_lowerCAmelCase)  ,       num_beams=5  ,       forced_bos_token_id=tokenizer.get_lang_id('en')  ,       )

											__lowercase       	=[
											    'The NSA case highlights the total absence of intelligence debate',
											    'I think there are two levels of response from the French government.',
											    'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'
											    ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'
											    ' communications in France.',
											]

											__lowercase       	=tokenizer.batch_decode(
											    hypotheses_batch.tolist()  ,       clean_up_tokenization_spaces=_lowerCAmelCase  ,       skip_special_tokens=_lowerCAmelCase)
											assert generated == expected_en








'''simple docstring'''



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 _UpperCamelCase		(     A      ,       A      ,       A      ,       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 				__lowerCamelCase     (							self  :  Union[str, Any]):







											'''simple docstring'''

											torch.manual_seed(0)
											__lowercase       	=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  ,       )
											__lowercase       	=DDIMScheduler(
											    beta_start=0.0_0085  ,       beta_end=0.012  ,       beta_schedule='scaled_linear'  ,       clip_sample=_lowerCAmelCase  ,       set_alpha_to_one=_lowerCAmelCase  ,       )
											torch.manual_seed(0)
											__lowercase       	=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  ,       )

											# 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)
											__lowercase       	=CLIPTextConfig(
											    bos_token_id=0  ,       eos_token_id=2  ,       hidden_size=3_2  ,       projection_dim=3_2  ,       intermediate_size=3_7  ,       layer_norm_eps=1e-05  ,       num_attention_heads=4  ,       num_hidden_layers=5  ,       pad_token_id=1  ,       vocab_size=5_0_0_2  ,       )
											__lowercase       	=CLIPTextModel(_lowerCAmelCase)

											__lowercase       	=XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta')
											__lowercase       	=7_7

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

				def 				__lowerCamelCase     (							self  :  List[Any]  ,       _lowerCAmelCase  :  Union[str, Any]  ,       _lowerCAmelCase  :  Dict=0):







											'''simple docstring'''

											if str(_lowerCAmelCase).startswith('mps'):
																		__lowercase       	=torch.manual_seed(_lowerCAmelCase)
											else:
																		__lowercase       	=torch.Generator(device=_lowerCAmelCase).manual_seed(_lowerCAmelCase)
											__lowercase       	={
											    '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 				__lowerCamelCase     (							self  :  List[str]):







											'''simple docstring'''

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

				def 				__lowerCamelCase     (							self  :  Optional[int]):







											'''simple docstring'''

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

				def 				__lowerCamelCase     (							self  :  Optional[Any]):







											'''simple docstring'''

											__lowercase       	='cpu'  # ensure determinism for the device-dependent torch.Generator

											__lowercase       	=self.get_dummy_components()
											torch.manual_seed(0)
											__lowercase       	=RobertaSeriesConfig(
											    hidden_size=3_2  ,       project_dim=3_2  ,       intermediate_size=3_7  ,       layer_norm_eps=1e-05  ,       num_attention_heads=4  ,       num_hidden_layers=5  ,       vocab_size=5_0_0_2  ,       )
											# TODO: remove after fixing the non-deterministic text encoder
											__lowercase       	=RobertaSeriesModelWithTransformation(_lowerCAmelCase)
											__lowercase       	=text_encoder

											__lowercase       	=AltDiffusionPipeline(**_lowerCAmelCase)
											__lowercase       	=alt_pipe.to(_lowerCAmelCase)
											alt_pipe.set_progress_bar_config(disable=_lowerCAmelCase)

											__lowercase       	=self.get_dummy_inputs(_lowerCAmelCase)
											__lowercase       	='A photo of an astronaut'
											__lowercase       	=alt_pipe(**_lowerCAmelCase)
											__lowercase       	=output.images
											__lowercase       	=image[0, -3:, -3:, -1]

											assert image.shape == (1, 6_4, 6_4, 3)
											__lowercase       	=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 				__lowerCamelCase     (							self  :  str):







											'''simple docstring'''

											__lowercase       	='cpu'  # ensure determinism for the device-dependent torch.Generator

											__lowercase       	=self.get_dummy_components()
											__lowercase       	=PNDMScheduler(skip_prk_steps=_lowerCAmelCase)
											torch.manual_seed(0)
											__lowercase       	=RobertaSeriesConfig(
											    hidden_size=3_2  ,       project_dim=3_2  ,       intermediate_size=3_7  ,       layer_norm_eps=1e-05  ,       num_attention_heads=4  ,       num_hidden_layers=5  ,       vocab_size=5_0_0_2  ,       )
											# TODO: remove after fixing the non-deterministic text encoder
											__lowercase       	=RobertaSeriesModelWithTransformation(_lowerCAmelCase)
											__lowercase       	=text_encoder
											__lowercase       	=AltDiffusionPipeline(**_lowerCAmelCase)
											__lowercase       	=alt_pipe.to(_lowerCAmelCase)
											alt_pipe.set_progress_bar_config(disable=_lowerCAmelCase)

											__lowercase       	=self.get_dummy_inputs(_lowerCAmelCase)
											__lowercase       	=alt_pipe(**_lowerCAmelCase)
											__lowercase       	=output.images
											__lowercase       	=image[0, -3:, -3:, -1]

											assert image.shape == (1, 6_4, 6_4, 3)
											__lowercase       	=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 _UpperCamelCase		(     unittest.TestCase		):





				'''simple docstring'''





				def 				__lowerCamelCase     (							self  :  str):







											'''simple docstring'''

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

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







											'''simple docstring'''

											__lowercase       	=AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion'  ,       safety_checker=_lowerCAmelCase)
											__lowercase       	=alt_pipe.to(_lowerCAmelCase)
											alt_pipe.set_progress_bar_config(disable=_lowerCAmelCase)

											__lowercase       	='A painting of a squirrel eating a burger'
											__lowercase       	=torch.manual_seed(0)
											__lowercase       	=alt_pipe([prompt]  ,       generator=_lowerCAmelCase  ,       guidance_scale=6.0  ,       num_inference_steps=2_0  ,       output_type='np')

											__lowercase       	=output.images

											__lowercase       	=image[0, -3:, -3:, -1]

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											__lowercase       	=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 				__lowerCamelCase     (							self  :  Dict):







											'''simple docstring'''

											__lowercase       	=DDIMScheduler.from_pretrained('BAAI/AltDiffusion'  ,       subfolder='scheduler')

											__lowercase       	=AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion'  ,       scheduler=_lowerCAmelCase  ,       safety_checker=_lowerCAmelCase)
											__lowercase       	=alt_pipe.to(_lowerCAmelCase)
											alt_pipe.set_progress_bar_config(disable=_lowerCAmelCase)

											__lowercase       	='A painting of a squirrel eating a burger'
											__lowercase       	=torch.manual_seed(0)

											__lowercase       	=alt_pipe([prompt]  ,       generator=_lowerCAmelCase  ,       num_inference_steps=2  ,       output_type='numpy')
											__lowercase       	=output.images

											__lowercase       	=image[0, -3:, -3:, -1]

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											__lowercase       	=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



