


'''simple docstring'''




import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test

class 		UpperCAmelCase_      (  unittest.TestCase		):





     @parameterized.expand([(None,), ('foo.json',)]    )
     def 							__UpperCAmelCase      ( self       :      Dict    ,      UpperCAmelCase__       :      Optional[Any]    )				->  Tuple:
        lowerCAmelCase     =			GenerationConfig(
            do_sample=UpperCAmelCase__    ,      temperature=0.7    ,      length_penalty=1.0    ,      bad_words_ids=[[1, 2, 3], [4, 5]]    ,      )
        with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(UpperCAmelCase__    ,      config_name=UpperCAmelCase__    )
           lowerCAmelCase     =			GenerationConfig.from_pretrained(UpperCAmelCase__    ,      config_name=UpperCAmelCase__    )

        # Checks parameters that were specified
        self.assertEqual(loaded_config.do_sample    ,      UpperCAmelCase__    )
        self.assertEqual(loaded_config.temperature    ,      0.7    )
        self.assertEqual(loaded_config.length_penalty    ,      1.0    )
        self.assertEqual(loaded_config.bad_words_ids    ,      [[1, 2, 3], [4, 5]]    )

        # Checks parameters that were not specified (defaults)
        self.assertEqual(loaded_config.top_k    ,      5_0    )
        self.assertEqual(loaded_config.max_length    ,      2_0    )
        self.assertEqual(loaded_config.max_time    ,      UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  Union[str, Any]:
        lowerCAmelCase     =			AutoConfig.from_pretrained('gpt2'    )
        lowerCAmelCase     =			GenerationConfig.from_model_config(UpperCAmelCase__    )
        lowerCAmelCase     =			GenerationConfig()

        # The generation config has loaded a few non-default parameters from the model config
        self.assertNotEqual(UpperCAmelCase__    ,      UpperCAmelCase__    )

        # One of those parameters is eos_token_id -- check if it matches
        self.assertNotEqual(generation_config_from_model.eos_token_id    ,      default_generation_config.eos_token_id    )
        self.assertEqual(generation_config_from_model.eos_token_id    ,      model_config.eos_token_id    )





     def 							__UpperCAmelCase      ( self       :      str    )				->  Dict:
        lowerCAmelCase     =			GenerationConfig()
        lowerCAmelCase     =			{
            'max_new_tokens': 1_0_2_4,
            'foo': 'bar',
        }
        lowerCAmelCase     =			copy.deepcopy(UpperCAmelCase__    )
        lowerCAmelCase     =			generation_config.update(**UpperCAmelCase__    )

        # update_kwargs was not modified (no side effects)
        self.assertEqual(UpperCAmelCase__    ,      UpperCAmelCase__    )

        # update_kwargs was used to update the config on valid attributes
        self.assertEqual(generation_config.max_new_tokens    ,      1_0_2_4    )

        # `.update()` returns a dictionary of unused kwargs
        self.assertEqual(UpperCAmelCase__    ,      {'foo': 'bar'}    )





     def 							__UpperCAmelCase      ( self       :      int    )				->  Any:
        lowerCAmelCase     =			GenerationConfig()
        lowerCAmelCase     =			'bar'

        with tempfile.TemporaryDirectory('test-generation-config'    ) as tmp_dir:
           generation_config.save_pretrained(UpperCAmelCase__    )

           lowerCAmelCase     =			GenerationConfig.from_pretrained(UpperCAmelCase__    )
        # update_kwargs was used to update the config on valid attributes
        self.assertEqual(new_config.foo    ,      'bar'    )

        lowerCAmelCase     =			GenerationConfig.from_model_config(UpperCAmelCase__    )
        assert not hasattr(UpperCAmelCase__    ,      'foo'    )  # no new kwargs should be initialized if from config





     def 							__UpperCAmelCase      ( self       :      int    )				->  int:
        lowerCAmelCase     =			GenerationConfig()
        self.assertEqual(default_config.temperature    ,      1.0    )
        self.assertEqual(default_config.do_sample    ,      UpperCAmelCase__    )
        self.assertEqual(default_config.num_beams    ,      1    )

        lowerCAmelCase     =			GenerationConfig(
            do_sample=UpperCAmelCase__    ,      temperature=0.7    ,      length_penalty=1.0    ,      bad_words_ids=[[1, 2, 3], [4, 5]]    ,      )
        self.assertEqual(config.temperature    ,      0.7    )
        self.assertEqual(config.do_sample    ,      UpperCAmelCase__    )
        self.assertEqual(config.num_beams    ,      1    )

        with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(UpperCAmelCase__    )
           lowerCAmelCase     =			GenerationConfig.from_pretrained(UpperCAmelCase__    ,      temperature=1.0    )

        self.assertEqual(loaded_config.temperature    ,      1.0    )
        self.assertEqual(loaded_config.do_sample    ,      UpperCAmelCase__    )
        self.assertEqual(loaded_config.num_beams    ,      1    )  # default value




@is_staging_test
class 		UpperCAmelCase_      (  unittest.TestCase		):





     @classmethod
     def 							__UpperCAmelCase      ( cls       :      Dict    )				->  List[str]:
        lowerCAmelCase     =			TOKEN
        HfFolder.save_token(UpperCAmelCase__    )





     @classmethod
     def 							__UpperCAmelCase      ( cls       :      str    )				->  str:
        try:
           delete_repo(token=cls._token    ,      repo_id='test-generation-config'    )
        except HTTPError:
           pass

        try:
           delete_repo(token=cls._token    ,      repo_id='valid_org/test-generation-config-org'    )
        except HTTPError:
           pass





     def 							__UpperCAmelCase      ( self       :      int    )				->  List[Any]:
        lowerCAmelCase     =			GenerationConfig(
            do_sample=UpperCAmelCase__    ,      temperature=0.7    ,      length_penalty=1.0    ,      )
        config.push_to_hub('test-generation-config'    ,      use_auth_token=self._token    )

        lowerCAmelCase     =			GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''    )
        for k, v in config.to_dict().items():
           if k != "transformers_version":
              self.assertEqual(UpperCAmelCase__    ,      getattr(UpperCAmelCase__    ,      UpperCAmelCase__    )    )

        # Reset repo
        delete_repo(token=self._token    ,      repo_id='test-generation-config'    )

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(
               UpperCAmelCase__    ,      repo_id='test-generation-config'    ,      push_to_hub=UpperCAmelCase__    ,      use_auth_token=self._token    )

        lowerCAmelCase     =			GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''    )
        for k, v in config.to_dict().items():
           if k != "transformers_version":
              self.assertEqual(UpperCAmelCase__    ,      getattr(UpperCAmelCase__    ,      UpperCAmelCase__    )    )





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Optional[int]:
        lowerCAmelCase     =			GenerationConfig(
            do_sample=UpperCAmelCase__    ,      temperature=0.7    ,      length_penalty=1.0    ,      )
        config.push_to_hub('valid_org/test-generation-config-org'    ,      use_auth_token=self._token    )

        lowerCAmelCase     =			GenerationConfig.from_pretrained('valid_org/test-generation-config-org'    )
        for k, v in config.to_dict().items():
           if k != "transformers_version":
              self.assertEqual(UpperCAmelCase__    ,      getattr(UpperCAmelCase__    ,      UpperCAmelCase__    )    )

        # Reset repo
        delete_repo(token=self._token    ,      repo_id='valid_org/test-generation-config-org'    )

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
           config.save_pretrained(
               UpperCAmelCase__    ,      repo_id='valid_org/test-generation-config-org'    ,      push_to_hub=UpperCAmelCase__    ,      use_auth_token=self._token    )

        lowerCAmelCase     =			GenerationConfig.from_pretrained('valid_org/test-generation-config-org'    )
        for k, v in config.to_dict().items():
           if k != "transformers_version":
              self.assertEqual(UpperCAmelCase__    ,      getattr(UpperCAmelCase__    ,      UpperCAmelCase__    )    )









