






import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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 							lowercase    (						unittest.TestCase			):






 '''simple docstring'''




 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



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


 @property
 def  snake_case__				(	self) ->		Optional[Any]:

     """simple docstring"""



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

     _UpperCAmelCase				:      List[Any]			  =				floats_tensor((batch_size, num_channels) + sizes							,  rng=random.Random(0)).to(__UpperCamelCase)
     return image


 @property
 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     torch.manual_seed(0)
     _UpperCAmelCase				:      Dict			  =				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							,  )
     return model


 @property
 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



     torch.manual_seed(0)
     _UpperCAmelCase				:      str			  =				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							,  )
     return model


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

     """simple docstring"""



     torch.manual_seed(0)
     _UpperCAmelCase				:      Tuple			  =				RobertaSeriesConfig(
         hidden_size=32							,  project_dim=32							,  intermediate_size=37							,  layer_norm_eps=1e-05							,  num_attention_heads=4							,  num_hidden_layers=5							,  pad_token_id=1							,  vocab_size=5006							,  )
     return RobertaSeriesModelWithTransformation(__UpperCamelCase)


 @property
 def  snake_case__				(	self) ->		str:

     """simple docstring"""



     def extract(*_A							,  **_A):
         class 							lowercase    :






          '''simple docstring'''




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

              """simple docstring"""



              _UpperCAmelCase				:      int			  =				torch.ones([0])


          def  snake_case__				(	self							,  _A) ->		Optional[Any]:

              """simple docstring"""



              self.pixel_values.to(__UpperCamelCase)
              return self



         return Out()

     return extract


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

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     _UpperCAmelCase				:      Tuple			  =				self.dummy_cond_unet
     _UpperCAmelCase				:      List[str]			  =				PNDMScheduler(skip_prk_steps=__UpperCamelCase)
     _UpperCAmelCase				:      Union[str, Any]			  =				self.dummy_vae
     _UpperCAmelCase				:      Optional[Any]			  =				self.dummy_text_encoder
     _UpperCAmelCase				:      Union[str, Any]			  =				XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''')
     _UpperCAmelCase				:      Dict			  =				77

     _UpperCAmelCase				:      int			  =				self.dummy_image.to(__UpperCamelCase)
     _UpperCAmelCase				:      Optional[Any]			  =				init_image / 2 + 0.5

     # make sure here that pndm scheduler skips prk
     _UpperCAmelCase				:      Any			  =				AltDiffusionImgaImgPipeline(
         unet=__UpperCamelCase							,  scheduler=__UpperCamelCase							,  vae=__UpperCamelCase							,  text_encoder=__UpperCamelCase							,  tokenizer=__UpperCamelCase							,  safety_checker=__UpperCamelCase							,  feature_extractor=self.dummy_extractor							,  )
     _UpperCAmelCase				:      str			  =				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,  do_normalize=__UpperCamelCase)
     _UpperCAmelCase				:      Union[str, Any]			  =				alt_pipe.to(__UpperCamelCase)
     alt_pipe.set_progress_bar_config(disable=__UpperCamelCase)

     _UpperCAmelCase				:      Optional[int]			  =				'''A painting of a squirrel eating a burger'''
     _UpperCAmelCase				:      str			  =				torch.Generator(device=__UpperCamelCase).manual_seed(0)
     _UpperCAmelCase				:      Optional[int]			  =				alt_pipe(
         [prompt]							,  generator=__UpperCamelCase							,  guidance_scale=6.0							,  num_inference_steps=2							,  output_type='''np'''							,  image=__UpperCamelCase							,  )

     _UpperCAmelCase				:      Tuple			  =				output.images

     _UpperCAmelCase				:      Any			  =				torch.Generator(device=__UpperCamelCase).manual_seed(0)
     _UpperCAmelCase				:      Any			  =				alt_pipe(
         [prompt]							,  generator=__UpperCamelCase							,  guidance_scale=6.0							,  num_inference_steps=2							,  output_type='''np'''							,  image=__UpperCamelCase							,  return_dict=__UpperCamelCase							,  )[0]

     _UpperCAmelCase				:      List[str]			  =				image[0, -3:, -3:, -1]
     _UpperCAmelCase				:      Dict			  =				image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)
     _UpperCAmelCase				:      Tuple			  =				np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499])

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


 @unittest.skipIf(torch_device != '''cuda'''							,  '''This test requires a GPU''')
 def  snake_case__				(	self) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				self.dummy_cond_unet
     _UpperCAmelCase				:      Dict			  =				PNDMScheduler(skip_prk_steps=__UpperCamelCase)
     _UpperCAmelCase				:      List[str]			  =				self.dummy_vae
     _UpperCAmelCase				:      Union[str, Any]			  =				self.dummy_text_encoder
     _UpperCAmelCase				:      Optional[int]			  =				XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''')
     _UpperCAmelCase				:      int			  =				77

     _UpperCAmelCase				:      List[str]			  =				self.dummy_image.to(__UpperCamelCase)

     # put models in fp16
     _UpperCAmelCase				:      int			  =				unet.half()
     _UpperCAmelCase				:      int			  =				vae.half()
     _UpperCAmelCase				:      Tuple			  =				bert.half()

     # make sure here that pndm scheduler skips prk
     _UpperCAmelCase				:      Optional[int]			  =				AltDiffusionImgaImgPipeline(
         unet=__UpperCamelCase							,  scheduler=__UpperCamelCase							,  vae=__UpperCamelCase							,  text_encoder=__UpperCamelCase							,  tokenizer=__UpperCamelCase							,  safety_checker=__UpperCamelCase							,  feature_extractor=self.dummy_extractor							,  )
     _UpperCAmelCase				:      Any			  =				VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,  do_normalize=__UpperCamelCase)
     _UpperCAmelCase				:      List[Any]			  =				alt_pipe.to(__UpperCamelCase)
     alt_pipe.set_progress_bar_config(disable=__UpperCamelCase)

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

     assert image.shape == (1, 32, 32, 3)


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

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/img2img/sketch-mountains-input.jpg''')
     # resize to resolution that is divisible by 8 but not 16 or 32
     _UpperCAmelCase				:      int			  =				init_image.resize((760, 504))

     _UpperCAmelCase				:      List[str]			  =				'''BAAI/AltDiffusion'''
     _UpperCAmelCase				:      str			  =				AltDiffusionImgaImgPipeline.from_pretrained(
         __UpperCamelCase							,  safety_checker=__UpperCamelCase							,  )
     pipe.to(__UpperCamelCase)
     pipe.set_progress_bar_config(disable=__UpperCamelCase)
     pipe.enable_attention_slicing()

     _UpperCAmelCase				:      Optional[int]			  =				'''A fantasy landscape, trending on artstation'''

     _UpperCAmelCase				:      Optional[int]			  =				torch.manual_seed(0)
     _UpperCAmelCase				:      Union[str, Any]			  =				pipe(
         prompt=__UpperCamelCase							,  image=__UpperCamelCase							,  strength=0.75							,  guidance_scale=7.5							,  generator=__UpperCamelCase							,  output_type='''np'''							,  )
     _UpperCAmelCase				:      List[str]			  =				output.images[0]

     _UpperCAmelCase				:      str			  =				image[255:258, 383:386, -1]

     assert image.shape == (504, 760, 3)
     _UpperCAmelCase				:      Optional[int]			  =				np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000])

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



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






 '''simple docstring'''




 def  snake_case__				(	self) ->		str:

     """simple docstring"""



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


 def  snake_case__				(	self) ->		Any:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/img2img/sketch-mountains-input.jpg''')
     _UpperCAmelCase				:      Optional[Any]			  =				init_image.resize((768, 512))
     _UpperCAmelCase				:      Optional[int]			  =				load_numpy(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''')

     _UpperCAmelCase				:      Dict			  =				'''BAAI/AltDiffusion'''
     _UpperCAmelCase				:      Any			  =				AltDiffusionImgaImgPipeline.from_pretrained(
         __UpperCamelCase							,  safety_checker=__UpperCamelCase							,  )
     pipe.to(__UpperCamelCase)
     pipe.set_progress_bar_config(disable=__UpperCamelCase)
     pipe.enable_attention_slicing()

     _UpperCAmelCase				:      int			  =				'''A fantasy landscape, trending on artstation'''

     _UpperCAmelCase				:      Union[str, Any]			  =				torch.manual_seed(0)
     _UpperCAmelCase				:      Optional[int]			  =				pipe(
         prompt=__UpperCamelCase							,  image=__UpperCamelCase							,  strength=0.75							,  guidance_scale=7.5							,  generator=__UpperCamelCase							,  output_type='''np'''							,  )
     _UpperCAmelCase				:      str			  =				output.images[0]

     assert image.shape == (512, 768, 3)
     # img2img is flaky across GPUs even in fp32, so using MAE here
     assert np.abs(expected_image - image).max() < 1e-2












import unittest

from knapsack import knapsack as k
class 							A_    (						unittest.TestCase			):






 '''simple docstring'''




 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				0
     _UpperCAmelCase				:      List[Any]			  =				[0]
     _UpperCAmelCase				:      Optional[Any]			  =				[0]
     _UpperCAmelCase				:      Optional[int]			  =				len(_A)
     self.assertEqual(k.knapsack(_A							,  _A							,  _A							,  _A)							,  0)

     _UpperCAmelCase				:      Optional[int]			  =				[60]
     _UpperCAmelCase				:      List[str]			  =				[10]
     _UpperCAmelCase				:      str			  =				len(_A)
     self.assertEqual(k.knapsack(_A							,  _A							,  _A							,  _A)							,  0)


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

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				3
     _UpperCAmelCase				:      int			  =				[1, 2, 3]
     _UpperCAmelCase				:      List[str]			  =				[3, 2, 1]
     _UpperCAmelCase				:      Union[str, Any]			  =				len(_A)
     self.assertEqual(k.knapsack(_A							,  _A							,  _A							,  _A)							,  5)


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				50
     _UpperCAmelCase				:      Tuple			  =				[60, 100, 120]
     _UpperCAmelCase				:      Optional[int]			  =				[10, 20, 30]
     _UpperCAmelCase				:      Optional[Any]			  =				len(_A)
     self.assertEqual(k.knapsack(_A							,  _A							,  _A							,  _A)							,  220)


if __name__ == "__main__":
  unittest.main()




