



import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    BertTokenizer,
    ViltConfig,
    ViltForImageAndTextRetrieval,
    ViltForImagesAndTextClassification,
    ViltForMaskedLM,
    ViltForQuestionAnswering,
    ViltImageProcessor,
    ViltProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
__snake_case       :	Tuple            =logging.get_logger(__name__)






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any] ,lowerCamelCase_	:	Dict=False ,lowerCamelCase_	:	Optional[Any]=False ,lowerCamelCase_	:	Tuple=False):





				'''simple docstring'''

				lowerCAmelCase__  :       int				=  []
				for i in range(config.num_hidden_layers):
								# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
								rename_keys.append((f"""transformer.blocks.{i}.norm1.weight""", f"""vilt.encoder.layer.{i}.layernorm_before.weight"""))
								rename_keys.append((f"""transformer.blocks.{i}.norm1.bias""", f"""vilt.encoder.layer.{i}.layernorm_before.bias"""))
								rename_keys.append(
								    (f"""transformer.blocks.{i}.attn.proj.weight""", f"""vilt.encoder.layer.{i}.attention.output.dense.weight"""))
								rename_keys.append(
								    (f"""transformer.blocks.{i}.attn.proj.bias""", f"""vilt.encoder.layer.{i}.attention.output.dense.bias"""))
								rename_keys.append((f"""transformer.blocks.{i}.norm2.weight""", f"""vilt.encoder.layer.{i}.layernorm_after.weight"""))
								rename_keys.append((f"""transformer.blocks.{i}.norm2.bias""", f"""vilt.encoder.layer.{i}.layernorm_after.bias"""))
								rename_keys.append(
								    (f"""transformer.blocks.{i}.mlp.fc1.weight""", f"""vilt.encoder.layer.{i}.intermediate.dense.weight"""))
								rename_keys.append((f"""transformer.blocks.{i}.mlp.fc1.bias""", f"""vilt.encoder.layer.{i}.intermediate.dense.bias"""))
								rename_keys.append((f"""transformer.blocks.{i}.mlp.fc2.weight""", f"""vilt.encoder.layer.{i}.output.dense.weight"""))
								rename_keys.append((f"""transformer.blocks.{i}.mlp.fc2.bias""", f"""vilt.encoder.layer.{i}.output.dense.bias"""))

				# embeddings
				rename_keys.extend(
				    [
				        # text embeddings
				        ('''text_embeddings.word_embeddings.weight''', '''vilt.embeddings.text_embeddings.word_embeddings.weight'''),
				        (
				            '''text_embeddings.position_embeddings.weight''',
				            '''vilt.embeddings.text_embeddings.position_embeddings.weight''',
				        ),
				        ('''text_embeddings.position_ids''', '''vilt.embeddings.text_embeddings.position_ids'''),
				        (
				            '''text_embeddings.token_type_embeddings.weight''',
				            '''vilt.embeddings.text_embeddings.token_type_embeddings.weight''',
				        ),
				        ('''text_embeddings.LayerNorm.weight''', '''vilt.embeddings.text_embeddings.LayerNorm.weight'''),
				        ('''text_embeddings.LayerNorm.bias''', '''vilt.embeddings.text_embeddings.LayerNorm.bias'''),
				        # patch embeddings
				        ('''transformer.cls_token''', '''vilt.embeddings.cls_token'''),
				        ('''transformer.patch_embed.proj.weight''', '''vilt.embeddings.patch_embeddings.projection.weight'''),
				        ('''transformer.patch_embed.proj.bias''', '''vilt.embeddings.patch_embeddings.projection.bias'''),
				        ('''transformer.pos_embed''', '''vilt.embeddings.position_embeddings'''),
				        # token type embeddings
				        ('''token_type_embeddings.weight''', '''vilt.embeddings.token_type_embeddings.weight'''),
				    ])

				# final layernorm + pooler
				rename_keys.extend(
				    [
				        ('''transformer.norm.weight''', '''vilt.layernorm.weight'''),
				        ('''transformer.norm.bias''', '''vilt.layernorm.bias'''),
				        ('''pooler.dense.weight''', '''vilt.pooler.dense.weight'''),
				        ('''pooler.dense.bias''', '''vilt.pooler.dense.bias'''),
				    ])

				# classifier head(s)
				if vqa_model:
								# classification head
								rename_keys.extend(
								    [
								        ('''vqa_classifier.0.weight''', '''classifier.0.weight'''),
								        ('''vqa_classifier.0.bias''', '''classifier.0.bias'''),
								        ('''vqa_classifier.1.weight''', '''classifier.1.weight'''),
								        ('''vqa_classifier.1.bias''', '''classifier.1.bias'''),
								        ('''vqa_classifier.3.weight''', '''classifier.3.weight'''),
								        ('''vqa_classifier.3.bias''', '''classifier.3.bias'''),
								    ])
				elif nlvr_model:
								# classification head
								rename_keys.extend(
								    [
								        ('''nlvr2_classifier.0.weight''', '''classifier.0.weight'''),
								        ('''nlvr2_classifier.0.bias''', '''classifier.0.bias'''),
								        ('''nlvr2_classifier.1.weight''', '''classifier.1.weight'''),
								        ('''nlvr2_classifier.1.bias''', '''classifier.1.bias'''),
								        ('''nlvr2_classifier.3.weight''', '''classifier.3.weight'''),
								        ('''nlvr2_classifier.3.bias''', '''classifier.3.bias'''),
								    ])
				else:
								pass

				return rename_keys






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Optional[int] ,lowerCamelCase_	:	Dict):





				'''simple docstring'''

				for i in range(config.num_hidden_layers):
								lowerCAmelCase__  :       str				=  '''vilt.'''
								# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
								lowerCAmelCase__  :       Union[str, Any]				=  state_dict.pop(f"""transformer.blocks.{i}.attn.qkv.weight""")
								lowerCAmelCase__  :       List[Any]				=  state_dict.pop(f"""transformer.blocks.{i}.attn.qkv.bias""")
								# next, add query, keys and values (in that order) to the state dict
								lowerCAmelCase__  :       str				=  in_proj_weight[
								    : config.hidden_size, :
								]
								lowerCAmelCase__  :       Optional[Any]				=  in_proj_bias[: config.hidden_size]
								lowerCAmelCase__  :       Dict				=  in_proj_weight[
								    config.hidden_size : config.hidden_size * 2, :
								]
								lowerCAmelCase__  :       int				=  in_proj_bias[
								    config.hidden_size : config.hidden_size * 2
								]
								lowerCAmelCase__  :       List[Any]				=  in_proj_weight[
								    -config.hidden_size :, :
								]
								lowerCAmelCase__  :       Union[str, Any]				=  in_proj_bias[-config.hidden_size :]






