


import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin



@skip_mps
class 	__lowerCamelCase			(_a				,      _a				,      unittest.TestCase						):
       _lowercase											=     IFImgaImgSuperResolutionPipeline
       _lowercase											=     TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""width""", """height"""}
       _lowercase											=     TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""original_image"""}						)
       _lowercase											=     PipelineTesterMixin.required_optional_params - {"""latents"""}







       def 		snake_case_	(			self: Any					):






            '''simple docstring'''




            return self._get_superresolution_dummy_components()







       def 		snake_case_	(			self: List[str],A_: int,A_: Union[str, Any]=0					):






            '''simple docstring'''




            if str(A_					).startswith('mps'					):
                 __UpperCamelCase =			torch.manual_seed(A_					)
            else:
                 __UpperCamelCase =			torch.Generator(device=A_					).manual_seed(A_					)

            __UpperCamelCase =			floats_tensor((1, 3, 32, 32),rng=random.Random(A_					)					).to(A_					)
            __UpperCamelCase =			floats_tensor((1, 3, 16, 16),rng=random.Random(A_					)					).to(A_					)

            __UpperCamelCase =			{
                'prompt': 'A painting of a squirrel eating a burger',
                'image': image,
                'original_image': original_image,
                'generator': generator,
                'num_inference_steps': 2,
                'output_type': 'numpy',
            }

            return inputs







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






            '''simple docstring'''




            self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3					)







       def 		snake_case_	(			self: Optional[int]					):






            '''simple docstring'''




            self._test_save_load_optional_components()







       @unittest.skipIf(torch_device != 'cuda',reason='float16 requires CUDA'					)
       def 		snake_case_	(			self: str					):






            '''simple docstring'''




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







       def 		snake_case_	(			self: Any					):






            '''simple docstring'''




            self._test_attention_slicing_forward_pass(expected_max_diff=1E-2					)







       def 		snake_case_	(			self: int					):






            '''simple docstring'''




            self._test_save_load_local()







       def 		snake_case_	(			self: Union[str, Any]					):






            '''simple docstring'''




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





from typing import Dict, List, Optional

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


_lowerCamelCase      :					Any					    =      logging.get_logger(__name__)


_lowerCamelCase      :					Tuple					    =      {
    '''nielsr/canine-s''': 2048,
}

# Unicode defines 1,114,112 total “codepoints”
_lowerCamelCase      :					List[str]					    =      111_4112

# Below: Constants defining canonical codepoints for special, pseudo-characters.
# Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py
_lowerCamelCase      :					List[str]					    =      0

_lowerCamelCase      :					Any					    =      0xe_0_0_0
_lowerCamelCase      :					Union[str, Any]					    =      0xe_0_0_1
_lowerCamelCase      :					Any					    =      0xe_0_0_2
_lowerCamelCase      :					List[str]					    =      0xe_0_0_3
_lowerCamelCase      :					Any					    =      0xe_0_0_4

# Maps special codepoints to human-readable names.
_lowerCamelCase      :					Dict[int, str]					    =      {
    # Special symbols are represented using codepoints values that are valid,
    # but designated as "Private Use", meaning that they will never be assigned
    # characters by the Unicode Consortium, and are thus safe for use here.
    #
    # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly
    # excluded and should fail with a hard error.
    CLS: "[CLS]",
    SEP: "[SEP]",
    BOS: "[BOS]",
    MASK: "[MASK]",
    PAD: "[PAD]",
    RESERVED: "[RESERVED]",
}

# Maps special codepoint human-readable names to their codepoint values.
_lowerCamelCase      :					Dict[str, int]					    =      {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()}





