





import tempfile
import unittest

import torch

from diffusers import UNetaDConditionModel
from diffusers.training_utils import EMAModel
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device


enable_full_determinism()

class 				A    (unittest.TestCase				):
      _SCREAMING_SNAKE_CASE					=							"""hf-internal-testing/tiny-stable-diffusion-pipe"""
      _SCREAMING_SNAKE_CASE					=							1
      _SCREAMING_SNAKE_CASE					=							77
      _SCREAMING_SNAKE_CASE					=							32
      _SCREAMING_SNAKE_CASE					=							4
      _SCREAMING_SNAKE_CASE					=							_SCREAMING_SNAKE_CASE					=							64
      _SCREAMING_SNAKE_CASE					=							torch.manual_seed(0				)



      def    __a (					self     ,  lowercase_=0.9999					)      ->   Tuple:



             '''simple docstring'''

             _snake_case      :							Tuple     				=						UNetaDConditionModel.from_pretrained(self.model_id     ,  subfolder='''unet'''					)
             _snake_case      :							int     				=						unet.to(lowercase_					)
             _snake_case      :							Optional[int]     				=						EMAModel(unet.parameters()     ,  decay=lowercase_     ,  model_cls=lowercase_     ,  model_config=unet.config					)
             return unet, ema_unet



      def    __a (					self					)      ->   Optional[int]:



             '''simple docstring'''

             _snake_case      :							Optional[Any]     				=						torch.randn(
                 self.batch_size     ,  self.num_in_channels     ,  self.latent_height     ,  self.latent_width     ,  generator=self.generator					).to(lowercase_					)
             _snake_case      :							str     				=						torch.randint(0     ,  1000     ,  size=(self.batch_size,)     ,  generator=self.generator					).to(lowercase_					)
             _snake_case      :							int     				=						torch.randn(
                 self.batch_size     ,  self.prompt_length     ,  self.text_encoder_hidden_dim     ,  generator=self.generator					).to(lowercase_					)
             return noisy_latents, timesteps, encoder_hidden_states



      def    __a (					self     ,  lowercase_					)      ->   Optional[int]:



             '''simple docstring'''

             _snake_case      :							Any     				=						{}
             for k, param in unet.state_dict().items():
                    _snake_case      :							Tuple     				=						torch.randn_like(lowercase_					) + (param * torch.randn_like(lowercase_					))
                    updated_state_dict.update({k: updated_param}					)
             unet.load_state_dict(lowercase_					)
             return unet



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



             '''simple docstring'''

             _snake_case				,    _snake_case      :							List[str]     				=						self.get_models()
             # Take the first (hypothetical) EMA step.
             ema_unet.step(unet.parameters()					)
             assert ema_unet.optimization_step == 1

             # Take two more.
             for _ in range(2					):
                    ema_unet.step(unet.parameters()					)
             assert ema_unet.optimization_step == 3



      def    __a (					self					)      ->   Dict:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							int     				=						self.get_models()
             # Since the `unet` is not being updated (i.e., backprop'd)
             # there won't be any difference between the `params` of `unet`
             # and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
             ema_unet.step(unet.parameters()					)
             _snake_case      :							Optional[Any]     				=						list(unet.parameters()					)
             for s_param, param in zip(ema_unet.shadow_params     ,  lowercase_					):
                    assert torch.allclose(lowercase_     ,  lowercase_					)

             # The above holds true even if we call `ema.step()` multiple times since
             # `unet` params are still not being updated.
             for _ in range(4					):
                    ema_unet.step(unet.parameters()					)
             for s_param, param in zip(ema_unet.shadow_params     ,  lowercase_					):
                    assert torch.allclose(lowercase_     ,  lowercase_					)



      def    __a (					self					)      ->   Optional[Any]:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							Tuple     				=						self.get_models()
             # Here we simulate the parameter updates for `unet`. Since there might
             # be some parameters which are initialized to zero we take extra care to
             # initialize their values to something non-zero before the multiplication.
             _snake_case      :							Optional[Any]     				=						self.simulate_backprop(lowercase_					)

             # Take the EMA step.
             ema_unet.step(unet_pseudo_updated_step_one.parameters()					)

             # Now the EMA'd parameters won't be equal to the original model parameters.
             _snake_case      :							Tuple     				=						list(unet_pseudo_updated_step_one.parameters()					)
             for s_param, param in zip(ema_unet.shadow_params     ,  lowercase_					):
                    assert ~torch.allclose(lowercase_     ,  lowercase_					)

             # Ensure this is the case when we take multiple EMA steps.
             for _ in range(4					):
                    ema_unet.step(unet.parameters()					)
             for s_param, param in zip(ema_unet.shadow_params     ,  lowercase_					):
                    assert ~torch.allclose(lowercase_     ,  lowercase_					)



      def    __a (					self					)      ->   Optional[Any]:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							Tuple     				=						self.get_models()

             # First backprop + EMA
             _snake_case      :							int     				=						self.simulate_backprop(lowercase_					)
             ema_unet.step(unet_step_one.parameters()					)
             _snake_case      :							str     				=						ema_unet.shadow_params

             # Second backprop + EMA
             _snake_case      :							Union[str, Any]     				=						self.simulate_backprop(lowercase_					)
             ema_unet.step(unet_step_two.parameters()					)
             _snake_case      :							Union[str, Any]     				=						ema_unet.shadow_params

             for step_one, step_two in zip(lowercase_     ,  lowercase_					):
                    assert ~torch.allclose(lowercase_     ,  lowercase_					)



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



             '''simple docstring'''

             _snake_case				,    _snake_case      :							Optional[int]     				=						self.get_models(decay=0.0					)
             _snake_case      :							Tuple     				=						self.simulate_backprop(lowercase_					)
             ema_unet.step(unet_step_one.parameters()					)
             _snake_case      :							Any     				=						ema_unet.shadow_params

             _snake_case      :							Optional[Any]     				=						self.simulate_backprop(lowercase_					)
             ema_unet.step(unet_step_two.parameters()					)
             _snake_case      :							Dict     				=						ema_unet.shadow_params

             for step_one, step_two in zip(lowercase_     ,  lowercase_					):
                    assert torch.allclose(lowercase_     ,  lowercase_					)



      @skip_mps
      def    __a (					self					)      ->   Union[str, Any]:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							Tuple     				=						self.get_models()
             _snake_case				,    _snake_case				,    _snake_case      :							str     				=						self.get_dummy_inputs()

             with tempfile.TemporaryDirectory() as tmpdir:
                    ema_unet.save_pretrained(lowercase_					)
                    _snake_case      :							int     				=						UNetaDConditionModel.from_pretrained(lowercase_     ,  model_cls=lowercase_					)
                    _snake_case      :							Tuple     				=						loaded_unet.to(unet.device					)

             # Since no EMA step has been performed the outputs should match.
             _snake_case      :							str     				=						unet(lowercase_     ,  lowercase_     ,  lowercase_					).sample
             _snake_case      :							int     				=						loaded_unet(lowercase_     ,  lowercase_     ,  lowercase_					).sample

             assert torch.allclose(lowercase_     ,  lowercase_     ,  atol=1E-4					)













