




'''simple docstring'''





import collections
import os
from typing import List, Optional, Tuple

from transformers.utils import is_jieba_available, requires_backends


if is_jieba_available():
		import jieba

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_SCREAMING_SNAKE_CASE							:       Union[str, Any]						=			logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE							:       Dict						=			{"vocab_file": "vocab.txt"}

_SCREAMING_SNAKE_CASE							:       Tuple						=			{
    "vocab_file": {
        "openbmb/cpm-ant-10b": "https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt",
    },
}

_SCREAMING_SNAKE_CASE							:       Union[str, Any]						=			{
    "openbmb/cpm-ant-10b": 1024,
}


def 					UpperCamelCase_(     snake_case							:	Optional[int]					):

							'''simple docstring'''






							snake_case_      =				collections.OrderedDict()
							with open(snake_case							,    "r"							,    encoding="utf-8"					) as reader:
														snake_case_      =				reader.readlines()
							for index, token in enumerate(snake_case					):
														snake_case_      =				token.rstrip("\n"					)
														snake_case_      =				index
							return vocab




class 			_snake_case		(     lowercase_							):




			def __init__( self    ,							a__    ,							a__="<unk>"    ,							a__=200							)    ->    List[Any]:

										'''simple docstring'''




										snake_case_      =				vocab
										snake_case_      =				unk_token
										snake_case_      =				max_input_chars_per_word




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    str:

										'''simple docstring'''




										snake_case_      =				list(a__							)
										if len(a__							) > self.max_input_chars_per_word:
																	return [self.unk_token]

										snake_case_      =				0
										snake_case_      =				[]
										while start < len(a__							):
																	snake_case_      =				len(a__							)
																	snake_case_      =				None
																	while start < end:
																								snake_case_      =				"".join(chars[start:end]							)
																								if substr in self.vocab:
																															snake_case_      =				substr
																															break
																								end -= 1
																	if cur_substr is None:
																								sub_tokens.append(self.unk_token							)
																								start += 1
																	else:
																								sub_tokens.append(a__							)
																								snake_case_      =				end

										return sub_tokens