def 			lowerCAmelCase__	(					lowerCamelCase_	:	Union[str, Any]):





				'''simple docstring'''

				lowerCAmelCase__  :       List[str]				=  ['''head.weight''', '''head.bias''']
				for k in ignore_keys:
								state_dict.pop(lowerCamelCase_ ,lowerCamelCase_)






def 			lowerCAmelCase__	(					lowerCamelCase_	:	str ,lowerCamelCase_	:	int ,lowerCamelCase_	:	int):





				'''simple docstring'''

				lowerCAmelCase__  :       Any				=  dct.pop(lowerCamelCase_)
				lowerCAmelCase__  :       Optional[Any]				=  val






@torch.no_grad()
def 			lowerCAmelCase__	(					lowerCamelCase_	:	Tuple ,lowerCamelCase_	:	int):





				'''simple docstring'''

				lowerCAmelCase__  :       List[str]				=  ViltConfig(image_size=384 ,patch_size=32 ,tie_word_embeddings=lowerCamelCase_)
				lowerCAmelCase__  :       Dict				=  False
				lowerCAmelCase__  :       Tuple				=  False
				lowerCAmelCase__  :       Union[str, Any]				=  False
				lowerCAmelCase__  :       int				=  False
				if "vqa" in checkpoint_url:
								lowerCAmelCase__  :       Tuple				=  True
								lowerCAmelCase__  :       Any				=  3129
								lowerCAmelCase__  :       Optional[Any]				=  '''huggingface/label-files'''
								lowerCAmelCase__  :       List[str]				=  '''vqa2-id2label.json'''
								lowerCAmelCase__  :       Union[str, Any]				=  json.load(open(hf_hub_download(lowerCamelCase_ ,lowerCamelCase_ ,repo_type='''dataset''') ,'''r'''))
								lowerCAmelCase__  :       Any				=  {int(lowerCamelCase_): v for k, v in idalabel.items()}
								lowerCAmelCase__  :       Dict				=  idalabel
								lowerCAmelCase__  :       int				=  {v: k for k, v in idalabel.items()}
								lowerCAmelCase__  :       str				=  ViltForQuestionAnswering(lowerCamelCase_)
				elif "nlvr" in checkpoint_url:
								lowerCAmelCase__  :       int				=  True
								lowerCAmelCase__  :       Dict				=  2
								lowerCAmelCase__  :       List[str]				=  {0: '''False''', 1: '''True'''}
								lowerCAmelCase__  :       Optional[Any]				=  {v: k for k, v in config.idalabel.items()}
								lowerCAmelCase__  :       int				=  3
								lowerCAmelCase__  :       List[Any]				=  ViltForImagesAndTextClassification(lowerCamelCase_)
				elif "irtr" in checkpoint_url:
								lowerCAmelCase__  :       Optional[Any]				=  True
								lowerCAmelCase__  :       int				=  ViltForImageAndTextRetrieval(lowerCamelCase_)
				elif "mlm_itm" in checkpoint_url:
								lowerCAmelCase__  :       int				=  True
								lowerCAmelCase__  :       str				=  ViltForMaskedLM(lowerCamelCase_)
				else:
								raise ValueError('''Unknown model type''')

				# load state_dict of original model, remove and rename some keys
				lowerCAmelCase__  :       Tuple				=  torch.hub.load_state_dict_from_url(lowerCamelCase_ ,map_location='''cpu''')['''state_dict''']
				lowerCAmelCase__  :       Any				=  create_rename_keys(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_)
				for src, dest in rename_keys:
								rename_key(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_)
				read_in_q_k_v(lowerCamelCase_ ,lowerCamelCase_)
				if mlm_model or irtr_model:
								lowerCAmelCase__  :       Optional[int]				=  ['''itm_score.fc.weight''', '''itm_score.fc.bias''']
								for k in ignore_keys:
												state_dict.pop(lowerCamelCase_ ,lowerCamelCase_)

    # load state dict into HuggingFace model
				model.eval()
				if mlm_model:
								lowerCAmelCase__  :       Dict				=  model.load_state_dict(lowerCamelCase_ ,strict=lowerCamelCase_)
								assert missing_keys == ["mlm_score.decoder.bias"]
				else:
								model.load_state_dict(lowerCamelCase_)

				# Define processor
				lowerCAmelCase__  :       Optional[Any]				=  ViltImageProcessor(size=384)
				lowerCAmelCase__  :       int				=  BertTokenizer.from_pretrained('''bert-base-uncased''')
				lowerCAmelCase__  :       List[Any]				=  ViltProcessor(lowerCamelCase_ ,lowerCamelCase_)

				# Forward pass on example inputs (image + text)
				if nlvr_model:
								lowerCAmelCase__  :       List[Any]				=  Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg''' ,stream=lowerCamelCase_).raw)
								lowerCAmelCase__  :       Dict				=  Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg''' ,stream=lowerCamelCase_).raw)
								lowerCAmelCase__  :       Dict				=  (
								    '''The left image contains twice the number of dogs as the right image, and at least two dogs in total are'''
								    ''' standing.'''
								)
								lowerCAmelCase__  :       List[Any]				=  processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''')
								lowerCAmelCase__  :       str				=  processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''')
								lowerCAmelCase__  :       Optional[int]				=  model(
								    input_ids=encoding_a.input_ids ,pixel_values=encoding_a.pixel_values ,pixel_values_a=encoding_a.pixel_values ,)
				else:
								lowerCAmelCase__  :       List[str]				=  Image.open(requests.get('''http://images.cocodataset.org/val2017/000000039769.jpg''' ,stream=lowerCamelCase_).raw)
								if mlm_model:
												lowerCAmelCase__  :       int				=  '''a bunch of [MASK] laying on a [MASK].'''
								else:
												lowerCAmelCase__  :       Dict				=  '''How many cats are there?'''
								lowerCAmelCase__  :       List[Any]				=  processor(lowerCamelCase_ ,lowerCamelCase_ ,return_tensors='''pt''')
								lowerCAmelCase__  :       Tuple				=  model(**lowerCamelCase_)

				# Verify outputs
				if mlm_model:
								lowerCAmelCase__  :       Union[str, Any]				=  torch.Size([1, 11, 30522])
								lowerCAmelCase__  :       Dict				=  torch.tensor([-12.5061, -12.5123, -12.5174])
								assert outputs.logits.shape == expected_shape
								assert torch.allclose(outputs.logits[0, 0, :3] ,lowerCamelCase_ ,atol=1E-4)

								# verify masked token prediction equals "cats"
								lowerCAmelCase__  :       Optional[int]				=  outputs.logits[0, 4, :].argmax(-1).item()
								assert tokenizer.decode([predicted_id]) == "cats"
				elif vqa_model:
								lowerCAmelCase__  :       Any				=  torch.Size([1, 3129])
								lowerCAmelCase__  :       int				=  torch.tensor([-15.9495, -18.1472, -10.3041])
								assert torch.allclose(outputs.logits[0, :3] ,lowerCamelCase_ ,atol=1E-4)
								assert outputs.logits.shape == expected_shape
								assert torch.allclose(outputs.logits[0, 0, :3] ,lowerCamelCase_ ,atol=1E-4)

								# verify vqa prediction equals "2"
								lowerCAmelCase__  :       Dict				=  outputs.logits.argmax(-1).item()
								assert model.config.idalabel[predicted_idx] == "2"
				elif nlvr_model:
								lowerCAmelCase__  :       Dict				=  torch.Size([1, 2])
								lowerCAmelCase__  :       List[str]				=  torch.tensor([-2.8721, 2.1291])
								assert torch.allclose(outputs.logits[0, :3] ,lowerCamelCase_ ,atol=1E-4)
								assert outputs.logits.shape == expected_shape

				Path(lowerCamelCase_).mkdir(exist_ok=lowerCamelCase_)
				print(f"""Saving model and processor to {pytorch_dump_folder_path}""")
				model.save_pretrained(lowerCamelCase_)
				processor.save_pretrained(lowerCamelCase_)