import unittest

from transformers import load_tool
from transformers.tools.agent_types import AGENT_TYPE_MAPPING

from .test_tools_common import ToolTesterMixin, output_types

class 				A    (unittest.TestCase       ,__UpperCAmelCase				):



      def    __a (					self					)      ->   str:



             '''simple docstring'''

             _snake_case      :							List[Any]     				=						load_tool('''translation'''					)
             self.tool.setup()
             _snake_case      :							Any     				=						load_tool('''translation'''     ,  remote=lowercase_					)



      def    __a (					self					)      ->   Optional[int]:



             '''simple docstring'''

             _snake_case      :							Tuple     				=						self.tool('''Hey, what\'s up?'''     ,  src_lang='''English'''     ,  tgt_lang='''French'''					)
             self.assertEqual(lowercase_     ,  '''- Hé, comment ça va?'''					)



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



             '''simple docstring'''

             _snake_case      :							Optional[int]     				=						self.remote_tool('''Hey, what\'s up?'''     ,  src_lang='''English'''     ,  tgt_lang='''French'''					)
             self.assertEqual(lowercase_     ,  '''- Hé, comment ça va?'''					)



      def    __a (					self					)      ->   List[Any]:



             '''simple docstring'''

             _snake_case      :							Dict     				=						self.tool(text='''Hey, what\'s up?'''     ,  src_lang='''English'''     ,  tgt_lang='''French'''					)
             self.assertEqual(lowercase_     ,  '''- Hé, comment ça va?'''					)



      def    __a (					self					)      ->   Dict:



             '''simple docstring'''

             _snake_case      :							List[Any]     				=						self.remote_tool(text='''Hey, what\'s up?'''     ,  src_lang='''English'''     ,  tgt_lang='''French'''					)
             self.assertEqual(lowercase_     ,  '''- Hé, comment ça va?'''					)



      def    __a (					self					)      ->   str:



             '''simple docstring'''

             _snake_case      :							Optional[int]     				=						['''Hey, what\'s up?''', '''English''', '''Spanish''']
             _snake_case      :							Dict     				=						self.tool(*lowercase_					)

             # There is a single output
             if len(self.tool.outputs					) == 1:
                    _snake_case      :							Optional[Any]     				=						[outputs]

             self.assertListEqual(output_types(lowercase_					)     ,  self.tool.outputs					)



      def    __a (					self					)      ->   Tuple:



             '''simple docstring'''

             _snake_case      :							Union[str, Any]     				=						['''Hey, what\'s up?''', '''English''', '''Spanish''']
             _snake_case      :							Dict     				=						self.tool(*lowercase_					)

             if not isinstance(lowercase_     ,  lowercase_					):
                    _snake_case      :							Optional[Any]     				=						[outputs]

             self.assertEqual(len(lowercase_					)     ,  len(self.tool.outputs					)					)

             for output, output_type in zip(lowercase_     ,  self.tool.outputs					):
                    _snake_case      :							List[str]     				=						AGENT_TYPE_MAPPING[output_type]
                    self.assertTrue(isinstance(lowercase_     ,  lowercase_					)					)



      def    __a (					self					)      ->   List[Any]:



             '''simple docstring'''

             _snake_case      :							Dict     				=						['''Hey, what\'s up?''', '''English''', '''Spanish''']

             _snake_case      :							Any     				=						[]

             for _input, input_type in zip(lowercase_     ,  self.tool.inputs					):
                    if isinstance(lowercase_     ,  lowercase_					):
                           _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input					) for _input_type in input_type]					)
                    else:
                           _inputs.append(AGENT_TYPE_MAPPING[input_type](_input					)					)

        # Should not raise an error
             _snake_case      :							List[Any]     				=						self.tool(*lowercase_					)

             if not isinstance(lowercase_     ,  lowercase_					):
                    _snake_case      :							Any     				=						[outputs]

             self.assertEqual(len(lowercase_					)     ,  len(self.tool.outputs					)					)