class 			_snake_case		(     lowercase_							):
			lowerCAmelCase_					:				Dict							=   VOCAB_FILES_NAMES
			lowerCAmelCase_					:				Dict							=   PRETRAINED_VOCAB_FILES_MAP
			lowerCAmelCase_					:				Dict							=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			lowerCAmelCase_					:				Tuple							=   ["input_ids", "attention_mask"]
			lowerCAmelCase_					:				List[str]							=   False




			def __init__( self    ,							a__    ,							a__="<d>"    ,							a__="</d>"    ,							a__="<s>"    ,							a__="</s>"    ,							a__="<pad>"    ,							a__="<unk>"    ,							a__="</n>"    ,							a__="</_>"    ,							a__="left"    ,							**a__    ,							)    ->    Optional[int]:

										'''simple docstring'''




										requires_backends(self    ,							["jieba"]							)
										super().__init__(
										    bod_token=a__    ,							eod_token=a__    ,							bos_token=a__    ,							eos_token=a__    ,							pad_token=a__    ,							unk_token=a__    ,							line_token=a__    ,							space_token=a__    ,							padding_side=a__    ,							**a__    ,							)
										snake_case_      =				bod_token
										snake_case_      =				eod_token
										snake_case_      =				load_vocab(a__							)
										snake_case_      =				self.encoder[space_token]
										snake_case_      =				self.encoder[line_token]

										del self.encoder[space_token]
										del self.encoder[line_token]

										snake_case_      =				collections.OrderedDict(sorted(self.encoder.items()    ,							key=lambda a__							: x[1]							)							)
										snake_case_      =				{v: k for k, v in self.encoder.items()}

										snake_case_      =				WordpieceTokenizer(vocab=self.encoder    ,							unk_token=self.unk_token							)




			@property
			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										return self.encoder[self.bod_token]




			@property
			def        lowerCAmelCase__    ( self							)    ->    Any:

										'''simple docstring'''




										return self.encoder[self.eod_token]




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

										'''simple docstring'''




										return self.encoder["\n"]




			@property
			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										return len(self.encoder							)




			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




										return dict(self.encoder    ,							**self.added_tokens_encoder							)




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    Tuple:

										'''simple docstring'''




										snake_case_      =				[]
										for x in jieba.cut(a__    ,							cut_all=a__							):
																	output_tokens.extend(self.wordpiece_tokenizer.tokenize(a__							)							)
										return output_tokens




			def        lowerCAmelCase__    ( self    ,							a__    ,							**a__							)    ->    str:

										'''simple docstring'''




										snake_case_      =				[i for i in token_ids if i >= 0]
										snake_case_      =				[
										    x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
										]
										return super()._decode(a__    ,							**a__							)




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    Optional[int]:

										'''simple docstring'''




										return token in self.encoder




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    str:

										'''simple docstring'''




										return "".join(a__							)




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    Optional[int]:

										'''simple docstring'''




										return self.encoder.get(a__    ,							self.encoder.get(self.unk_token							)							)




			def        lowerCAmelCase__    ( self    ,							a__							)    ->    Optional[int]:

										'''simple docstring'''




										return self.decoder.get(a__    ,							self.unk_token							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__ = None							)    ->    Tuple[str]:

										'''simple docstring'''




										if os.path.isdir(a__							):
																	snake_case_      =				os.path.join(
																	    a__    ,							(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]							)
										else:
																	snake_case_      =				(filename_prefix + "-" if filename_prefix else "") + save_directory
										snake_case_      =				0
										if " " in self.encoder:
																	snake_case_      =				self.encoder[" "]
																	del self.encoder[" "]
										if "\n" in self.encoder:
																	snake_case_      =				self.encoder["\n"]
																	del self.encoder["\n"]
										snake_case_      =				collections.OrderedDict(sorted(self.encoder.items()    ,							key=lambda a__							: x[1]							)							)
										with open(a__    ,							"w"    ,							encoding="utf-8"							) as writer:
																	for token, token_index in self.encoder.items():
																								if index != token_index:
																															logger.warning(
																															    F'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'
																															    " Please check that the vocabulary is not corrupted!"							)
																															snake_case_      =				token_index
																								writer.write(token + "\n"							)
																								index += 1
										return (vocab_file,)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__ = None							)    ->    List[int]:

										'''simple docstring'''




										if token_ids_a is None:
																	return [self.bos_token_id] + token_ids_a
										return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__ = None    ,							a__ = False							)    ->    List[int]:

										'''simple docstring'''




										if already_has_special_tokens:
																	return super().get_special_tokens_mask(
																	    token_ids_a=a__    ,							token_ids_a=a__    ,							already_has_special_tokens=a__							)

										if token_ids_a is not None:
																	return [1] + ([0] * len(a__							)) + [1] + ([0] * len(a__							))
										return [1] + ([0] * len(a__							))










'''simple docstring'''





import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin




