


'''simple docstring'''






import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

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


enable_full_determinism()




class 	a       (       __lowercase					,			unittest.TestCase    ):
 _lowerCAmelCase	   =		LDMTextToImagePipeline
 _lowerCAmelCase	   =		TEXT_TO_IMAGE_PARAMS - {
     """negative_prompt""",
     """negative_prompt_embeds""",
     """cross_attention_kwargs""",
     """prompt_embeds""",
 }
 _lowerCAmelCase	   =		PipelineTesterMixin.required_optional_params - {
     """num_images_per_prompt""",
     """callback""",
     """callback_steps""",
 }
 _lowerCAmelCase	   =		TEXT_TO_IMAGE_BATCH_PARAMS
 _lowerCAmelCase	   =		False
 def 							__UpperCAmelCase						(	self  )   ->							Optional[int]:
      torch.manual_seed(0  )
      _a      =							UNetaDConditionModel(
          block_out_channels=(32, 64) ,			layers_per_block=2 ,			sample_size=32 ,			in_channels=4 ,			out_channels=4 ,			down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,			up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,			cross_attention_dim=32 ,			)
      _a      =							DDIMScheduler(
          beta_start=0.0_0_0_8_5 ,			beta_end=0.0_1_2 ,			beta_schedule='scaled_linear' ,			clip_sample=_a ,			set_alpha_to_one=_a ,			)
      torch.manual_seed(0  )
      _a      =							AutoencoderKL(
          block_out_channels=(32, 64) ,			in_channels=3 ,			out_channels=3 ,			down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') ,			up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') ,			latent_channels=4 ,			)
      torch.manual_seed(0  )
      _a      =							CLIPTextConfig(
          bos_token_id=0 ,			eos_token_id=2 ,			hidden_size=32 ,			intermediate_size=37 ,			layer_norm_eps=1e-05 ,			num_attention_heads=4 ,			num_hidden_layers=5 ,			pad_token_id=1 ,			vocab_size=10_00 ,			)
      _a      =							CLIPTextModel(_a  )
      _a      =							CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

      _a      =							{
          'unet': unet,
          'scheduler': scheduler,
          'vqvae': vae,
          'bert': text_encoder,
          'tokenizer': tokenizer,
      }
      return components
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__=0  )   ->							Union[str, Any]:
      if str(_a  ).startswith('mps'  ):
           _a      =							torch.manual_seed(_a  )
      else:
           _a      =							torch.Generator(device=_a  ).manual_seed(_a  )
      _a      =							{
          'prompt': 'A painting of a squirrel eating a burger',
          'generator': generator,
          'num_inference_steps': 2,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs




 def 							__UpperCAmelCase						(	self  )   ->							Optional[Any]:
      _a      =							'cpu'  # ensure determinism for the device-dependent torch.Generator

      _a      =							self.get_dummy_components()
      _a      =							LDMTextToImagePipeline(**_a  )
      pipe.to(_a  )
      pipe.set_progress_bar_config(disable=_a  )

      _a      =							self.get_dummy_inputs(_a  )
      _a      =							pipe(**_a  ).images
      _a      =							image[0, -3:, -3:, -1]

      assert image.shape == (1, 16, 16, 3)
      _a      =							np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]  )

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





@slow
@require_torch_gpu
class 	a       (       unittest.TestCase    ):
 def 							__UpperCAmelCase						(	self  )   ->							Dict:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__=torch.floataa ,			__magic_name__=0  )   ->							int:
      _a      =							torch.manual_seed(_a  )
      _a      =							np.random.RandomState(_a  ).standard_normal((1, 4, 32, 32)  )
      _a      =							torch.from_numpy(_a  ).to(device=_a ,			dtype=_a  )
      _a      =							{
          'prompt': 'A painting of a squirrel eating a burger',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 3,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs




 def 							__UpperCAmelCase						(	self  )   ->							str:
      _a      =							LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'  ).to(_a  )
      pipe.set_progress_bar_config(disable=_a  )

      _a      =							self.get_inputs(_a  )
      _a      =							pipe(**_a  ).images
      _a      =							image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 2_56, 2_56, 3)
      _a      =							np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]  )
      _a      =							np.abs(expected_slice - image_slice  ).max()
      assert max_diff < 1e-3





@nightly
@require_torch_gpu
class 	a       (       unittest.TestCase    ):
 def 							__UpperCAmelCase						(	self  )   ->							Tuple:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__=torch.floataa ,			__magic_name__=0  )   ->							List[str]:
      _a      =							torch.manual_seed(_a  )
      _a      =							np.random.RandomState(_a  ).standard_normal((1, 4, 32, 32)  )
      _a      =							torch.from_numpy(_a  ).to(device=_a ,			dtype=_a  )
      _a      =							{
          'prompt': 'A painting of a squirrel eating a burger',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 50,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs




 def 							__UpperCAmelCase						(	self  )   ->							Optional[Any]:
      _a      =							LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'  ).to(_a  )
      pipe.set_progress_bar_config(disable=_a  )

      _a      =							self.get_inputs(_a  )
      _a      =							pipe(**_a  ).images[0]

      _a      =							load_numpy(
          'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'  )
      _a      =							np.abs(expected_image - image  ).max()
      assert max_diff < 1e-3





'''simple docstring'''






from timeit import timeit






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     if number < 0:
          raise ValueError('the value of input must not be negative'						)
     _a      =							0
     while number:
          number &= number - 1
          result += 1
     return result






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     if number < 0:
          raise ValueError('the value of input must not be negative'						)
     _a      =							0
     while number:
          if number % 2 == 1:
               result += 1
          number >>= 1
     return result






def 		_A			()				->					None:




     '''simple docstring'''



     def do_benchmark(lowerCAmelCase__					:int						) -> None:
          _a      =							'import __main__ as z'
          print(f'Benchmark when {number = }:'						)
          print(f'{get_set_bits_count_using_modulo_operator(lowerCAmelCase__						) = }'						)
          _a      =							timeit('z.get_set_bits_count_using_modulo_operator(25)'			,  setup=lowerCAmelCase__						)
          print(f'timeit() runs in {timing} seconds'						)
          print(f'{get_set_bits_count_using_brian_kernighans_algorithm(lowerCAmelCase__						) = }'						)
          _a      =							timeit(
              'z.get_set_bits_count_using_brian_kernighans_algorithm(25)'			,  setup=lowerCAmelCase__			,  )
          print(f'timeit() runs in {timing} seconds'						)

     for number in (25, 37, 58, 0):
          do_benchmark(lowerCAmelCase__						)
          print()


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 benchmark()

