


import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import is_torch_available, logging


if is_torch_available():
   import torch


if TYPE_CHECKING:
   from transformers.pipelines.conversational import Conversation


_snake_case             =     logging.get_logger(__name__)
_snake_case             =     {'''vocab_file''': '''spiece.model'''}

_snake_case             =     {
    '''vocab_file''': {
        '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''',
    }
}

_snake_case             =     {
    '''AI-Sweden/gpt-sw3-126m''': 20_48,
    '''AI-Sweden/gpt-sw3-350m''': 20_48,
    '''AI-Sweden/gpt-sw3-1.6b''': 20_48,
    '''AI-Sweden/gpt-sw3-6.7b''': 20_48,
    '''AI-Sweden/gpt-sw3-20b''': 20_48,
}
class 	UpperCAmelCase_					(					UpperCamelCase    ):

   '''simple docstring'''




   __A :      Optional[Any]     		=		VOCAB_FILES_NAMES
   __A :      Tuple     		=		PRETRAINED_VOCAB_FILES_MAP
   __A :      int     		=		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __A :      List[str]     		=		["input_ids", "attention_mask"]






   def __init__(		self						,				__A						,				__A=False						,				__A=False						,				__A=False						,				__A=None						,				__A=None						,				__A=None						,				__A=None						,				__A = None						,				**__A						,				):






     """simple docstring"""





     lowerCamelCase :					Any    =				{} if sp_model_kwargs is None else sp_model_kwargs

     lowerCamelCase :					Union[str, Any]    =				kwargs.get("name_or_path" )
     if name_or_path is None:
       logger.warning(
           "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,"
           " you are testing the model, this can safely be ignored" )
       lowerCamelCase :					List[Any]    =				"None"

     # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
     lowerCamelCase :					int    =				"<|endoftext|>" if eos_token is None else eos_token
     lowerCamelCase :					Tuple    =				"<unk>" if unk_token is None else unk_token
     if "gpt-sw3-7b" in name_or_path:
       lowerCamelCase :					Any    =				unk_token if pad_token is None else pad_token
       lowerCamelCase :					List[str]    =				eos_token if bos_token is None else bos_token
     else:
       lowerCamelCase :					List[str]    =				"<pad>" if pad_token is None else pad_token
       lowerCamelCase :					List[str]    =				"<s>" if bos_token is None else bos_token

     super().__init__(
         do_lower_case=__A						,				remove_space=__A						,				keep_accents=__A						,				bos_token=__A						,				eos_token=__A						,				unk_token=__A						,				pad_token=__A						,				sp_model_kwargs=self.sp_model_kwargs						,				**__A						,				)

     lowerCamelCase :					Dict    =				do_lower_case
     lowerCamelCase :					str    =				remove_space
     lowerCamelCase :					Union[str, Any]    =				keep_accents
     lowerCamelCase :					Optional[int]    =				vocab_file

     lowerCamelCase :					int    =				spm.SentencePieceProcessor(**self.sp_model_kwargs )
     self.sp_model.Load(__A )

     # Used for whitespace normalization in input texts
     # fmt : off
     lowerCamelCase :					List[Any]    =				{" ", " ", " ", " ", " ", "　", " ", " ", " ", " ", "￼", ""}
     # fmt : on

     # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
     lowerCamelCase :					List[str]    =				re.compile(
         F"""[{''.join(map(__A						,				list(range(0						,				9 ) ) + list(range(11						,				32 ) ) + list(range(127						,				160 ) ) + [160, 173, 8203] ) )}]""" )






   def __getstate__(		self ):






     """simple docstring"""





     lowerCamelCase :					List[Any]    =				self.__dict__.copy()
     lowerCamelCase :					Tuple    =				None
     return state






   def __setstate__(		self						,				__A ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				d

     # for backward compatibility
     if not hasattr(self						,				"sp_model_kwargs" ):
       lowerCamelCase :					Union[str, Any]    =				{}

     lowerCamelCase :					Any    =				spm.SentencePieceProcessor(**self.sp_model_kwargs )
     self.sp_model.Load(self.vocab_file )






   @property
   # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
   def _snake_case    (		self ):






     """simple docstring"""





     return len(self.sp_model )






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     lowerCamelCase :					Dict    =				self.non_printing_characters_re.sub(""						,				__A )

     # Normalize whitespaces
     lowerCamelCase :					int    =				"".join([char if char not in self.whitespaces else " " for char in text] )

     # NFC Unicode normalization
     lowerCamelCase :					Optional[int]    =				unicodedata.normalize("NFC"						,				__A )
     return text






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






     """simple docstring"""





     lowerCamelCase :					List[str]    =				self.preprocess_text(__A )
     return self.sp_model.encode(__A						,				out_type=__A )






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     return self.sp_model.PieceToId(__A )






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     return self.sp_model.IdToPiece(__A )






   @staticmethod
   def _snake_case    (		__A ):






     """simple docstring"""





     return out_string






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     lowerCamelCase :					Optional[int]    =				[]
     lowerCamelCase :					List[Any]    =				""
     lowerCamelCase :					List[str]    =				False
     for token in tokens:
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
         # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
         if not prev_is_special:
           out_string += " "

         out_string += self.sp_model.decode(__A ) + token
         lowerCamelCase :					Any    =				True
         lowerCamelCase :					Optional[Any]    =				[]
       else:
         current_sub_tokens.append(__A )
         lowerCamelCase :					List[str]    =				False
     out_string += self.sp_model.decode(__A )

     return out_string






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Any    =				{self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )}
     vocab.update(self.added_tokens_encoder )
     return vocab






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






     """simple docstring"""





     if not os.path.isdir(__A ):
       logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
       return
     lowerCamelCase :					Union[str, Any]    =				os.path.join(
         __A						,				(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )

     if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ):
       copyfile(self.vocab_file						,				__A )
     elif not os.path.isfile(self.vocab_file ):
       with open(__A						,				"wb" ) as fi:
         lowerCamelCase :					Optional[int]    =				self.sp_model.serialized_model_proto()
         fi.write(__A )

     return (out_vocab_file,)






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






     """simple docstring"""





     if isinstance(__A						,				__A ):
       lowerCamelCase :					Optional[int]    =				self.preprocess_text(__A )
       lowerCamelCase :					Union[str, Any]    =				self.sp_model.encode(__A )
     else:
       lowerCamelCase :					Optional[int]    =				[self.preprocess_text(__A ) for t in text]
       lowerCamelCase :					Optional[int]    =				self.sp_model.encode(__A )

     if return_tensors is True or return_tensors == "pt":
       lowerCamelCase :					Optional[Any]    =				torch.tensor(__A )

     return token_ids






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     return self.sp_model.decode(__A )






   def _snake_case    (		self						,				__A ):






     """simple docstring"""





     lowerCamelCase :					int    =				[F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()]
     lowerCamelCase :					List[Any]    =				(
         F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(__A ) + F"""{self.bos_token}Bot:"""
     )
     return self.encode(text=__A )







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



