





"""simple docstring"""



import itertools
import json
import os
import unittest

from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 		__snake_case					(		SCREAMING_SNAKE_CASE__							,							unittest.TestCase     ):





 """simple docstring"""


 _lowerCamelCase        =     RobertaTokenizer
 _lowerCamelCase        =     RobertaTokenizerFast
 _lowerCamelCase        =     True
 _lowerCamelCase        =     {"""cls_token""": """<s>"""}

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     super().setUp()

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

     __A    :						Optional[int]						 =     os.path.join(self.tmpdirname					,						VOCAB_FILES_NAMES['''vocab_file''']  )
     __A    :						Optional[int]						 =     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(__lowerCamelCase  ) + '''\n'''  )
     with open(self.merges_file					,						'''w'''					,						encoding='''utf-8'''  ) as fp:
         fp.write('''\n'''.join(__lowerCamelCase  )  )

 def 					UpperCamelCase__(    self					,						**__lowerCamelCase  ):



     '''simple docstring'''




     kwargs.update(self.special_tokens_map  )
     return self.tokenizer_class.from_pretrained(self.tmpdirname					,						**__lowerCamelCase  )

 def 					UpperCamelCase__(    self					,						**__lowerCamelCase  ):



     '''simple docstring'''




     kwargs.update(self.special_tokens_map  )
     return RobertaTokenizerFast.from_pretrained(self.tmpdirname					,						**__lowerCamelCase  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						int						 =     '''lower newer'''
     __A    :						str						 =     '''lower newer'''
     return input_text, output_text

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     self.tokenizer_class(self.vocab_file					,						self.merges_file					,						**self.special_tokens_map  )
     __A    :						Optional[Any]						 =     '''lower newer'''
     __A    :						Union[str, Any]						 =     ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er''']
     __A    :						str						 =     tokenizer.tokenize(__lowerCamelCase  )  # , add_prefix_space=True)
     self.assertListEqual(__lowerCamelCase					,						__lowerCamelCase  )

     __A    :						List[Any]						 =     tokens + [tokenizer.unk_token]
     __A    :						Tuple						 =     [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
     self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase  )					,						__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     self.get_tokenizer()

     self.assertListEqual(tokenizer.encode('''Hello world!'''					,						add_special_tokens=__lowerCamelCase  )					,						[0, 3_1414, 232, 328, 2]  )
     self.assertListEqual(
         tokenizer.encode('''Hello world! cécé herlolip 418'''					,						add_special_tokens=__lowerCamelCase  )					,						[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]					,						)

 @slow
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     self.tokenizer_class.from_pretrained('''roberta-base'''  )

     __A    :						Any						 =     tokenizer.encode('''sequence builders'''					,						add_special_tokens=__lowerCamelCase  )
     __A    :						int						 =     tokenizer.encode('''multi-sequence build'''					,						add_special_tokens=__lowerCamelCase  )

     __A    :						str						 =     tokenizer.encode(
         '''sequence builders'''					,						add_special_tokens=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase  )
     __A    :						List[Any]						 =     tokenizer.encode(
         '''sequence builders'''					,						'''multi-sequence build'''					,						add_special_tokens=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase  )

     __A    :						Dict						 =     tokenizer.build_inputs_with_special_tokens(__lowerCamelCase  )
     __A    :						Tuple						 =     tokenizer.build_inputs_with_special_tokens(__lowerCamelCase					,						__lowerCamelCase  )

     assert encoded_sentence == encoded_text_from_decode
     assert encoded_pair == encoded_pair_from_decode

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[str]						 =     self.get_tokenizer()

     __A    :						Optional[int]						 =     '''Encode this sequence.'''
     __A    :						List[Any]						 =     tokenizer.byte_encoder[''' '''.encode('''utf-8'''  )[0]]

     # Testing encoder arguments
     __A    :						Tuple						 =     tokenizer.encode(__lowerCamelCase					,						add_special_tokens=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase  )
     __A    :						int						 =     tokenizer.convert_ids_to_tokens(encoded[0]  )[0]
     self.assertNotEqual(__lowerCamelCase					,						__lowerCamelCase  )

     __A    :						Optional[int]						 =     tokenizer.encode(__lowerCamelCase					,						add_special_tokens=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase  )
     __A    :						Dict						 =     tokenizer.convert_ids_to_tokens(encoded[0]  )[0]
     self.assertEqual(__lowerCamelCase					,						__lowerCamelCase  )

     tokenizer.add_special_tokens({'''bos_token''': '''<s>'''}  )
     __A    :						List[str]						 =     tokenizer.encode(__lowerCamelCase					,						add_special_tokens=__lowerCamelCase  )
     __A    :						str						 =     tokenizer.convert_ids_to_tokens(encoded[1]  )[0]
     self.assertNotEqual(__lowerCamelCase					,						__lowerCamelCase  )

     # Testing spaces after special tokens
     __A    :						Dict						 =     '''<mask>'''
     tokenizer.add_special_tokens(
         {'''mask_token''': AddedToken(__lowerCamelCase					,						lstrip=__lowerCamelCase					,						rstrip=__lowerCamelCase  )}  )  # mask token has a left space
     __A    :						Any						 =     tokenizer.convert_tokens_to_ids(__lowerCamelCase  )

     __A    :						Optional[int]						 =     '''Encode <mask> sequence'''
     __A    :						int						 =     '''Encode <mask>sequence'''

     __A    :						Tuple						 =     tokenizer.encode(__lowerCamelCase  )
     __A    :						str						 =     encoded.index(__lowerCamelCase  )
     __A    :						Any						 =     tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1]  )[0]
     self.assertEqual(__lowerCamelCase					,						__lowerCamelCase  )

     __A    :						Union[str, Any]						 =     tokenizer.encode(__lowerCamelCase  )
     __A    :						Union[str, Any]						 =     encoded.index(__lowerCamelCase  )
     __A    :						Any						 =     tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1]  )[0]
     self.assertNotEqual(__lowerCamelCase					,						__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     pass

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""  ):
             __A    :						Optional[int]						 =     self.rust_tokenizer_class.from_pretrained(__lowerCamelCase					,						**__lowerCamelCase  )
             __A    :						List[Any]						 =     self.tokenizer_class.from_pretrained(__lowerCamelCase					,						**__lowerCamelCase  )
             __A    :						int						 =     '''A, <mask> AllenNLP sentence.'''
             __A    :						int						 =     tokenizer_r.encode_plus(__lowerCamelCase					,						add_special_tokens=__lowerCamelCase					,						return_token_type_ids=__lowerCamelCase  )
             __A    :						Tuple						 =     tokenizer_p.encode_plus(__lowerCamelCase					,						add_special_tokens=__lowerCamelCase					,						return_token_type_ids=__lowerCamelCase  )

             # token_type_ids should put 0 everywhere
             self.assertEqual(sum(tokens_r['''token_type_ids''']  )					,						sum(tokens_p['''token_type_ids''']  )  )

             # attention_mask should put 1 everywhere, so sum over length should be 1
             self.assertEqual(
                 sum(tokens_r['''attention_mask''']  ) / len(tokens_r['''attention_mask''']  )					,						sum(tokens_p['''attention_mask''']  ) / len(tokens_p['''attention_mask''']  )					,						)

             __A    :						Tuple						 =     tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids''']  )
             __A    :						Optional[int]						 =     tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids''']  )

             # Rust correctly handles the space before the mask while python doesnt
             self.assertSequenceEqual(tokens_p['''input_ids''']					,						[0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2]  )
             self.assertSequenceEqual(tokens_r['''input_ids''']					,						[0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2]  )

             self.assertSequenceEqual(
                 __lowerCamelCase					,						['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>''']  )
             self.assertSequenceEqual(
                 __lowerCamelCase					,						['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>''']  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     for trim_offsets, add_prefix_space in itertools.product([True, False]					,						repeat=2  ):
         __A    :						Optional[Any]						 =     self.rust_tokenizer_class.from_pretrained(
             self.tmpdirname					,						use_fast=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase					,						trim_offsets=__lowerCamelCase  )

         __A    :						Dict						 =     json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__()  )
         __A    :						Dict						 =     json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__()  )

         self.assertEqual(pre_tokenizer_state['''add_prefix_space''']					,						__lowerCamelCase  )

         self.assertEqual(post_processor_state['''add_prefix_space''']					,						__lowerCamelCase  )
         self.assertEqual(post_processor_state['''trim_offsets''']					,						__lowerCamelCase  )







 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
         with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""  ):
             __A    :						Optional[Any]						 =     '''hello'''  # `hello` is a token in the vocabulary of `pretrained_name`
             __A    :						Tuple						 =     F"""{text_of_1_token} {text_of_1_token}"""

             __A    :						Optional[Any]						 =     self.rust_tokenizer_class.from_pretrained(
                 __lowerCamelCase					,						use_fast=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase					,						trim_offsets=__lowerCamelCase  )
             __A    :						Optional[int]						 =     tokenizer_r(__lowerCamelCase					,						return_offsets_mapping=__lowerCamelCase					,						add_special_tokens=__lowerCamelCase  )
             self.assertEqual(encoding.offset_mapping[0]					,						(0, len(__lowerCamelCase  ))  )
             self.assertEqual(
                 encoding.offset_mapping[1]					,						(len(__lowerCamelCase  ) + 1, len(__lowerCamelCase  ) + 1 + len(__lowerCamelCase  ))					,						)

             __A    :						List[Any]						 =     self.rust_tokenizer_class.from_pretrained(
                 __lowerCamelCase					,						use_fast=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase					,						trim_offsets=__lowerCamelCase  )
             __A    :						Dict						 =     tokenizer_r(__lowerCamelCase					,						return_offsets_mapping=__lowerCamelCase					,						add_special_tokens=__lowerCamelCase  )
             self.assertEqual(encoding.offset_mapping[0]					,						(0, len(__lowerCamelCase  ))  )
             self.assertEqual(
                 encoding.offset_mapping[1]					,						(len(__lowerCamelCase  ) + 1, len(__lowerCamelCase  ) + 1 + len(__lowerCamelCase  ))					,						)

             __A    :						int						 =     self.rust_tokenizer_class.from_pretrained(
                 __lowerCamelCase					,						use_fast=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase					,						trim_offsets=__lowerCamelCase  )
             __A    :						List[Any]						 =     tokenizer_r(__lowerCamelCase					,						return_offsets_mapping=__lowerCamelCase					,						add_special_tokens=__lowerCamelCase  )
             self.assertEqual(encoding.offset_mapping[0]					,						(0, len(__lowerCamelCase  ))  )
             self.assertEqual(
                 encoding.offset_mapping[1]					,						(len(__lowerCamelCase  ), len(__lowerCamelCase  ) + 1 + len(__lowerCamelCase  ))					,						)

             __A    :						Any						 =     self.rust_tokenizer_class.from_pretrained(
                 __lowerCamelCase					,						use_fast=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase					,						trim_offsets=__lowerCamelCase  )
             __A    :						List[str]						 =     tokenizer_r(__lowerCamelCase					,						return_offsets_mapping=__lowerCamelCase					,						add_special_tokens=__lowerCamelCase  )
             self.assertEqual(encoding.offset_mapping[0]					,						(0, len(__lowerCamelCase  ))  )
             self.assertEqual(
                 encoding.offset_mapping[1]					,						(len(__lowerCamelCase  ), len(__lowerCamelCase  ) + 1 + len(__lowerCamelCase  ))					,						)

             __A    :						Tuple						 =     F""" {text}"""

             # tokenizer_r = self.rust_tokenizer_class.from_pretrained(
             #     pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
             # )
             # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
             # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
             # self.assertEqual(
             #     encoding.offset_mapping[1],
             #     (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
             # )

             __A    :						Optional[Any]						 =     self.rust_tokenizer_class.from_pretrained(
                 __lowerCamelCase					,						use_fast=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase					,						trim_offsets=__lowerCamelCase  )
             __A    :						Dict						 =     tokenizer_r(__lowerCamelCase					,						return_offsets_mapping=__lowerCamelCase					,						add_special_tokens=__lowerCamelCase  )
             self.assertEqual(encoding.offset_mapping[0]					,						(1, 1 + len(__lowerCamelCase  ))  )
             self.assertEqual(
                 encoding.offset_mapping[1]					,						(1 + len(__lowerCamelCase  ) + 1, 1 + len(__lowerCamelCase  ) + 1 + len(__lowerCamelCase  ))					,						)

             __A    :						Dict						 =     self.rust_tokenizer_class.from_pretrained(
                 __lowerCamelCase					,						use_fast=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase					,						trim_offsets=__lowerCamelCase  )
             __A    :						Tuple						 =     tokenizer_r(__lowerCamelCase					,						return_offsets_mapping=__lowerCamelCase					,						add_special_tokens=__lowerCamelCase  )
             self.assertEqual(encoding.offset_mapping[0]					,						(0, 1 + len(__lowerCamelCase  ))  )
             self.assertEqual(
                 encoding.offset_mapping[1]					,						(1 + len(__lowerCamelCase  ), 1 + len(__lowerCamelCase  ) + 1 + len(__lowerCamelCase  ))					,						)

             __A    :						str						 =     self.rust_tokenizer_class.from_pretrained(
                 __lowerCamelCase					,						use_fast=__lowerCamelCase					,						add_prefix_space=__lowerCamelCase					,						trim_offsets=__lowerCamelCase  )
             __A    :						Optional[int]						 =     tokenizer_r(__lowerCamelCase					,						return_offsets_mapping=__lowerCamelCase					,						add_special_tokens=__lowerCamelCase  )
             self.assertEqual(encoding.offset_mapping[0]					,						(0, 1 + len(__lowerCamelCase  ))  )
             self.assertEqual(
                 encoding.offset_mapping[1]					,						(1 + len(__lowerCamelCase  ), 1 + len(__lowerCamelCase  ) + 1 + len(__lowerCamelCase  ))					,						)











