





import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available


if is_vision_available():
						from PIL import Image

						from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor




@require_vision
class 			_a						(				unittest.TestCase    ):






				def     snake_case     (			self		:   Tuple							)     ->				Dict:




										'''simple docstring'''



										_UpperCamelCase      : int         =   tempfile.mkdtemp()

										_UpperCamelCase      : List[str]         =   [
										    '''[UNK]''',
										    '''[CLS]''',
										    '''[SEP]''',
										    '''[PAD]''',
										    '''[MASK]''',
										    '''的''',
										    '''价''',
										    '''格''',
										    '''是''',
										    '''15''',
										    '''便''',
										    '''alex''',
										    '''##andra''',
										    '''，''',
										    '''。''',
										    '''-''',
										    '''t''',
										    '''shirt''',
										]
										_UpperCamelCase      : Optional[Any]         =   os.path.join(self.tmpdirname,			VOCAB_FILES_NAMES['''vocab_file''']							)
										with open(self.vocab_file,			'''w''',			encoding='''utf-8'''							) as vocab_writer:
																vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]							)							)

										_UpperCamelCase      : Dict         =   {
										    '''do_resize''': True,
										    '''size''': {'''height''': 2_2_4, '''width''': 2_2_4},
										    '''do_center_crop''': True,
										    '''crop_size''': {'''height''': 1_8, '''width''': 1_8},
										    '''do_normalize''': True,
										    '''image_mean''': [0.48_145_466, 0.4_578_275, 0.40_821_073],
										    '''image_std''': [0.26_862_954, 0.26_130_258, 0.27_577_711],
										    '''do_convert_rgb''': True,
										}
										_UpperCamelCase      : Optional[Any]         =   os.path.join(self.tmpdirname,			lowerCAmelCase__							)
										with open(self.image_processor_file,			'''w''',			encoding='''utf-8'''							) as fp:
																json.dump(lowerCAmelCase__,			lowerCAmelCase__							)






				def     snake_case     (			self		:   str,			**lowerCAmelCase__		:   List[Any]							)     ->				Optional[int]:




										'''simple docstring'''



										return BertTokenizer.from_pretrained(self.tmpdirname,			**lowerCAmelCase__							)






				def     snake_case     (			self		:   Union[str, Any],			**lowerCAmelCase__		:   Tuple							)     ->				str:




										'''simple docstring'''



										return BertTokenizerFast.from_pretrained(self.tmpdirname,			**lowerCAmelCase__							)






				def     snake_case     (			self		:   Any,			**lowerCAmelCase__		:   Optional[int]							)     ->				Optional[Any]:




										'''simple docstring'''



										return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname,			**lowerCAmelCase__							)






				def     snake_case     (			self		:   str							)     ->				Optional[int]:




										'''simple docstring'''



										shutil.rmtree(self.tmpdirname							)






				def     snake_case     (			self		:   Any							)     ->				int:




										'''simple docstring'''



										_UpperCamelCase      : List[str]         =   [np.random.randint(2_5_5,			size=(3, 3_0, 4_0_0),			dtype=np.uinta							)]

										_UpperCamelCase      : List[Any]         =   [Image.fromarray(np.moveaxis(lowerCAmelCase__,			0,			-1							)							) for x in image_inputs]

										return image_inputs






				def     snake_case     (			self		:   str							)     ->				Any:




										'''simple docstring'''



										_UpperCamelCase      : Any         =   self.get_tokenizer()
										_UpperCamelCase      : int         =   self.get_rust_tokenizer()
										_UpperCamelCase      : int         =   self.get_image_processor()

										_UpperCamelCase      : Tuple         =   ChineseCLIPProcessor(tokenizer=lowerCAmelCase__,			image_processor=lowerCAmelCase__							)
										processor_slow.save_pretrained(self.tmpdirname							)
										_UpperCamelCase      : List[Any]         =   ChineseCLIPProcessor.from_pretrained(self.tmpdirname,			use_fast=lowerCAmelCase__							)

										_UpperCamelCase      : List[Any]         =   ChineseCLIPProcessor(tokenizer=lowerCAmelCase__,			image_processor=lowerCAmelCase__							)
										processor_fast.save_pretrained(self.tmpdirname							)
										_UpperCamelCase      : List[Any]         =   ChineseCLIPProcessor.from_pretrained(self.tmpdirname							)

										self.assertEqual(processor_slow.tokenizer.get_vocab(),			tokenizer_slow.get_vocab()							)
										self.assertEqual(processor_fast.tokenizer.get_vocab(),			tokenizer_fast.get_vocab()							)
										self.assertEqual(tokenizer_slow.get_vocab(),			tokenizer_fast.get_vocab()							)
										self.assertIsInstance(processor_slow.tokenizer,			lowerCAmelCase__							)
										self.assertIsInstance(processor_fast.tokenizer,			lowerCAmelCase__							)

										self.assertEqual(processor_slow.image_processor.to_json_string(),			image_processor.to_json_string()							)
										self.assertEqual(processor_fast.image_processor.to_json_string(),			image_processor.to_json_string()							)
										self.assertIsInstance(processor_slow.image_processor,			lowerCAmelCase__							)
										self.assertIsInstance(processor_fast.image_processor,			lowerCAmelCase__							)






				def     snake_case     (			self		:   int							)     ->				Tuple:




										'''simple docstring'''



										_UpperCamelCase      : List[Any]         =   ChineseCLIPProcessor(tokenizer=self.get_tokenizer(),			image_processor=self.get_image_processor()							)
										processor.save_pretrained(self.tmpdirname							)

										_UpperCamelCase      : Dict         =   self.get_tokenizer(cls_token='''(CLS)''',			sep_token='''(SEP)'''							)
										_UpperCamelCase      : List[str]         =   self.get_image_processor(do_normalize=lowerCAmelCase__							)

										_UpperCamelCase      : Optional[Any]         =   ChineseCLIPProcessor.from_pretrained(
										    self.tmpdirname,			cls_token='''(CLS)''',			sep_token='''(SEP)''',			do_normalize=lowerCAmelCase__							)

										self.assertEqual(processor.tokenizer.get_vocab(),			tokenizer_add_kwargs.get_vocab()							)
										self.assertIsInstance(processor.tokenizer,			lowerCAmelCase__							)

										self.assertEqual(processor.image_processor.to_json_string(),			image_processor_add_kwargs.to_json_string()							)
										self.assertIsInstance(processor.image_processor,			lowerCAmelCase__							)






				def     snake_case     (			self		:   Optional[int]							)     ->				Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase      : List[str]         =   self.get_image_processor()
										_UpperCamelCase      : str         =   self.get_tokenizer()

										_UpperCamelCase      : Optional[Any]         =   ChineseCLIPProcessor(tokenizer=lowerCAmelCase__,			image_processor=lowerCAmelCase__							)

										_UpperCamelCase      : List[str]         =   self.prepare_image_inputs()

										_UpperCamelCase      : Any         =   image_processor(lowerCAmelCase__,			return_tensors='''np'''							)
										_UpperCamelCase      : Any         =   processor(images=lowerCAmelCase__,			return_tensors='''np'''							)

										for key in input_feat_extract.keys():
																self.assertAlmostEqual(input_feat_extract[key].sum(),			input_processor[key].sum(),			delta=1e-2							)






				def     snake_case     (			self		:   Optional[Any]							)     ->				Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase      : Tuple         =   self.get_image_processor()
										_UpperCamelCase      : Optional[Any]         =   self.get_tokenizer()

										_UpperCamelCase      : Any         =   ChineseCLIPProcessor(tokenizer=lowerCAmelCase__,			image_processor=lowerCAmelCase__							)

										_UpperCamelCase      : Tuple         =   '''Alexandra，T-shirt的价格是15便士。'''

										_UpperCamelCase      : List[str]         =   processor(text=lowerCAmelCase__							)

										_UpperCamelCase      : Any         =   tokenizer(lowerCAmelCase__							)

										for key in encoded_tok.keys():
																self.assertListEqual(encoded_tok[key],			encoded_processor[key]							)






				def     snake_case     (			self		:   Dict							)     ->				Tuple:




										'''simple docstring'''



										_UpperCamelCase      : Tuple         =   self.get_image_processor()
										_UpperCamelCase      : Optional[Any]         =   self.get_tokenizer()

										_UpperCamelCase      : Dict         =   ChineseCLIPProcessor(tokenizer=lowerCAmelCase__,			image_processor=lowerCAmelCase__							)

										_UpperCamelCase      : Any         =   '''Alexandra，T-shirt的价格是15便士。'''
										_UpperCamelCase      : Union[str, Any]         =   self.prepare_image_inputs()

										_UpperCamelCase      : str         =   processor(text=lowerCAmelCase__,			images=lowerCAmelCase__							)

										self.assertListEqual(list(inputs.keys()							),			['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values''']							)

										# test if it raises when no input is passed
										with pytest.raises(lowerCAmelCase__							):
																processor()






				def     snake_case     (			self		:   Optional[Any]							)     ->				Union[str, Any]:




										'''simple docstring'''



										_UpperCamelCase      : int         =   self.get_image_processor()
										_UpperCamelCase      : int         =   self.get_tokenizer()

										_UpperCamelCase      : Optional[Any]         =   ChineseCLIPProcessor(tokenizer=lowerCAmelCase__,			image_processor=lowerCAmelCase__							)

										_UpperCamelCase      : List[Any]         =   [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

										_UpperCamelCase      : List[Any]         =   processor.batch_decode(lowerCAmelCase__							)
										_UpperCamelCase      : Dict         =   tokenizer.batch_decode(lowerCAmelCase__							)

										self.assertListEqual(lowerCAmelCase__,			lowerCAmelCase__							)






				def     snake_case     (			self		:   Union[str, Any]							)     ->				Dict:




										'''simple docstring'''



										_UpperCamelCase      : Any         =   self.get_image_processor()
										_UpperCamelCase      : Optional[int]         =   self.get_tokenizer()

										_UpperCamelCase      : Optional[Any]         =   ChineseCLIPProcessor(tokenizer=lowerCAmelCase__,			image_processor=lowerCAmelCase__							)

										_UpperCamelCase      : Any         =   '''Alexandra，T-shirt的价格是15便士。'''
										_UpperCamelCase      : int         =   self.prepare_image_inputs()

										_UpperCamelCase      : Dict         =   processor(text=lowerCAmelCase__,			images=lowerCAmelCase__							)

										self.assertListEqual(list(inputs.keys()							),			processor.model_input_names							)










"""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 			_a						(				_lowerCAmelCase     ,    _lowerCAmelCase     ,    _lowerCAmelCase     ,    unittest.TestCase    ):
				UpperCamelCase								=   AltDiffusionPipeline
				UpperCamelCase								=   TEXT_TO_IMAGE_PARAMS
				UpperCamelCase								=   TEXT_TO_IMAGE_BATCH_PARAMS
				UpperCamelCase								=   TEXT_TO_IMAGE_IMAGE_PARAMS
				UpperCamelCase								=   TEXT_TO_IMAGE_IMAGE_PARAMS






				def     snake_case     (			self		:   int							)     ->				int:




										'''simple docstring'''



										torch.manual_seed(0							)
										_UpperCamelCase      : Dict         =   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,			)
										_UpperCamelCase      : Union[str, Any]         =   DDIMScheduler(
										    beta_start=0.00_085,			beta_end=0.012,			beta_schedule='''scaled_linear''',			clip_sample=lowerCAmelCase__,			set_alpha_to_one=lowerCAmelCase__,			)
										torch.manual_seed(0							)
										_UpperCamelCase      : List[str]         =   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							)
										_UpperCamelCase      : str         =   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-0_5,			num_attention_heads=4,			num_hidden_layers=5,			pad_token_id=1,			vocab_size=5_0_0_2,			)
										_UpperCamelCase      : List[Any]         =   CLIPTextModel(lowerCAmelCase__							)

										_UpperCamelCase      : Dict         =   XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''							)
										_UpperCamelCase      : str         =   7_7

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






				def     snake_case     (			self		:   Dict,			lowerCAmelCase__		:   Any,			lowerCAmelCase__		:   int=0							)     ->				Optional[int]:




										'''simple docstring'''



										if str(lowerCAmelCase__							).startswith('''mps'''							):
																_UpperCamelCase      : Any         =   torch.manual_seed(lowerCAmelCase__							)
										else:
																_UpperCamelCase      : Dict         =   torch.Generator(device=lowerCAmelCase__							).manual_seed(lowerCAmelCase__							)
										_UpperCamelCase      : str         =   {
										    '''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     snake_case     (			self		:   List[Any]							)     ->				List[str]:




										'''simple docstring'''



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






				def     snake_case     (			self		:   List[Any]							)     ->				Tuple:




										'''simple docstring'''



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






				def     snake_case     (			self		:   List[str]							)     ->				List[Any]:




										'''simple docstring'''



										_UpperCamelCase      : Any         =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator

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

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

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

										assert image.shape == (1, 6_4, 6_4, 3)
										_UpperCamelCase      : List[Any]         =   np.array(
										    [0.5_748_162, 0.60_447_145, 0.48_821_217, 0.50_100_636, 0.5_431_185, 0.45_763_683, 0.49_657_696, 0.48_132_733, 0.47_573_093]							)

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






				def     snake_case     (			self		:   int							)     ->				Optional[Any]:




										'''simple docstring'''



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

										_UpperCamelCase      : Optional[Any]         =   self.get_dummy_components()
										_UpperCamelCase      : str         =   PNDMScheduler(skip_prk_steps=lowerCAmelCase__							)
										torch.manual_seed(0							)
										_UpperCamelCase      : int         =   RobertaSeriesConfig(
										    hidden_size=3_2,			project_dim=3_2,			intermediate_size=3_7,			layer_norm_eps=1e-0_5,			num_attention_heads=4,			num_hidden_layers=5,			vocab_size=5_0_0_2,			)
										# TODO: remove after fixing the non-deterministic text encoder
										_UpperCamelCase      : Tuple         =   RobertaSeriesModelWithTransformation(lowerCAmelCase__							)
										_UpperCamelCase      : int         =   text_encoder
										_UpperCamelCase      : str         =   AltDiffusionPipeline(**lowerCAmelCase__							)
										_UpperCamelCase      : List[str]         =   alt_pipe.to(lowerCAmelCase__							)
										alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

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

										assert image.shape == (1, 6_4, 6_4, 3)
										_UpperCamelCase      : List[Any]         =   np.array(
										    [0.51_605_093, 0.5_707_241, 0.47_365_507, 0.50_578_886, 0.5_633_877, 0.4_642_503, 0.5_182_081, 0.48_763_484, 0.49_084_237]							)

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




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






				def     snake_case     (			self		:   List[str]							)     ->				Any:




										'''simple docstring'''



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






				def     snake_case     (			self		:   Union[str, Any]							)     ->				Any:




										'''simple docstring'''



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

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

										_UpperCamelCase      : Optional[int]         =   output.images

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

										assert image.shape == (1, 5_1_2, 5_1_2, 3)
										_UpperCamelCase      : List[str]         =   np.array([0.1_010, 0.0_800, 0.0_794, 0.0_885, 0.0_843, 0.0_762, 0.0_769, 0.0_729, 0.0_586]							)

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






				def     snake_case     (			self		:   str							)     ->				str:




										'''simple docstring'''



										_UpperCamelCase      : Any         =   DDIMScheduler.from_pretrained('''BAAI/AltDiffusion''',			subfolder='''scheduler'''							)

										_UpperCamelCase      : Dict         =   AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion''',			scheduler=lowerCAmelCase__,			safety_checker=lowerCAmelCase__							)
										_UpperCamelCase      : Dict         =   alt_pipe.to(lowerCAmelCase__							)
										alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__							)

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

										_UpperCamelCase      : Union[str, Any]         =   alt_pipe([prompt],			generator=lowerCAmelCase__,			num_inference_steps=2,			output_type='''numpy'''							)
										_UpperCamelCase      : Tuple         =   output.images

										_UpperCamelCase      : Dict         =   image[0, -3:, -3:, -1]

										assert image.shape == (1, 5_1_2, 5_1_2, 3)
										_UpperCamelCase      : str         =   np.array([0.4_019, 0.4_052, 0.3_810, 0.4_119, 0.3_916, 0.3_982, 0.4_651, 0.4_195, 0.5_323]							)

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



