


import json
import os
import re
import unittest

from transformers import CodeGenTokenizer, CodeGenTokenizerFast
from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class 	UpperCAmelCase_					(					UpperCamelCase		, unittest.TestCase    ):

   '''simple docstring'''




   __A :      str     		=		CodeGenTokenizer
   __A :      Dict     		=		CodeGenTokenizerFast
   __A :      List[Any]     		=		True
   __A :      List[str]     		=		{"add_prefix_space": True}
   __A :      List[str]     		=		False






   def _snake_case    (		self ):






     """simple docstring"""





     super().setUp()

     # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
     lowerCamelCase :					str    =				[
         "l",
         "o",
         "w",
         "e",
         "r",
         "s",
         "t",
         "i",
         "d",
         "n",
         "\u0120",
         "\u0120l",
         "\u0120n",
         "\u0120lo",
         "\u0120low",
         "er",
         "\u0120lowest",
         "\u0120newer",
         "\u0120wider",
         "<unk>",
         "<|endoftext|>",
     ]
     lowerCamelCase :					Dict    =				dict(zip(__A						,				range(len(__A ) ) ) )
     lowerCamelCase :					List[str]    =				["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
     lowerCamelCase :					List[str]    =				{"unk_token": "<unk>"}

     lowerCamelCase :					List[str]    =				os.path.join(self.tmpdirname						,				VOCAB_FILES_NAMES["vocab_file"] )
     lowerCamelCase :					Any    =				os.path.join(self.tmpdirname						,				VOCAB_FILES_NAMES["merges_file"] )
     with open(self.vocab_file						,				"w"						,				encoding="utf-8" ) as fp:
       fp.write(json.dumps(__A ) + "\n" )
     with open(self.merges_file						,				"w"						,				encoding="utf-8" ) as fp:
       fp.write("\n".join(__A ) )






   def _snake_case    (		self						,				**__A ):






     """simple docstring"""





     kwargs.update(self.special_tokens_map )
     return CodeGenTokenizer.from_pretrained(self.tmpdirname						,				**__A )






   def _snake_case    (		self						,				**__A ):






     """simple docstring"""





     kwargs.update(self.special_tokens_map )
     return CodeGenTokenizerFast.from_pretrained(self.tmpdirname						,				**__A )






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				"lower newer"
     lowerCamelCase :					Optional[int]    =				"lower newer"
     return input_text, output_text






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					str    =				CodeGenTokenizer(self.vocab_file						,				self.merges_file						,				**self.special_tokens_map )
     lowerCamelCase :					Dict    =				"lower newer"
     lowerCamelCase :					Any    =				["\u0120low", "er", "\u0120", "n", "e", "w", "er"]
     lowerCamelCase :					int    =				tokenizer.tokenize(__A						,				add_prefix_space=__A )
     self.assertListEqual(__A						,				__A )

     lowerCamelCase :					Tuple    =				tokens + [tokenizer.unk_token]
     lowerCamelCase :					Tuple    =				[14, 15, 10, 9, 3, 2, 15, 19]
     self.assertListEqual(tokenizer.convert_tokens_to_ids(__A )						,				__A )






   def _snake_case    (		self ):






     """simple docstring"""





     if not self.test_rust_tokenizer:
       return

     lowerCamelCase :					int    =				self.get_tokenizer()
     lowerCamelCase :					List[Any]    =				self.get_rust_tokenizer(add_prefix_space=__A )

     lowerCamelCase :					int    =				"lower newer"

     # Testing tokenization
     lowerCamelCase :					Union[str, Any]    =				tokenizer.tokenize(__A						,				add_prefix_space=__A )
     lowerCamelCase :					Optional[int]    =				rust_tokenizer.tokenize(__A )
     self.assertListEqual(__A						,				__A )

     # Testing conversion to ids without special tokens
     lowerCamelCase :					Optional[Any]    =				tokenizer.encode(__A						,				add_special_tokens=__A						,				add_prefix_space=__A )
     lowerCamelCase :					List[Any]    =				rust_tokenizer.encode(__A						,				add_special_tokens=__A )
     self.assertListEqual(__A						,				__A )

     # Testing conversion to ids with special tokens
     lowerCamelCase :					int    =				self.get_rust_tokenizer(add_prefix_space=__A )
     lowerCamelCase :					Dict    =				tokenizer.encode(__A						,				add_prefix_space=__A )
     lowerCamelCase :					Dict    =				rust_tokenizer.encode(__A )
     self.assertListEqual(__A						,				__A )

     # Testing the unknown token
     lowerCamelCase :					Any    =				tokens + [rust_tokenizer.unk_token]
     lowerCamelCase :					str    =				[14, 15, 10, 9, 3, 2, 15, 19]
     self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__A )						,				__A )






   def _snake_case    (		self						,				*__A						,				**__A ):






     """simple docstring"""





     pass






   def _snake_case    (		self						,				__A=15 ):






     """simple docstring"""





     for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
       with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
         lowerCamelCase :					str    =				self.rust_tokenizer_class.from_pretrained(__A						,				**__A )

         # Simple input
         lowerCamelCase :					Dict    =				"This is a simple input"
         lowerCamelCase :					List[Any]    =				["This is a simple input 1", "This is a simple input 2"]
         lowerCamelCase :					int    =				("This is a simple input", "This is a pair")
         lowerCamelCase :					Optional[int]    =				[
             ("This is a simple input 1", "This is a simple input 2"),
             ("This is a simple pair 1", "This is a simple pair 2"),
         ]

         # Simple input tests
         self.assertRaises(__A						,				tokenizer_r.encode						,				__A						,				max_length=__A						,				padding="max_length" )

         # Simple input
         self.assertRaises(__A						,				tokenizer_r.encode_plus						,				__A						,				max_length=__A						,				padding="max_length" )

         # Simple input
         self.assertRaises(
             __A						,				tokenizer_r.batch_encode_plus						,				__A						,				max_length=__A						,				padding="max_length"						,				)

         # Pair input
         self.assertRaises(__A						,				tokenizer_r.encode						,				__A						,				max_length=__A						,				padding="max_length" )

         # Pair input
         self.assertRaises(__A						,				tokenizer_r.encode_plus						,				__A						,				max_length=__A						,				padding="max_length" )

         # Pair input
         self.assertRaises(
             __A						,				tokenizer_r.batch_encode_plus						,				__A						,				max_length=__A						,				padding="max_length"						,				)






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				CodeGenTokenizer.from_pretrained(self.tmpdirname						,				pad_token="<pad>" )

     # Simple input
     lowerCamelCase :					Optional[int]    =				"This is a simple input"
     lowerCamelCase :					int    =				["This is a simple input looooooooong", "This is a simple input"]
     lowerCamelCase :					List[Any]    =				("This is a simple input", "This is a pair")
     lowerCamelCase :					Union[str, Any]    =				[
         ("This is a simple input loooooong", "This is a simple input"),
         ("This is a simple pair loooooong", "This is a simple pair"),
     ]

     lowerCamelCase :					Any    =				tokenizer.pad_token_id

     lowerCamelCase :					Any    =				tokenizer(__A						,				padding="max_length"						,				max_length=30						,				return_tensors="np" )
     lowerCamelCase :					Any    =				tokenizer(__A						,				padding=__A						,				truncate=__A						,				return_tensors="np" )
     lowerCamelCase :					List[str]    =				tokenizer(*__A						,				padding="max_length"						,				max_length=60						,				return_tensors="np" )
     lowerCamelCase :					Tuple    =				tokenizer(__A						,				padding=__A						,				truncate=__A						,				return_tensors="np" )

     # s
     # test single string max_length padding
     self.assertEqual(out_s["input_ids"].shape[-1]						,				30 )
     self.assertTrue(pad_token_id in out_s["input_ids"] )
     self.assertTrue(0 in out_s["attention_mask"] )

     # s2
     # test automatic padding
     self.assertEqual(out_sa["input_ids"].shape[-1]						,				33 )
     # long slice doesn't have padding
     self.assertFalse(pad_token_id in out_sa["input_ids"][0] )
     self.assertFalse(0 in out_sa["attention_mask"][0] )
     # short slice does have padding
     self.assertTrue(pad_token_id in out_sa["input_ids"][1] )
     self.assertTrue(0 in out_sa["attention_mask"][1] )

     # p
     # test single pair max_length padding
     self.assertEqual(out_p["input_ids"].shape[-1]						,				60 )
     self.assertTrue(pad_token_id in out_p["input_ids"] )
     self.assertTrue(0 in out_p["attention_mask"] )

     # p2
     # test automatic padding pair
     self.assertEqual(out_pa["input_ids"].shape[-1]						,				52 )
     # long slice pair doesn't have padding
     self.assertFalse(pad_token_id in out_pa["input_ids"][0] )
     self.assertFalse(0 in out_pa["attention_mask"][0] )
     # short slice pair does have padding
     self.assertTrue(pad_token_id in out_pa["input_ids"][1] )
     self.assertTrue(0 in out_pa["attention_mask"][1] )






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Dict    =				"$$$"
     lowerCamelCase :					int    =				CodeGenTokenizer.from_pretrained(self.tmpdirname						,				bos_token=__A						,				add_bos_token=__A )

     lowerCamelCase :					Any    =				"This is a simple input"
     lowerCamelCase :					int    =				["This is a simple input 1", "This is a simple input 2"]

     lowerCamelCase :					Dict    =				tokenizer.bos_token_id

     lowerCamelCase :					Tuple    =				tokenizer(__A )
     lowerCamelCase :					List[str]    =				tokenizer(__A )

     self.assertEqual(out_s.input_ids[0]						,				__A )
     self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) )

     lowerCamelCase :					int    =				tokenizer.decode(out_s.input_ids )
     lowerCamelCase :					List[Any]    =				tokenizer.batch_decode(out_sa.input_ids )

     self.assertEqual(decode_s.split()[0]						,				__A )
     self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) )






   @slow
   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Optional[int]    =				CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono" )

     lowerCamelCase :					str    =				"\nif len_a > len_b:\n    result = a\nelse:\n    result = b\n\n\n\n#"
     lowerCamelCase :					Union[str, Any]    =				"\nif len_a > len_b:      result = a\nelse:      result = b"

     lowerCamelCase :					Any    =				tokenizer.encode(__A )
     lowerCamelCase :					Union[str, Any]    =				["^#", re.escape("<|endoftext|>" ), "^'''", "^\"\"\"", "\n\n\n"]
     lowerCamelCase :					int    =				tokenizer.decode(__A						,				truncate_before_pattern=__A )
     self.assertEqual(__A						,				__A )






   def _snake_case    (		self ):






     """simple docstring"""





     pass







