



"""simple docstring"""






import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import MODEL_MAPPING, PoolFormerConfig, PoolFormerForImageClassification, PoolFormerModel
    from transformers.models.poolformer.modeling_poolformer import POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import PoolFormerImageProcessor




class    __snake_case(					__A       ):




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			self.config_class(**self.inputs_dict			)
      self.parent.assertTrue(hasattr(A_    ,							'''hidden_sizes'''			)			)
      self.parent.assertTrue(hasattr(A_    ,							'''num_encoder_blocks'''			)			)




class    __snake_case:




    def __init__(   self    ,							A_    ,							A_=13    ,							A_=64    ,							A_=3    ,							A_=4    ,							A_=[2, 2, 2, 2]    ,							A_=[8, 4, 2, 1]    ,							A_=[16, 32, 64, 128]    ,							A_=[1, 4, 8, 16]    ,							A_=False    ,							A_=True    ,							A_="gelu"    ,							A_=0.1    ,							A_=0.02    ,							A_=3    ,							A_=None    ,							):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			parent
      _SCREAMING_SNAKE_CASE        =			batch_size
      _SCREAMING_SNAKE_CASE        =			image_size
      _SCREAMING_SNAKE_CASE        =			num_channels
      _SCREAMING_SNAKE_CASE        =			num_encoder_blocks
      _SCREAMING_SNAKE_CASE        =			sr_ratios
      _SCREAMING_SNAKE_CASE        =			depths
      _SCREAMING_SNAKE_CASE        =			hidden_sizes
      _SCREAMING_SNAKE_CASE        =			downsampling_rates
      _SCREAMING_SNAKE_CASE        =			is_training
      _SCREAMING_SNAKE_CASE        =			use_labels
      _SCREAMING_SNAKE_CASE        =			hidden_act
      _SCREAMING_SNAKE_CASE        =			hidden_dropout_prob
      _SCREAMING_SNAKE_CASE        =			initializer_range
      _SCREAMING_SNAKE_CASE        =			num_labels
      _SCREAMING_SNAKE_CASE        =			scope




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

      _SCREAMING_SNAKE_CASE        =			None
      if self.use_labels:
        _SCREAMING_SNAKE_CASE        =			ids_tensor([self.batch_size, self.image_size, self.image_size]    ,							self.num_labels			)

      _SCREAMING_SNAKE_CASE        =			PoolFormerConfig(
          image_size=self.image_size    ,							num_channels=self.num_channels    ,							num_encoder_blocks=self.num_encoder_blocks    ,							depths=self.depths    ,							hidden_sizes=self.hidden_sizes    ,							hidden_act=self.hidden_act    ,							hidden_dropout_prob=self.hidden_dropout_prob    ,							initializer_range=self.initializer_range    ,							)

      return config, pixel_values, labels




    def   A   (   self    ,							A_    ,							A_    ,							A_			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			PoolFormerModel(config=A_			)
      model.to(A_			)
      model.eval()
      _SCREAMING_SNAKE_CASE        =			model(A_			)
      _SCREAMING_SNAKE_CASE        =			_SCREAMING_SNAKE_CASE        =			self.image_size // 32.0
      self.parent.assertEqual(
          result.last_hidden_state.shape    ,							(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)			)




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			self.prepare_config_and_inputs()
      _SCREAMING_SNAKE_CASE    ,     _SCREAMING_SNAKE_CASE    ,     _SCREAMING_SNAKE_CASE        =			config_and_inputs
      _SCREAMING_SNAKE_CASE        =			{'''pixel_values''': pixel_values}
      return config, inputs_dict




@require_torch
class    __snake_case(					__A			,			__A			,			unittest.TestCase       ):
    _A       = (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
    _A       = (
        {'''feature-extraction''': PoolFormerModel, '''image-classification''': PoolFormerForImageClassification}
        if is_torch_available()
        else {}
    )

    _A       = False
    _A       = False
    _A       = False
    _A       = False
    _A       = False




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			PoolFormerModelTester(self			)
      _SCREAMING_SNAKE_CASE        =			PoolFormerConfigTester(self    ,							config_class=A_			)




    def   A   (   self			):





      '''simple docstring'''



      self.config_tester.run_common_tests()




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A_			)




    @unittest.skip('''PoolFormer does not use inputs_embeds'''			)
    def   A   (   self			):





      '''simple docstring'''



      pass




    @unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'''			)
    def   A   (   self			):





      '''simple docstring'''



      pass




    def   A   (   self			):





      '''simple docstring'''



      def check_hidden_states_output(A_    ,							A_    ,							A_			):
        _SCREAMING_SNAKE_CASE        =			model_class(A_			)
        model.to(A_			)
        model.eval()

        with torch.no_grad():
          _SCREAMING_SNAKE_CASE        =			model(**self._prepare_for_class(A_    ,							A_			)			)

        _SCREAMING_SNAKE_CASE        =			outputs.hidden_states

        _SCREAMING_SNAKE_CASE        =			self.model_tester.num_encoder_blocks
        self.assertEqual(len(A_			)    ,							A_			)

        # verify the first hidden states (first block)
        self.assertListEqual(
            list(hidden_states[0].shape[-3:]			)    ,							[
                self.model_tester.hidden_sizes[0],
                self.model_tester.image_size // 4,
                self.model_tester.image_size // 4,
            ]    ,							)

      _SCREAMING_SNAKE_CASE    ,     _SCREAMING_SNAKE_CASE        =			self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        _SCREAMING_SNAKE_CASE        =			True
        check_hidden_states_output(A_    ,							A_    ,							A_			)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        _SCREAMING_SNAKE_CASE        =			True

        check_hidden_states_output(A_    ,							A_    ,							A_			)




    def   A   (   self			):





      '''simple docstring'''



      if not self.model_tester.is_training:
        return

      _SCREAMING_SNAKE_CASE    ,     _SCREAMING_SNAKE_CASE        =			self.model_tester.prepare_config_and_inputs_for_common()
      _SCREAMING_SNAKE_CASE        =			True

      for model_class in self.all_model_classes:
        if model_class in get_values(A_			):
          continue
        _SCREAMING_SNAKE_CASE        =			model_class(A_			)
        model.to(A_			)
        model.train()
        _SCREAMING_SNAKE_CASE        =			self._prepare_for_class(A_    ,							A_    ,							return_labels=A_			)
        _SCREAMING_SNAKE_CASE        =			model(**A_			).loss
        loss.backward()




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE    ,     _SCREAMING_SNAKE_CASE        =			self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        _SCREAMING_SNAKE_CASE        =			model_class(A_			)
        _SCREAMING_SNAKE_CASE        =			inspect.signature(model.forward			)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        _SCREAMING_SNAKE_CASE        =			[*signature.parameters.keys()]

        _SCREAMING_SNAKE_CASE        =			['''pixel_values''']
        self.assertListEqual(arg_names[:1]    ,							A_			)




    @slow
    def   A   (   self			):





      '''simple docstring'''



      for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _SCREAMING_SNAKE_CASE        =			PoolFormerModel.from_pretrained(A_			)
        self.assertIsNotNone(A_			)



def 							A__ (     ):


  '''simple docstring'''


  _SCREAMING_SNAKE_CASE        =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''    )
  return image







@require_torch
class    __snake_case(					unittest.TestCase       ):




    @slow
    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			PoolFormerImageProcessor()
      _SCREAMING_SNAKE_CASE        =			PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''			).to(A_			)

      _SCREAMING_SNAKE_CASE        =			image_processor(images=prepare_img()    ,							return_tensors='''pt'''			).to(A_			)

      # forward pass
      with torch.no_grad():
        _SCREAMING_SNAKE_CASE        =			model(**A_			)

      # verify the logits
      _SCREAMING_SNAKE_CASE        =			torch.Size((1, 1_000)			)
      self.assertEqual(outputs.logits.shape    ,							A_			)

      _SCREAMING_SNAKE_CASE        =			torch.tensor([-0.6_113, 0.1_685, -0.0_492]			).to(A_			)
      self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,							A_    ,							atol=1e-4			)			)





"""simple docstring"""






import unittest

import numpy as np
import torch

from diffusers import DDPMPipeline, DDPMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device


enable_full_determinism()




class    __snake_case(					unittest.TestCase       ):




    @property
    def   A   (   self			):





      '''simple docstring'''



      torch.manual_seed(0			)
      _SCREAMING_SNAKE_CASE        =			UNetaDModel(
          block_out_channels=(32, 64)    ,							layers_per_block=2    ,							sample_size=32    ,							in_channels=3    ,							out_channels=3    ,							down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')    ,							up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')    ,							)
      return model




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			'''cpu'''
      _SCREAMING_SNAKE_CASE        =			self.dummy_uncond_unet
      _SCREAMING_SNAKE_CASE        =			DDPMScheduler()

      _SCREAMING_SNAKE_CASE        =			DDPMPipeline(unet=A_    ,							scheduler=A_			)
      ddpm.to(A_			)
      ddpm.set_progress_bar_config(disable=A_			)

      _SCREAMING_SNAKE_CASE        =			torch.Generator(device=A_			).manual_seed(0			)
      _SCREAMING_SNAKE_CASE        =			ddpm(generator=A_    ,							num_inference_steps=2    ,							output_type='''numpy'''			).images

      _SCREAMING_SNAKE_CASE        =			torch.Generator(device=A_			).manual_seed(0			)
      _SCREAMING_SNAKE_CASE        =			ddpm(generator=A_    ,							num_inference_steps=2    ,							output_type='''numpy'''    ,							return_dict=A_			)[0]

      _SCREAMING_SNAKE_CASE        =			image[0, -3:, -3:, -1]
      _SCREAMING_SNAKE_CASE        =			image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 32, 32, 3)
      _SCREAMING_SNAKE_CASE        =			np.array(
          [9.956e-01, 5.785e-01, 4.675e-01, 9.930e-01, 0.0, 1.000, 1.199e-03, 2.648e-04, 5.101e-04]			)

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




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			self.dummy_uncond_unet
      _SCREAMING_SNAKE_CASE        =			DDPMScheduler(prediction_type='''sample'''			)

      _SCREAMING_SNAKE_CASE        =			DDPMPipeline(unet=A_    ,							scheduler=A_			)
      ddpm.to(A_			)
      ddpm.set_progress_bar_config(disable=A_			)

      _SCREAMING_SNAKE_CASE        =			torch.manual_seed(0			)
      _SCREAMING_SNAKE_CASE        =			ddpm(generator=A_    ,							num_inference_steps=2    ,							output_type='''numpy'''			).images

      _SCREAMING_SNAKE_CASE        =			torch.manual_seed(0			)
      _SCREAMING_SNAKE_CASE        =			ddpm(generator=A_    ,							num_inference_steps=2    ,							output_type='''numpy'''			)[0]

      _SCREAMING_SNAKE_CASE        =			image[0, -3:, -3:, -1]
      _SCREAMING_SNAKE_CASE        =			image_eps[0, -3:, -3:, -1]

      assert image.shape == (1, 32, 32, 3)
      _SCREAMING_SNAKE_CASE        =			1e-2 if torch_device != '''mps''' else 3e-2
      assert np.abs(image_slice.flatten() - image_eps_slice.flatten()			).max() < tolerance




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




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			'''google/ddpm-cifar10-32'''

      _SCREAMING_SNAKE_CASE        =			UNetaDModel.from_pretrained(A_			)
      _SCREAMING_SNAKE_CASE        =			DDPMScheduler.from_pretrained(A_			)

      _SCREAMING_SNAKE_CASE        =			DDPMPipeline(unet=A_    ,							scheduler=A_			)
      ddpm.to(A_			)
      ddpm.set_progress_bar_config(disable=A_			)

      _SCREAMING_SNAKE_CASE        =			torch.manual_seed(0			)
      _SCREAMING_SNAKE_CASE        =			ddpm(generator=A_    ,							output_type='''numpy'''			).images

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

      assert image.shape == (1, 32, 32, 3)
      _SCREAMING_SNAKE_CASE        =			np.array([0.4_200, 0.3_588, 0.1_939, 0.3_847, 0.3_382, 0.2_647, 0.4_155, 0.3_582, 0.3_385]			)
      assert np.abs(image_slice.flatten() - expected_slice			).max() < 1e-2