class        lowerCAmelCase__  (					__magic_name__			):



       '''simple docstring'''







       lowercase_						=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES

       def __init__(							self ,   lowercase__=chr(lowercase__     ) ,   lowercase__=chr(lowercase__     ) ,   lowercase__=chr(lowercase__     ) ,   lowercase__=chr(lowercase__     ) ,   lowercase__=chr(lowercase__     ) ,   lowercase__=chr(lowercase__     ) ,   lowercase__=False ,   lowercase__=2_0_4_8 ,   **lowercase__ ,   ):







             '''simple docstring'''



             __A    =AddedToken(lowercase__ ,   lstrip=lowercase__ ,   rstrip=lowercase__     ) if isinstance(lowercase__ ,   lowercase__     ) else bos_token
             __A    =AddedToken(lowercase__ ,   lstrip=lowercase__ ,   rstrip=lowercase__     ) if isinstance(lowercase__ ,   lowercase__     ) else eos_token
             __A    =AddedToken(lowercase__ ,   lstrip=lowercase__ ,   rstrip=lowercase__     ) if isinstance(lowercase__ ,   lowercase__     ) else sep_token
             __A    =AddedToken(lowercase__ ,   lstrip=lowercase__ ,   rstrip=lowercase__     ) if isinstance(lowercase__ ,   lowercase__     ) else cls_token
             __A    =AddedToken(lowercase__ ,   lstrip=lowercase__ ,   rstrip=lowercase__     ) if isinstance(lowercase__ ,   lowercase__     ) else pad_token

             # Mask token behave like a normal word, i.e. include the space before it
             __A    =AddedToken(lowercase__ ,   lstrip=lowercase__ ,   rstrip=lowercase__     ) if isinstance(lowercase__ ,   lowercase__     ) else mask_token

             super().__init__(
                 bos_token=lowercase__ ,   eos_token=lowercase__ ,   sep_token=lowercase__ ,   cls_token=lowercase__ ,   pad_token=lowercase__ ,   mask_token=lowercase__ ,   add_prefix_space=lowercase__ ,   model_max_length=lowercase__ ,   **lowercase__ ,   )

             # Creates a mapping for looking up the IDs of special symbols.
             __A    ={}
             for codepoint, name in SPECIAL_CODEPOINTS.items():
                   __A    =codepoint

             # Creates a mapping for looking up the string forms of special symbol IDs.
             __A    ={
                 codepoint: name for name, codepoint in self._special_codepoints.items()
             }

             __A    =UNICODE_VOCAB_SIZE
             __A    =len(self._special_codepoints     )

       @property
       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             return self._unicode_vocab_size

       def     __UpperCamelCase     (							self ,   lowercase__     ):







             '''simple docstring'''



             return list(lowercase__     )

       def     __UpperCamelCase     (							self ,   lowercase__     ):







             '''simple docstring'''



             try:
                   return ord(lowercase__     )
             except TypeError:
                   raise ValueError(f'''invalid token: \'{token}\''''     )

       def     __UpperCamelCase     (							self ,   lowercase__     ):







             '''simple docstring'''



             try:
                   if index in SPECIAL_CODEPOINTS:
                         return SPECIAL_CODEPOINTS[index]
                   return chr(lowercase__     )
             except TypeError:
                   raise ValueError(f'''invalid id: {index}'''     )

       def     __UpperCamelCase     (							self ,   lowercase__     ):







             '''simple docstring'''



             return "".join(lowercase__     )

       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__ = None     ):







             '''simple docstring'''



             __A    =[self.sep_token_id]
             __A    =[self.cls_token_id]

             __A    =cls + token_ids_a + sep
             if token_ids_a is not None:
                   result += token_ids_a + sep
             return result

       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__ = None ,   lowercase__ = False     ):







             '''simple docstring'''



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

             __A    =[1] + ([0] * len(lowercase__     )) + [1]
             if token_ids_a is not None:
                   result += ([0] * len(lowercase__     )) + [1]
             return result

       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__ = None     ):







             '''simple docstring'''



             __A    =[self.sep_token_id]
             __A    =[self.cls_token_id]

             __A    =len(cls + token_ids_a + sep     ) * [0]
             if token_ids_a is not None:
                   result += len(token_ids_a + sep     ) * [1]
             return result


       def     __UpperCamelCase     (							self ,   lowercase__ ,   lowercase__ = None     ):







             '''simple docstring'''



             return ()