"""simple docstring"""



import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






class 		__snake_case					(		unittest.TestCase     ):





 """simple docstring"""


 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

 @property
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     1
     __A    :						Any						 =     3
     __A    :						List[str]						 =     (32, 32)

     __A    :						List[str]						 =     floats_tensor((batch_size, num_channels) + sizes					,						rng=random.Random(0  )  ).to(__lowerCamelCase  )
     return image

 @property
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     torch.manual_seed(0  )
     __A    :						List[Any]						 =     UNetaDConditionModel(
         block_out_channels=(32, 32, 64)					,						layers_per_block=2					,						sample_size=32					,						in_channels=7					,						out_channels=4					,						down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''')					,						up_block_types=('''CrossAttnUpBlock2D''', '''CrossAttnUpBlock2D''', '''UpBlock2D''')					,						cross_attention_dim=32					,						attention_head_dim=8					,						use_linear_projection=__lowerCamelCase					,						only_cross_attention=(True, True, False)					,						num_class_embeds=100					,						)
     return model

 @property
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     torch.manual_seed(0  )
     __A    :						Any						 =     AutoencoderKL(
         block_out_channels=[32, 32, 64]					,						in_channels=3					,						out_channels=3					,						down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D''']					,						up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D''']					,						latent_channels=4					,						)
     return model

 @property
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     torch.manual_seed(0  )
     __A    :						Tuple						 =     CLIPTextConfig(
         bos_token_id=0					,						eos_token_id=2					,						hidden_size=32					,						intermediate_size=37					,						layer_norm_eps=1e-0_5					,						num_attention_heads=4					,						num_hidden_layers=5					,						pad_token_id=1					,						vocab_size=1000					,						hidden_act='''gelu'''					,						projection_dim=512					,						)
     return CLIPTextModel(__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     '''cpu'''  # ensure determinism for the device-dependent torch.Generator
     __A    :						int						 =     self.dummy_cond_unet_upscale
     __A    :						Union[str, Any]						 =     DDPMScheduler()
     __A    :						Dict						 =     DDIMScheduler(prediction_type='''v_prediction'''  )
     __A    :						int						 =     self.dummy_vae
     __A    :						int						 =     self.dummy_text_encoder
     __A    :						Union[str, Any]						 =     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )

     __A    :						Tuple						 =     self.dummy_image.cpu().permute(0					,						2					,						3					,						1  )[0]
     __A    :						Any						 =     Image.fromarray(np.uinta(__lowerCamelCase  )  ).convert('''RGB'''  ).resize((64, 64)  )

     # make sure here that pndm scheduler skips prk
     __A    :						Dict						 =     StableDiffusionUpscalePipeline(
         unet=__lowerCamelCase					,						low_res_scheduler=__lowerCamelCase					,						scheduler=__lowerCamelCase					,						vae=__lowerCamelCase					,						text_encoder=__lowerCamelCase					,						tokenizer=__lowerCamelCase					,						max_noise_level=350					,						)
     __A    :						str						 =     sd_pipe.to(__lowerCamelCase  )
     sd_pipe.set_progress_bar_config(disable=__lowerCamelCase  )

     __A    :						List[str]						 =     '''A painting of a squirrel eating a burger'''
     __A    :						Any						 =     torch.Generator(device=__lowerCamelCase  ).manual_seed(0  )
     __A    :						List[str]						 =     sd_pipe(
         [prompt]					,						image=__lowerCamelCase					,						generator=__lowerCamelCase					,						guidance_scale=6.0					,						noise_level=20					,						num_inference_steps=2					,						output_type='''np'''					,						)

     __A    :						Union[str, Any]						 =     output.images

     __A    :						List[str]						 =     torch.Generator(device=__lowerCamelCase  ).manual_seed(0  )
     __A    :						str						 =     sd_pipe(
         [prompt]					,						image=__lowerCamelCase					,						generator=__lowerCamelCase					,						guidance_scale=6.0					,						noise_level=20					,						num_inference_steps=2					,						output_type='''np'''					,						return_dict=__lowerCamelCase					,						)[0]

     __A    :						Tuple						 =     image[0, -3:, -3:, -1]
     __A    :						int						 =     image_from_tuple[0, -3:, -3:, -1]

     __A    :						Dict						 =     low_res_image.size[0] * 4
     assert image.shape == (1, expected_height_width, expected_height_width, 3)
     __A    :						str						 =     np.array([0.3_1_1_3, 0.3_9_1_0, 0.4_2_7_2, 0.4_8_5_9, 0.5_0_6_1, 0.4_6_5_2, 0.5_3_6_2, 0.5_7_1_5, 0.5_6_6_1]  )

     assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice  ).max() < 1e-2

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Tuple						 =     '''cpu'''  # ensure determinism for the device-dependent torch.Generator
     __A    :						Dict						 =     self.dummy_cond_unet_upscale
     __A    :						List[str]						 =     DDPMScheduler()
     __A    :						str						 =     DDIMScheduler(prediction_type='''v_prediction'''  )
     __A    :						Optional[int]						 =     self.dummy_vae
     __A    :						Optional[Any]						 =     self.dummy_text_encoder
     __A    :						Optional[Any]						 =     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )

     __A    :						List[Any]						 =     self.dummy_image.cpu().permute(0					,						2					,						3					,						1  )[0]
     __A    :						int						 =     Image.fromarray(np.uinta(__lowerCamelCase  )  ).convert('''RGB'''  ).resize((64, 64)  )

     # make sure here that pndm scheduler skips prk
     __A    :						Any						 =     StableDiffusionUpscalePipeline(
         unet=__lowerCamelCase					,						low_res_scheduler=__lowerCamelCase					,						scheduler=__lowerCamelCase					,						vae=__lowerCamelCase					,						text_encoder=__lowerCamelCase					,						tokenizer=__lowerCamelCase					,						max_noise_level=350					,						)
     __A    :						Any						 =     sd_pipe.to(__lowerCamelCase  )
     sd_pipe.set_progress_bar_config(disable=__lowerCamelCase  )

     __A    :						Any						 =     '''A painting of a squirrel eating a burger'''
     __A    :						Any						 =     sd_pipe(
         2 * [prompt]					,						image=2 * [low_res_image]					,						guidance_scale=6.0					,						noise_level=20					,						num_inference_steps=2					,						output_type='''np'''					,						)
     __A    :						Union[str, Any]						 =     output.images
     assert image.shape[0] == 2

     __A    :						Optional[Any]						 =     torch.Generator(device=__lowerCamelCase  ).manual_seed(0  )
     __A    :						Any						 =     sd_pipe(
         [prompt]					,						image=__lowerCamelCase					,						generator=__lowerCamelCase					,						num_images_per_prompt=2					,						guidance_scale=6.0					,						noise_level=20					,						num_inference_steps=2					,						output_type='''np'''					,						)
     __A    :						Union[str, Any]						 =     output.images
     assert image.shape[0] == 2







 @unittest.skipIf(torch_device != '''cuda'''					,						'''This test requires a GPU'''  )
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     self.dummy_cond_unet_upscale
     __A    :						int						 =     DDPMScheduler()
     __A    :						List[Any]						 =     DDIMScheduler(prediction_type='''v_prediction'''  )
     __A    :						Optional[Any]						 =     self.dummy_vae
     __A    :						List[str]						 =     self.dummy_text_encoder
     __A    :						Dict						 =     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )

     __A    :						Union[str, Any]						 =     self.dummy_image.cpu().permute(0					,						2					,						3					,						1  )[0]
     __A    :						int						 =     Image.fromarray(np.uinta(__lowerCamelCase  )  ).convert('''RGB'''  ).resize((64, 64)  )

     # put models in fp16, except vae as it overflows in fp16
     __A    :						Union[str, Any]						 =     unet.half()
     __A    :						Optional[int]						 =     text_encoder.half()

     # make sure here that pndm scheduler skips prk
     __A    :						Optional[int]						 =     StableDiffusionUpscalePipeline(
         unet=__lowerCamelCase					,						low_res_scheduler=__lowerCamelCase					,						scheduler=__lowerCamelCase					,						vae=__lowerCamelCase					,						text_encoder=__lowerCamelCase					,						tokenizer=__lowerCamelCase					,						max_noise_level=350					,						)
     __A    :						Union[str, Any]						 =     sd_pipe.to(__lowerCamelCase  )
     sd_pipe.set_progress_bar_config(disable=__lowerCamelCase  )

     __A    :						Union[str, Any]						 =     '''A painting of a squirrel eating a burger'''
     __A    :						Optional[Any]						 =     torch.manual_seed(0  )
     __A    :						Tuple						 =     sd_pipe(
         [prompt]					,						image=__lowerCamelCase					,						generator=__lowerCamelCase					,						num_inference_steps=2					,						output_type='''np'''					,						).images

     __A    :						str						 =     low_res_image.size[0] * 4
     assert image.shape == (1, expected_height_width, expected_height_width, 3)






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





 """simple docstring"""


 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/sd2-upscale/low_res_cat.png'''  )
     __A    :						Dict						 =     load_numpy(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'''
         '''/upsampled_cat.npy'''  )

     __A    :						str						 =     '''stabilityai/stable-diffusion-x4-upscaler'''
     __A    :						Optional[Any]						 =     StableDiffusionUpscalePipeline.from_pretrained(__lowerCamelCase  )
     pipe.to(__lowerCamelCase  )
     pipe.set_progress_bar_config(disable=__lowerCamelCase  )
     pipe.enable_attention_slicing()

     __A    :						Union[str, Any]						 =     '''a cat sitting on a park bench'''

     __A    :						Union[str, Any]						 =     torch.manual_seed(0  )
     __A    :						Optional[Any]						 =     pipe(
         prompt=__lowerCamelCase					,						image=__lowerCamelCase					,						generator=__lowerCamelCase					,						output_type='''np'''					,						)
     __A    :						List[str]						 =     output.images[0]

     assert image.shape == (512, 512, 3)
     assert np.abs(expected_image - image  ).max() < 1e-3

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Dict						 =     load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/sd2-upscale/low_res_cat.png'''  )
     __A    :						List[Any]						 =     load_numpy(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'''
         '''/upsampled_cat_fp16.npy'''  )

     __A    :						Optional[int]						 =     '''stabilityai/stable-diffusion-x4-upscaler'''
     __A    :						Optional[int]						 =     StableDiffusionUpscalePipeline.from_pretrained(
         __lowerCamelCase					,						torch_dtype=torch.floataa					,						)
     pipe.to(__lowerCamelCase  )
     pipe.set_progress_bar_config(disable=__lowerCamelCase  )
     pipe.enable_attention_slicing()

     __A    :						Dict						 =     '''a cat sitting on a park bench'''

     __A    :						Any						 =     torch.manual_seed(0  )
     __A    :						Optional[int]						 =     pipe(
         prompt=__lowerCamelCase					,						image=__lowerCamelCase					,						generator=__lowerCamelCase					,						output_type='''np'''					,						)
     __A    :						Any						 =     output.images[0]

     assert image.shape == (512, 512, 3)
     assert np.abs(expected_image - image  ).max() < 5e-1







 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

     __A    :						Union[str, Any]						 =     load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/sd2-upscale/low_res_cat.png'''  )

     __A    :						List[str]						 =     '''stabilityai/stable-diffusion-x4-upscaler'''
     __A    :						Dict						 =     StableDiffusionUpscalePipeline.from_pretrained(
         __lowerCamelCase					,						torch_dtype=torch.floataa					,						)
     pipe.to(__lowerCamelCase  )
     pipe.set_progress_bar_config(disable=__lowerCamelCase  )
     pipe.enable_attention_slicing(1  )
     pipe.enable_sequential_cpu_offload()

     __A    :						Tuple						 =     '''a cat sitting on a park bench'''

     __A    :						Tuple						 =     torch.manual_seed(0  )
     __A    :						List[str]						 =     pipe(
         prompt=__lowerCamelCase					,						image=__lowerCamelCase					,						generator=__lowerCamelCase					,						num_inference_steps=5					,						output_type='''np'''					,						)

     __A    :						Any						 =     torch.cuda.max_memory_allocated()
     # make sure that less than 2.9 GB is allocated
     assert mem_bytes < 2.9 * 10**9