'''simple docstring'''




import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()

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





     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  int:
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  Any:
        lowerCAmelCase     =			StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'    )
        lowerCAmelCase     =			sd_pipe.to(UpperCAmelCase__    )
        sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__    )

        sd_pipe.set_scheduler('sample_euler'    )

        lowerCAmelCase     =			'A painting of a squirrel eating a burger'
        lowerCAmelCase     =			torch.manual_seed(0    )
        lowerCAmelCase     =			sd_pipe([prompt]    ,      generator=UpperCAmelCase__    ,      guidance_scale=9.0    ,      num_inference_steps=2_0    ,      output_type='np'    )

        lowerCAmelCase     =			output.images

        lowerCAmelCase     =			image[0, -3:, -3:, -1]

        assert image.shape == (1, 5_1_2, 5_1_2, 3)
        lowerCAmelCase     =			np.array([0.0_447, 0.0_492, 0.0_468, 0.0_408, 0.0_383, 0.0_408, 0.0_354, 0.0_380, 0.0_339]    )

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





     def 							__UpperCAmelCase      ( self       :      List[str]    )				->  Dict:
        lowerCAmelCase     =			StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'    )
        lowerCAmelCase     =			sd_pipe.to(UpperCAmelCase__    )
        sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__    )

        sd_pipe.set_scheduler('sample_euler'    )

        lowerCAmelCase     =			'A painting of a squirrel eating a burger'
        lowerCAmelCase     =			torch.manual_seed(0    )
        lowerCAmelCase     =			sd_pipe([prompt]    ,      generator=UpperCAmelCase__    ,      guidance_scale=9.0    ,      num_inference_steps=2_0    ,      output_type='np'    )

        lowerCAmelCase     =			output.images

        lowerCAmelCase     =			image[0, -3:, -3:, -1]

        assert image.shape == (1, 5_1_2, 5_1_2, 3)
        lowerCAmelCase     =			np.array([0.1_237, 0.1_320, 0.1_438, 0.1_359, 0.1_390, 0.1_132, 0.1_277, 0.1_175, 0.1_112]    )

        assert np.abs(image_slice.flatten() - expected_slice    ).max() < 5E-1





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  List[str]:
        lowerCAmelCase     =			StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'    )
        lowerCAmelCase     =			sd_pipe.to(UpperCAmelCase__    )
        sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__    )

        sd_pipe.set_scheduler('sample_dpmpp_2m'    )

        lowerCAmelCase     =			'A painting of a squirrel eating a burger'
        lowerCAmelCase     =			torch.manual_seed(0    )
        lowerCAmelCase     =			sd_pipe(
            [prompt]    ,      generator=UpperCAmelCase__    ,      guidance_scale=7.5    ,      num_inference_steps=1_5    ,      output_type='np'    ,      use_karras_sigmas=UpperCAmelCase__    ,      )

        lowerCAmelCase     =			output.images

        lowerCAmelCase     =			image[0, -3:, -3:, -1]

        assert image.shape == (1, 5_1_2, 5_1_2, 3)
        lowerCAmelCase     =			np.array(
            [0.11_381_689, 0.12_112_921, 0.1_389_457, 0.12_549_606, 0.1_244_964, 0.10_831_517, 0.11_562_866, 0.10_867_816, 0.10_499_048]    )

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