import gc
import unittest

import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    PriorTransformer,
    StableUnCLIPPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device

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,
    assert_mean_pixel_difference,
)


enable_full_determinism()
class 	UpperCAmelCase_					(					UpperCamelCase		, UpperCamelCase		, UpperCamelCase		, unittest.TestCase    ):

   '''simple docstring'''




   __A :      Tuple     		=		StableUnCLIPPipeline
   __A :      Optional[int]     		=		TEXT_TO_IMAGE_PARAMS
   __A :      str     		=		TEXT_TO_IMAGE_BATCH_PARAMS
   __A :      int     		=		TEXT_TO_IMAGE_IMAGE_PARAMS
   __A :      Tuple     		=		TEXT_TO_IMAGE_IMAGE_PARAMS

   # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
   __A :      Union[str, Any]     		=		False






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				32
     lowerCamelCase :					Dict    =				embedder_hidden_size

     # prior components

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				CLIPTextModelWithProjection(
         CLIPTextConfig(
             bos_token_id=0						,				eos_token_id=2						,				hidden_size=__A						,				projection_dim=__A						,				intermediate_size=37						,				layer_norm_eps=1e-05						,				num_attention_heads=4						,				num_hidden_layers=5						,				pad_token_id=1						,				vocab_size=1000						,				) )

     torch.manual_seed(0 )
     lowerCamelCase :					List[Any]    =				PriorTransformer(
         num_attention_heads=2						,				attention_head_dim=12						,				embedding_dim=__A						,				num_layers=1						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					Dict    =				DDPMScheduler(
         variance_type="fixed_small_log"						,				prediction_type="sample"						,				num_train_timesteps=1000						,				clip_sample=__A						,				clip_sample_range=5.0						,				beta_schedule="squaredcos_cap_v2"						,				)

     # regular denoising components

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				StableUnCLIPImageNormalizer(embedding_dim=__A )
     lowerCamelCase :					Tuple    =				DDPMScheduler(beta_schedule="squaredcos_cap_v2" )

     torch.manual_seed(0 )
     lowerCamelCase :					List[Any]    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

     torch.manual_seed(0 )
     lowerCamelCase :					str    =				CLIPTextModel(
         CLIPTextConfig(
             bos_token_id=0						,				eos_token_id=2						,				hidden_size=__A						,				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=1000						,				) )

     torch.manual_seed(0 )
     lowerCamelCase :					Any    =				UNetaDConditionModel(
         sample_size=32						,				in_channels=4						,				out_channels=4						,				down_block_types=("CrossAttnDownBlock2D", "DownBlock2D")						,				up_block_types=("UpBlock2D", "CrossAttnUpBlock2D")						,				block_out_channels=(32, 64)						,				attention_head_dim=(2, 4)						,				class_embed_type="projection"						,				projection_class_embeddings_input_dim=embedder_projection_dim * 2						,				cross_attention_dim=__A						,				layers_per_block=1						,				upcast_attention=__A						,				use_linear_projection=__A						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					int    =				DDIMScheduler(
         beta_schedule="scaled_linear"						,				beta_start=0.00085						,				beta_end=0.012						,				prediction_type="v_prediction"						,				set_alpha_to_one=__A						,				steps_offset=1						,				)

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

     lowerCamelCase :					Optional[int]    =				{
         # prior components
         "prior_tokenizer": prior_tokenizer,
         "prior_text_encoder": prior_text_encoder,
         "prior": prior,
         "prior_scheduler": prior_scheduler,
         # image noising components
         "image_normalizer": image_normalizer,
         "image_noising_scheduler": image_noising_scheduler,
         # regular denoising components
         "tokenizer": tokenizer,
         "text_encoder": text_encoder,
         "unet": unet,
         "scheduler": scheduler,
         "vae": vae,
     }

     return components






   def _snake_case    (		self						,				__A						,				__A=0 ):






     """simple docstring"""





     if str(__A ).startswith("mps" ):
       lowerCamelCase :					Optional[int]    =				torch.manual_seed(__A )
     else:
       lowerCamelCase :					Optional[Any]    =				torch.Generator(device=__A ).manual_seed(__A )
     lowerCamelCase :					Tuple    =				{
         "prompt": "A painting of a squirrel eating a burger",
         "generator": generator,
         "num_inference_steps": 2,
         "prior_num_inference_steps": 2,
         "output_type": "numpy",
     }
     return inputs






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Dict    =				torch_device == "cpu"

     self._test_attention_slicing_forward_pass(test_max_difference=__A )






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[Any]    =				torch_device in ["cpu", "mps"]

     self._test_inference_batch_single_identical(test_max_difference=__A )



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

   '''simple docstring'''




   def _snake_case    (		self ):






     """simple docstring"""





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






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Optional[Any]    =				load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" )

     lowerCamelCase :					str    =				StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"						,				torch_dtype=torch.floataa )
     pipe.to(__A )
     pipe.set_progress_bar_config(disable=__A )
     # 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()

     lowerCamelCase :					List[Any]    =				torch.Generator(device="cpu" ).manual_seed(0 )
     lowerCamelCase :					Dict    =				pipe("anime turle"						,				generator=__A						,				output_type="np" )

     lowerCamelCase :					Dict    =				output.images[0]

     assert image.shape == (768, 768, 3)

     assert_mean_pixel_difference(__A						,				__A )






   def _snake_case    (		self ):






     """simple docstring"""





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

     lowerCamelCase :					int    =				StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"						,				torch_dtype=torch.floataa )
     lowerCamelCase :					Union[str, Any]    =				pipe.to(__A )
     pipe.set_progress_bar_config(disable=__A )
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     lowerCamelCase :					Any    =				pipe(
         "anime turtle"						,				prior_num_inference_steps=2						,				num_inference_steps=2						,				output_type="np"						,				)

     lowerCamelCase :					List[str]    =				torch.cuda.max_memory_allocated()
     # make sure that less than 7 GB is allocated
     assert mem_bytes < 7 * 10**9



