


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       lowerCamelCase__   (       unittest.TestCase):





     @parameterized.expand([(None,), ('''foo.json''',)]       )
     def      __A					(self		,     UpperCAmelCase       )     ->   Any:
      _lowercase							      =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       )
       _lowercase							      =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      __A					(self       )     ->   Optional[Any]:
      _lowercase							      =AutoConfig.from_pretrained('''gpt2'''       )
      _lowercase							      =GenerationConfig.from_model_config(UpperCAmelCase       )
      _lowercase							      =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      __A					(self       )     ->   List[str]:
      _lowercase							      =GenerationConfig()
      _lowercase							      ={
          '''max_new_tokens''': 1_0_2_4,
          '''foo''': '''bar''',
      }
      _lowercase							      =copy.deepcopy(UpperCAmelCase       )
      _lowercase							      =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      __A					(self       )     ->   Tuple:
      _lowercase							      =GenerationConfig()
      _lowercase							      ='''bar'''

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

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

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





     def      __A					(self       )     ->   List[str]:
      _lowercase							      =GenerationConfig()
      self.assertEqual(default_config.temperature		,     1.0       )
      self.assertEqual(default_config.do_sample		,     UpperCAmelCase       )
      self.assertEqual(default_config.num_beams		,     1       )

      _lowercase							      =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       )
       _lowercase							      =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       lowerCamelCase__   (       unittest.TestCase):





     @classmethod
     def      __A					(cls       )     ->   str:
      _lowercase							      =TOKEN
      HfFolder.save_token(UpperCAmelCase       )





     @classmethod
     def      __A					(cls       )     ->   Tuple:
      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      __A					(self       )     ->   int:
      _lowercase							      =GenerationConfig(
          do_sample=UpperCAmelCase		,     temperature=0.7		,     length_penalty=1.0		,     )
      config.push_to_hub('''test-generation-config'''		,     use_auth_token=self._token       )

      _lowercase							      =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       )

      _lowercase							      =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      __A					(self       )     ->   Optional[int]:
      _lowercase							      =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       )

      _lowercase							      =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       )

      _lowercase							      =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       )       )





import gc
import unittest

from diffusers import FlaxStableDiffusionInpaintPipeline
from diffusers.utils import is_flax_available, load_image, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
  import jax
  import jax.numpy as jnp
  from flax.jax_utils import replicate
  from flax.training.common_utils import shard







@slow
@require_flax
class       lowerCamelCase__   (       unittest.TestCase):





     def      __A					(self       )     ->   List[Any]:
      # clean up the VRAM after each test
      super().tearDown()
      gc.collect()





     def      __A					(self       )     ->   Optional[Any]:
      _lowercase							      =load_image(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
          '''/sd2-inpaint/init_image.png'''       )
      _lowercase							      =load_image(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''       )

      _lowercase							      ='''xvjiarui/stable-diffusion-2-inpainting'''
      _lowercase      ,    _lowercase							      =FlaxStableDiffusionInpaintPipeline.from_pretrained(UpperCAmelCase		,     safety_checker=UpperCAmelCase       )

      _lowercase							      ='''Face of a yellow cat, high resolution, sitting on a park bench'''

      _lowercase							      =jax.random.PRNGKey(0       )
      _lowercase							      =5_0

      _lowercase							      =jax.device_count()
      _lowercase							      =num_samples * [prompt]
      _lowercase							      =num_samples * [init_image]
      _lowercase							      =num_samples * [mask_image]
      _lowercase      ,    _lowercase      ,    _lowercase							      =pipeline.prepare_inputs(UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase       )

      # shard inputs and rng
      _lowercase							      =replicate(UpperCAmelCase       )
      _lowercase							      =jax.random.split(UpperCAmelCase		,     jax.device_count()       )
      _lowercase							      =shard(UpperCAmelCase       )
      _lowercase							      =shard(UpperCAmelCase       )
      _lowercase							      =shard(UpperCAmelCase       )

      _lowercase							      =pipeline(
          UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     jit=UpperCAmelCase       )

      _lowercase							      =output.images.reshape(UpperCAmelCase		,     5_1_2		,     5_1_2		,     3       )

      _lowercase							      =images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

      _lowercase							      =jnp.asarray(jax.device_get(image_slice.flatten()       )       )
      _lowercase							      =jnp.array(
          [0.361_1307, 0.3764_9736, 0.375_7408, 0.3821_3953, 0.3929_5167, 0.384_1631, 0.4155_4978, 0.413_7475, 0.421_7084]       )
      print(f"output_slice: {output_slice}"       )
      assert jnp.abs(output_slice - expected_slice       ).max() < 1e-2

