


import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
				if is_torch_available():
								import torch
				if is_tf_available():
								import tensorflow as tf

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer


lowerCAmelCase       		=    logging.get_logger(__name__)

lowerCAmelCase       		=    {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

lowerCAmelCase       		=    {
    """vocab_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """Salesforce/codegen-350M-mono""": (
            """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json"""
        ),
    },
}

lowerCAmelCase       		=    {
    """Salesforce/codegen-350M-mono""": 2_048,
}




class 							lowerCamelCase   (  _UpperCamelCase ):
	_lowerCAmelCase     :		Dict										=						VOCAB_FILES_NAMES
	_lowerCAmelCase     :		Optional[Any]										=						PRETRAINED_VOCAB_FILES_MAP
	_lowerCAmelCase     :		List[str]										=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_lowerCAmelCase     :		List[Any]										=						['''input_ids''', '''attention_mask''']
	_lowerCAmelCase     :		Optional[Any]										=						CodeGenTokenizer


	def __init__(    self				,     lowercase__=None				,     lowercase__=None				,     lowercase__=None				,     lowercase__="<|endoftext|>"				,     lowercase__="<|endoftext|>"				,     lowercase__="<|endoftext|>"				,     lowercase__=False				,     **lowercase__				,     ):
							super().__init__(
							    lowercase__				,     lowercase__				,     tokenizer_file=lowercase__				,     unk_token=lowercase__				,     bos_token=lowercase__				,     eos_token=lowercase__				,     add_prefix_space=lowercase__				,     **lowercase__				,     )

							if kwargs.pop('''add_bos_token'''				,     lowercase__):
													__UpperCAmelCase			:							str	    =	kwargs.pop('''name_or_path'''				,     '''''')
													raise ValueError(
													    '''Currenty GPT2\'s fast tokenizer does NOT support adding a BOS token.'''
													    '''Instead you should use GPT2\'s slow tokenizer class `CodeGenTokenizer` as follows: \n'''
													    F"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n"
													    F"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n"
													    '''This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.'''
													    ''' so that the fast tokenizer works correctly.''')

							__UpperCAmelCase			:							Dict	    =	json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
							if pre_tok_state.get('''add_prefix_space'''				,     lowercase__) != add_prefix_space:
													__UpperCAmelCase			:							Optional[Any]	    =	getattr(lowercase__				,     pre_tok_state.pop('''type'''))
													__UpperCAmelCase			:							List[str]	    =	add_prefix_space
													__UpperCAmelCase			:							int	    =	pre_tok_class(**lowercase__)

							__UpperCAmelCase			:							Union[str, Any]	    =	add_prefix_space


	def  A(    self				,     *lowercase__				,     **lowercase__):
							__UpperCAmelCase			:							Tuple	    =	kwargs.get('''is_split_into_words'''				,     lowercase__)
							assert self.add_prefix_space or not is_split_into_words, (
							    F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
							    "to use it with pretokenized inputs."
							)

							return super()._batch_encode_plus(*lowercase__				,     **lowercase__)


	def  A(    self				,     *lowercase__				,     **lowercase__):
							__UpperCAmelCase			:							List[Any]	    =	kwargs.get('''is_split_into_words'''				,     lowercase__)

							assert self.add_prefix_space or not is_split_into_words, (
							    F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
							    "to use it with pretokenized inputs."
							)

							return super()._encode_plus(*lowercase__				,     **lowercase__)


	def  A(    self				,     lowercase__				,     lowercase__ = None):
							__UpperCAmelCase			:							Any	    =	self._tokenizer.model.save(lowercase__				,     name=lowercase__)
							return tuple(lowercase__)


	def  A(    self				,     lowercase__				,     lowercase__ = False				,     lowercase__ = None				,     lowercase__ = None				,     **lowercase__				,     ):
							__UpperCAmelCase			:							Optional[Any]	    =	super().decode(
							    token_ids=lowercase__				,     skip_special_tokens=lowercase__				,     clean_up_tokenization_spaces=lowercase__				,     **lowercase__				,     )

							if truncate_before_pattern is not None and len(lowercase__) > 0:
													__UpperCAmelCase			:							List[Any]	    =	self.truncate(lowercase__				,     lowercase__)

							return decoded_text


	def  A(    self				,     lowercase__				,     lowercase__):
							def find_re(lowercase__				,     lowercase__				,     lowercase__):
													__UpperCAmelCase			:							Optional[Any]	    =	pattern.search(lowercase__				,     lowercase__)
													return m.start() if m else -1

							__UpperCAmelCase			:							Optional[int]	    =	[re.compile(lowercase__				,     re.MULTILINE) for pattern in truncate_before_pattern]

							__UpperCAmelCase			:							Optional[int]	    =	list(re.finditer('''^print'''				,     lowercase__				,     re.MULTILINE))

							if len(lowercase__) > 1:
													__UpperCAmelCase			:							str	    =	completion[: prints[1].start()]

							__UpperCAmelCase			:							Optional[int]	    =	list(re.finditer('''^def'''				,     lowercase__				,     re.MULTILINE))

							if len(lowercase__) > 1:
													__UpperCAmelCase			:							int	    =	completion[: defs[1].start()]

							__UpperCAmelCase			:							int	    =	0

							__UpperCAmelCase			:							Optional[int]	    =	[
							    pos for pos in [find_re(lowercase__				,     lowercase__				,     lowercase__) for terminal in terminals] if pos != -1
							]

							if len(lowercase__) > 0:
													return completion[: min(lowercase__)]
							else:
													return completion





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