if __name__ == "__main__":
							__snake_case       :	Optional[Any]            =argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    '--checkpoint_url',
							    default='https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt',
							    type=str,
							    help='URL of the checkpoint you\'d like to convert.',
							)
							parser.add_argument(
							    '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
							)

							__snake_case       :	Tuple            =parser.parse_args()
							convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)






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




		'''simple docstring'''



		snake_case_			=AltDiffusionPipeline
		snake_case_			=TEXT_TO_IMAGE_PARAMS
		snake_case_			=TEXT_TO_IMAGE_BATCH_PARAMS
		snake_case_			=TEXT_TO_IMAGE_IMAGE_PARAMS
		snake_case_			=TEXT_TO_IMAGE_IMAGE_PARAMS



		def 	lowerCAmelCase__   (self				)  ->    Dict:

						"""simple docstring"""






						torch.manual_seed(0				)
						lowerCAmelCase__  :       int				=  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	,)
						lowerCAmelCase__  :       List[str]				=  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				)
						lowerCAmelCase__  :       Optional[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				)
						lowerCAmelCase__  :       Dict				=  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=50_02	,)
						lowerCAmelCase__  :       int				=  CLIPTextModel(__lowerCamelCase				)

						lowerCAmelCase__  :       str				=  XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''				)
						lowerCAmelCase__  :       Union[str, Any]				=  77

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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase=0				)  ->    Optional[Any]:

						"""simple docstring"""






						if str(__lowerCamelCase				).startswith('''mps'''				):
										lowerCAmelCase__  :       Tuple				=  torch.manual_seed(__lowerCamelCase				)
						else:
										lowerCAmelCase__  :       Any				=  torch.Generator(device=__lowerCamelCase				).manual_seed(__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[Any]				=  {
						    '''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				)  ->    str:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self				)  ->    Tuple:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self				)  ->    Tuple:

						"""simple docstring"""






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

						lowerCAmelCase__  :       int				=  self.get_dummy_components()
						torch.manual_seed(0				)
						lowerCAmelCase__  :       str				=  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=50_02	,)
						# TODO: remove after fixing the non-deterministic text encoder
						lowerCAmelCase__  :       Any				=  RobertaSeriesModelWithTransformation(__lowerCamelCase				)
						lowerCAmelCase__  :       List[str]				=  text_encoder

						lowerCAmelCase__  :       List[Any]				=  AltDiffusionPipeline(**__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[Any]				=  alt_pipe.to(__lowerCamelCase				)
						alt_pipe.set_progress_bar_config(disable=__lowerCamelCase				)

						lowerCAmelCase__  :       List[str]				=  self.get_dummy_inputs(__lowerCamelCase				)
						lowerCAmelCase__  :       str				=  '''A photo of an astronaut'''
						lowerCAmelCase__  :       Any				=  alt_pipe(**__lowerCamelCase				)
						lowerCAmelCase__  :       int				=  output.images
						lowerCAmelCase__  :       List[Any]				=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						lowerCAmelCase__  :       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 	lowerCAmelCase__   (self				)  ->    Optional[int]:

						"""simple docstring"""






						lowerCAmelCase__  :       List[Any]				=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator

						lowerCAmelCase__  :       str				=  self.get_dummy_components()
						lowerCAmelCase__  :       Optional[Any]				=  PNDMScheduler(skip_prk_steps=__lowerCamelCase				)
						torch.manual_seed(0				)
						lowerCAmelCase__  :       int				=  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=50_02	,)
						# TODO: remove after fixing the non-deterministic text encoder
						lowerCAmelCase__  :       Tuple				=  RobertaSeriesModelWithTransformation(__lowerCamelCase				)
						lowerCAmelCase__  :       List[str]				=  text_encoder
						lowerCAmelCase__  :       List[Any]				=  AltDiffusionPipeline(**__lowerCamelCase				)
						lowerCAmelCase__  :       str				=  alt_pipe.to(__lowerCamelCase				)
						alt_pipe.set_progress_bar_config(disable=__lowerCamelCase				)

						lowerCAmelCase__  :       Union[str, Any]				=  self.get_dummy_inputs(__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[int]				=  alt_pipe(**__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[int]				=  output.images
						lowerCAmelCase__  :       str				=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						lowerCAmelCase__  :       Union[str, Any]				=  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  lowerCamelCase__    (							unittest.TestCase):




		'''simple docstring'''



		def 	lowerCAmelCase__   (self				)  ->    List[Any]:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self				)  ->    List[str]:

						"""simple docstring"""






						lowerCAmelCase__  :       Union[str, Any]				=  AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''	,safety_checker=__lowerCamelCase				)
						lowerCAmelCase__  :       List[Any]				=  alt_pipe.to(__lowerCamelCase				)
						alt_pipe.set_progress_bar_config(disable=__lowerCamelCase				)

						lowerCAmelCase__  :       Any				=  '''A painting of a squirrel eating a burger'''
						lowerCAmelCase__  :       List[Any]				=  torch.manual_seed(0				)
						lowerCAmelCase__  :       str				=  alt_pipe([prompt]	,generator=__lowerCamelCase	,guidance_scale=6.0	,num_inference_steps=20	,output_type='''np'''				)

						lowerCAmelCase__  :       str				=  output.images

						lowerCAmelCase__  :       int				=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						lowerCAmelCase__  :       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 	lowerCAmelCase__   (self				)  ->    Any:

						"""simple docstring"""






						lowerCAmelCase__  :       List[Any]				=  DDIMScheduler.from_pretrained('''BAAI/AltDiffusion'''	,subfolder='''scheduler'''				)

						lowerCAmelCase__  :       List[str]				=  AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''	,scheduler=__lowerCamelCase	,safety_checker=__lowerCamelCase				)
						lowerCAmelCase__  :       Union[str, Any]				=  alt_pipe.to(__lowerCamelCase				)
						alt_pipe.set_progress_bar_config(disable=__lowerCamelCase				)

						lowerCAmelCase__  :       List[Any]				=  '''A painting of a squirrel eating a burger'''
						lowerCAmelCase__  :       Optional[Any]				=  torch.manual_seed(0				)

						lowerCAmelCase__  :       List[str]				=  alt_pipe([prompt]	,generator=__lowerCamelCase	,num_inference_steps=2	,output_type='''numpy'''				)
						lowerCAmelCase__  :       List[str]				=  output.images

						lowerCAmelCase__  :       Optional[int]				=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						lowerCAmelCase__  :       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

