






import unittest

from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


__lowerCamelCase						:		int				      = get_tests_dir("""fixtures/test_sentencepiece.model""")







@require_sentencepiece
@require_tokenizers
class 			_lowercase ( _UpperCamelCase    ,					unittest.TestCase    ):
      _a				:    Union[str, Any]				      =				XLNetTokenizer
      _a				:    int				      =				XLNetTokenizerFast
      _a				:    Optional[Any]				      =				True
      _a				:    Optional[Any]				      =				True
      def     lowercase__       (  self ):
       super().setUp()

       # We have a SentencePiece fixture for testing
       snake_case__	:     Optional[Any]											=XLNetTokenizer(lowercase__					,      keep_accents=lowercase__ )
       tokenizer.sanitize_special_tokens()
       tokenizer.save_pretrained(self.tmpdirname )
      def     lowercase__       (  self ):
       snake_case__	:     Tuple											='''<s>'''
       snake_case__	:     List[str]											=1

       self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase__ )					,      lowercase__ )
       self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase__ )					,      lowercase__ )
      def     lowercase__       (  self ):
       snake_case__	:     Union[str, Any]											=list(self.get_tokenizer().get_vocab().keys() )

       self.assertEqual(vocab_keys[0]					,      """<unk>""" )
       self.assertEqual(vocab_keys[1]					,      """<s>""" )
       self.assertEqual(vocab_keys[-1]					,      """<eod>""" )
       self.assertEqual(len(lowercase__ )					,      1_0_0_6 )
      def     lowercase__       (  self ):
       self.assertEqual(self.get_tokenizer().vocab_size					,      1_0_0_0 )
      def     lowercase__       (  self ):
       snake_case__	:     List[str]											=XLNetTokenizer(lowercase__					,      keep_accents=lowercase__ )

       snake_case__	:     Optional[Any]											=tokenizer.tokenize("""This is a test""" )
       self.assertListEqual(lowercase__					,      ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] )

       self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase__ )					,      [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2] )

       snake_case__	:     Tuple											=tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
       self.assertListEqual(
           lowercase__					,      [
               SPIECE_UNDERLINE + """I""",
               SPIECE_UNDERLINE + """was""",
               SPIECE_UNDERLINE + """b""",
               """or""",
               """n""",
               SPIECE_UNDERLINE + """in""",
               SPIECE_UNDERLINE + """""",
               """9""",
               """2""",
               """0""",
               """0""",
               """0""",
               """,""",
               SPIECE_UNDERLINE + """and""",
               SPIECE_UNDERLINE + """this""",
               SPIECE_UNDERLINE + """is""",
               SPIECE_UNDERLINE + """f""",
               """al""",
               """s""",
               """é""",
               """.""",
           ]					,      )
       snake_case__	:     Union[str, Any]											=tokenizer.convert_tokens_to_ids(lowercase__ )
       self.assertListEqual(lowercase__					,      [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4] )

       snake_case__	:     int											=tokenizer.convert_ids_to_tokens(lowercase__ )
       self.assertListEqual(
           lowercase__					,      [
               SPIECE_UNDERLINE + """I""",
               SPIECE_UNDERLINE + """was""",
               SPIECE_UNDERLINE + """b""",
               """or""",
               """n""",
               SPIECE_UNDERLINE + """in""",
               SPIECE_UNDERLINE + """""",
               """<unk>""",
               """2""",
               """0""",
               """0""",
               """0""",
               """,""",
               SPIECE_UNDERLINE + """and""",
               SPIECE_UNDERLINE + """this""",
               SPIECE_UNDERLINE + """is""",
               SPIECE_UNDERLINE + """f""",
               """al""",
               """s""",
               """<unk>""",
               """.""",
           ]					,      )
      def     lowercase__       (  self ):
       snake_case__	:     str											=XLNetTokenizer(lowercase__					,      do_lower_case=lowercase__ )
       snake_case__	:     int											=tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
       self.assertListEqual(
           lowercase__					,      [
               SPIECE_UNDERLINE + """""",
               """i""",
               SPIECE_UNDERLINE + """was""",
               SPIECE_UNDERLINE + """b""",
               """or""",
               """n""",
               SPIECE_UNDERLINE + """in""",
               SPIECE_UNDERLINE + """""",
               """9""",
               """2""",
               """0""",
               """0""",
               """0""",
               """,""",
               SPIECE_UNDERLINE + """and""",
               SPIECE_UNDERLINE + """this""",
               SPIECE_UNDERLINE + """is""",
               SPIECE_UNDERLINE + """f""",
               """al""",
               """se""",
               """.""",
           ]					,      )
       self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" )					,      ["""▁he""", """ll""", """o"""] )
      def     lowercase__       (  self ):
       snake_case__	:     Optional[Any]											=XLNetTokenizer(lowercase__					,      do_lower_case=lowercase__ )
       snake_case__	:     Union[str, Any]											=tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
       self.assertListEqual(
           lowercase__					,      [
               SPIECE_UNDERLINE + """I""",
               SPIECE_UNDERLINE + """was""",
               SPIECE_UNDERLINE + """b""",
               """or""",
               """n""",
               SPIECE_UNDERLINE + """in""",
               SPIECE_UNDERLINE + """""",
               """9""",
               """2""",
               """0""",
               """0""",
               """0""",
               """,""",
               SPIECE_UNDERLINE + """and""",
               SPIECE_UNDERLINE + """this""",
               SPIECE_UNDERLINE + """is""",
               SPIECE_UNDERLINE + """f""",
               """al""",
               """se""",
               """.""",
           ]					,      )
      @slow
      def     lowercase__       (  self ):
       snake_case__	:     Tuple											=XLNetTokenizer.from_pretrained("""xlnet-base-cased""" )

       snake_case__	:     Optional[int]											=tokenizer.encode("""sequence builders"""					,      add_special_tokens=lowercase__ )
       snake_case__	:     Optional[int]											=tokenizer.encode("""multi-sequence build"""					,      add_special_tokens=lowercase__ )

       snake_case__	:     Union[str, Any]											=tokenizer.build_inputs_with_special_tokens(lowercase__ )
       snake_case__	:     Optional[Any]											=tokenizer.build_inputs_with_special_tokens(lowercase__					,      lowercase__ )

       assert encoded_sentence == text + [4, 3]
       assert encoded_pair == text + [4] + text_a + [4, 3]



      @slow
      def     lowercase__       (  self ):
       # fmt: off
       snake_case__	:     Optional[Any]											={'''input_ids''': [[1_7, 2_1_4_4_2, 2_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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}  # noqa: E501
       # fmt: on

       self.tokenizer_integration_test_util(
           expected_encoding=lowercase__					,      model_name="""xlnet-base-cased"""					,      revision="""c841166438c31ec7ca9a106dee7bb312b73ae511"""					,      )









import gc
import random
import unittest

import numpy as np
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModel,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    floats_tensor,
    load_image,
    load_numpy,
    require_torch_gpu,
    skip_mps,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()




class 							lowerCamelCase   (  _UpperCamelCase							,						_UpperCamelCase							,						_UpperCamelCase							,						unittest.TestCase ):
	_lowerCAmelCase     :		Optional[Any]										=						StableUnCLIPImgaImgPipeline
	_lowerCAmelCase     :		Any										=						TEXT_GUIDED_IMAGE_VARIATION_PARAMS
	_lowerCAmelCase     :		List[Any]										=						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	_lowerCAmelCase     :		Dict										=						frozenset(
	    [] )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
	_lowerCAmelCase     :		str										=						frozenset([] )


	def  A(    self):
							__UpperCAmelCase			:							Any	    =	3_2
							__UpperCAmelCase			:							Union[str, Any]	    =	embedder_hidden_size

							# image encoding components

							__UpperCAmelCase			:							Union[str, Any]	    =	CLIPImageProcessor(crop_size=3_2				,     size=3_2)

							torch.manual_seed(0)
							__UpperCAmelCase			:							List[str]	    =	CLIPVisionModelWithProjection(
							    CLIPVisionConfig(
							        hidden_size=lowercase__				,     projection_dim=lowercase__				,     num_hidden_layers=5				,     num_attention_heads=4				,     image_size=3_2				,     intermediate_size=3_7				,     patch_size=1				,     ))

							# regular denoising components

							torch.manual_seed(0)
							__UpperCAmelCase			:							List[Any]	    =	StableUnCLIPImageNormalizer(embedding_dim=lowercase__)
							__UpperCAmelCase			:							Any	    =	DDPMScheduler(beta_schedule='''squaredcos_cap_v2''')

							torch.manual_seed(0)
							__UpperCAmelCase			:							Dict	    =	CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

							torch.manual_seed(0)
							__UpperCAmelCase			:							int	    =	CLIPTextModel(
							    CLIPTextConfig(
							        bos_token_id=0				,     eos_token_id=2				,     hidden_size=lowercase__				,     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=1_0_0_0				,     ))

							torch.manual_seed(0)
							__UpperCAmelCase			:							Tuple	    =	UNetaDConditionModel(
							    sample_size=3_2				,     in_channels=4				,     out_channels=4				,     down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''')				,     up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''')				,     block_out_channels=(3_2, 6_4)				,     attention_head_dim=(2, 4)				,     class_embed_type='''projection'''				,     projection_class_embeddings_input_dim=embedder_projection_dim * 2				,     cross_attention_dim=lowercase__				,     layers_per_block=1				,     upcast_attention=lowercase__				,     use_linear_projection=lowercase__				,     )

							torch.manual_seed(0)
							__UpperCAmelCase			:							Optional[Any]	    =	DDIMScheduler(
							    beta_schedule='''scaled_linear'''				,     beta_start=0.0_0_0_8_5				,     beta_end=0.0_1_2				,     prediction_type='''v_prediction'''				,     set_alpha_to_one=lowercase__				,     steps_offset=1				,     )

							torch.manual_seed(0)
							__UpperCAmelCase			:							Optional[Any]	    =	AutoencoderKL()

							__UpperCAmelCase			:							Optional[Any]	    =	{
							    # image encoding components
							    '''feature_extractor''': feature_extractor,
							    '''image_encoder''': image_encoder.eval(),
							    # image noising components
							    '''image_normalizer''': image_normalizer.eval(),
							    '''image_noising_scheduler''': image_noising_scheduler,
							    # regular denoising components
							    '''tokenizer''': tokenizer,
							    '''text_encoder''': text_encoder.eval(),
							    '''unet''': unet.eval(),
							    '''scheduler''': scheduler,
							    '''vae''': vae.eval(),
							}

							return components


	def  A(    self				,     lowercase__				,     lowercase__=0				,     lowercase__=True):
							if str(lowercase__).startswith('''mps'''):
													__UpperCAmelCase			:							Union[str, Any]	    =	torch.manual_seed(lowercase__)
							else:
													__UpperCAmelCase			:							int	    =	torch.Generator(device=lowercase__).manual_seed(lowercase__)

							__UpperCAmelCase			:							Dict	    =	floats_tensor((1, 3, 3_2, 3_2)				,     rng=random.Random(lowercase__)).to(lowercase__)

							if pil_image:
													__UpperCAmelCase			:							int	    =	input_image * 0.5 + 0.5
													__UpperCAmelCase			:							str	    =	input_image.clamp(0				,     1)
													__UpperCAmelCase			:							Optional[int]	    =	input_image.cpu().permute(0				,     2				,     3				,     1).float().numpy()
													__UpperCAmelCase			:							Union[str, Any]	    =	DiffusionPipeline.numpy_to_pil(lowercase__)[0]

							return {
							    "prompt": "An anime racoon running a marathon",
							    "image": input_image,
							    "generator": generator,
							    "num_inference_steps": 2,
							    "output_type": "np",
							}


	@skip_mps
	def  A(    self):
							__UpperCAmelCase			:							Union[str, Any]	    =	'''cpu'''  # ensure determinism for the device-dependent torch.Generator
							__UpperCAmelCase			:							Dict	    =	self.get_dummy_components()
							__UpperCAmelCase			:							List[Any]	    =	StableUnCLIPImgaImgPipeline(**lowercase__)
							__UpperCAmelCase			:							List[str]	    =	sd_pipe.to(lowercase__)
							sd_pipe.set_progress_bar_config(disable=lowercase__)

							__UpperCAmelCase			:							Dict	    =	self.get_dummy_inputs(lowercase__)
							inputs.update({'''image_embeds''': None})
							__UpperCAmelCase			:							Any	    =	sd_pipe(**lowercase__).images
							__UpperCAmelCase			:							Union[str, Any]	    =	image[0, -3:, -3:, -1]

							assert image.shape == (1, 3_2, 3_2, 3)
							__UpperCAmelCase			:							Union[str, Any]	    =	np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8])

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


	def  A(    self):
							__UpperCAmelCase			:							Optional[Any]	    =	torch_device in ['''cpu''', '''mps''']

							self._test_attention_slicing_forward_pass(test_max_difference=lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							str	    =	torch_device in ['''cpu''', '''mps''']

							self._test_inference_batch_single_identical(test_max_difference=lowercase__)


	@unittest.skipIf(
	    torch_device != '''cuda''' or not is_xformers_available()				,     reason='''XFormers attention is only available with CUDA and `xformers` installed'''				,     )
	def  A(    self):
							self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowercase__)






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


	def  A(    self):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()


	def  A(    self):
							__UpperCAmelCase			:							Dict	    =	load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

							__UpperCAmelCase			:							List[str]	    =	load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy''')

							__UpperCAmelCase			:							Optional[int]	    =	StableUnCLIPImgaImgPipeline.from_pretrained(
							    '''fusing/stable-unclip-2-1-l-img2img'''				,     torch_dtype=torch.floataa)
							pipe.to(lowercase__)
							pipe.set_progress_bar_config(disable=lowercase__)
							# stable unclip will oom when integration tests are run on a V100,
							# so turn on memory savings
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__UpperCAmelCase			:							Optional[Any]	    =	torch.Generator(device='''cpu''').manual_seed(0)
							__UpperCAmelCase			:							Any	    =	pipe(lowercase__				,     '''anime turle'''				,     generator=lowercase__				,     output_type='''np''')

							__UpperCAmelCase			:							Optional[Any]	    =	output.images[0]

							assert image.shape == (7_6_8, 7_6_8, 3)

							assert_mean_pixel_difference(lowercase__				,     lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							str	    =	load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

							__UpperCAmelCase			:							Union[str, Any]	    =	load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy''')

							__UpperCAmelCase			:							Union[str, Any]	    =	StableUnCLIPImgaImgPipeline.from_pretrained(
							    '''fusing/stable-unclip-2-1-h-img2img'''				,     torch_dtype=torch.floataa)
							pipe.to(lowercase__)
							pipe.set_progress_bar_config(disable=lowercase__)
							# stable unclip will oom when integration tests are run on a V100,
							# so turn on memory savings
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__UpperCAmelCase			:							Dict	    =	torch.Generator(device='''cpu''').manual_seed(0)
							__UpperCAmelCase			:							int	    =	pipe(lowercase__				,     '''anime turle'''				,     generator=lowercase__				,     output_type='''np''')

							__UpperCAmelCase			:							List[str]	    =	output.images[0]

							assert image.shape == (7_6_8, 7_6_8, 3)

							assert_mean_pixel_difference(lowercase__				,     lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							str	    =	load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()

							__UpperCAmelCase			:							Optional[int]	    =	StableUnCLIPImgaImgPipeline.from_pretrained(
							    '''fusing/stable-unclip-2-1-h-img2img'''				,     torch_dtype=torch.floataa)
							__UpperCAmelCase			:							Optional[int]	    =	pipe.to(lowercase__)
							pipe.set_progress_bar_config(disable=lowercase__)
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__UpperCAmelCase			:							int	    =	pipe(
							    lowercase__				,     '''anime turtle'''				,     num_inference_steps=2				,     output_type='''np'''				,     )

							__UpperCAmelCase			:							Optional[Any]	    =	torch.cuda.max_memory_allocated()
							# make sure that less than 7 GB is allocated
							assert mem_bytes < 7 * 1_0**9