@skip_mps
class 			_snake_case		(     lowercase_						,						lowercase_						,						unittest.TestCase							):
			lowerCAmelCase_					:				List[str]							=   IFPipeline
			lowerCAmelCase_					:				int							=   TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
			lowerCAmelCase_					:				Optional[int]							=   TEXT_TO_IMAGE_BATCH_PARAMS
			lowerCAmelCase_					:				List[Any]							=   PipelineTesterMixin.required_optional_params - {"latents"}




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

										'''simple docstring'''




										return self._get_dummy_components()




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__=0							)    ->    str:

										'''simple docstring'''




										if str(a__							).startswith("mps"							):
																	snake_case_      =				torch.manual_seed(a__							)
										else:
																	snake_case_      =				torch.Generator(device=a__							).manual_seed(a__							)

										snake_case_      =				{
										    "prompt": "A painting of a squirrel eating a burger",
										    "generator": generator,
										    "num_inference_steps": 2,
										    "output_type": "numpy",
										}

										return inputs




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

										'''simple docstring'''




										self._test_save_load_optional_components()




			@unittest.skipIf(torch_device != "cuda"    ,							reason="float16 requires CUDA"							)
			def        lowerCAmelCase__    ( self							)    ->    str:

										'''simple docstring'''




										super().test_save_load_floataa(expected_max_diff=1e-1							)




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

										'''simple docstring'''




										self._test_attention_slicing_forward_pass(expected_max_diff=1e-2							)




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										self._test_save_load_local()




			def        lowerCAmelCase__    ( self							)    ->    int:

										'''simple docstring'''




										self._test_inference_batch_single_identical(
										    expected_max_diff=1e-2    ,							)




			@unittest.skipIf(
			    torch_device != "cuda" or not is_xformers_available()    ,							reason="XFormers attention is only available with CUDA and `xformers` installed"    ,							)
			def        lowerCAmelCase__    ( self							)    ->    List[str]:

										'''simple docstring'''




										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3							)




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




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

										'''simple docstring'''




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




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

										'''simple docstring'''




										snake_case_      =				IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0"    ,							variant="fp16"    ,							torch_dtype=torch.floataa							)

										snake_case_      =				IFSuperResolutionPipeline.from_pretrained(
										    "DeepFloyd/IF-II-L-v1.0"    ,							variant="fp16"    ,							torch_dtype=torch.floataa    ,							text_encoder=a__    ,							tokenizer=a__							)

										# pre compute text embeddings and remove T5 to save memory

										pipe_a.text_encoder.to("cuda"							)

										snake_case_ ,				snake_case_      =				pipe_a.encode_prompt("anime turtle"    ,							device="cuda"							)

										del pipe_a.tokenizer
										del pipe_a.text_encoder
										gc.collect()

										snake_case_      =				None
										snake_case_      =				None

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if(a__    ,							a__    ,							a__    ,							a__							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# img2img

										snake_case_      =				IFImgaImgPipeline(**pipe_a.components							)
										snake_case_      =				IFImgaImgSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_imgaimg(a__    ,							a__    ,							a__    ,							a__							)

										pipe_a.remove_all_hooks()
										pipe_a.remove_all_hooks()

										# inpainting

										snake_case_      =				IFInpaintingPipeline(**pipe_a.components							)
										snake_case_      =				IFInpaintingSuperResolutionPipeline(**pipe_a.components							)

										pipe_a.enable_model_cpu_offload()
										pipe_a.enable_model_cpu_offload()

										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)
										pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()							)

										self._test_if_inpainting(a__    ,							a__    ,							a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)
										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 13 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    Dict:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 10 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							original_image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)




			def        lowerCAmelCase__    ( self    ,							a__    ,							a__    ,							a__    ,							a__							)    ->    str:

										'''simple docstring'''




										_start_torch_memory_measurement()

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(1							)							).to(a__							)

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)
										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							mask_image=a__    ,							num_inference_steps=2    ,							generator=a__    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 10 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)

										# pipeline 2

										_start_torch_memory_measurement()

										snake_case_      =				torch.Generator(device="cpu"							).manual_seed(0							)

										snake_case_      =				floats_tensor((1, 3, 64, 64)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(0							)							).to(a__							)
										snake_case_      =				floats_tensor((1, 3, 256, 256)    ,							rng=random.Random(1							)							).to(a__							)

										snake_case_      =				pipe_a(
										    prompt_embeds=a__    ,							negative_prompt_embeds=a__    ,							image=a__    ,							mask_image=a__    ,							original_image=a__    ,							generator=a__    ,							num_inference_steps=2    ,							output_type="np"    ,							)

										snake_case_      =				output.images[0]

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

										snake_case_      =				torch.cuda.max_memory_allocated()
										assert mem_bytes < 4 * 10**9

										snake_case_      =				load_numpy(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy"							)
										assert_mean_pixel_difference(a__    ,							a__							)


def 					UpperCamelCase_(     ):

							'''simple docstring'''






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




