




'''simple docstring'''



import unittest

import torch

from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, slow, torch_device

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin







class 	lowercase_					(				lowerCAmelCase_  ,						lowerCAmelCase_  ,						unittest.TestCase     ):


   """simple docstring"""

   lowerCamelCase_       						=		UNetaDModel
   lowerCamelCase_       						=		'''sample'''



   @property
   def 							lowerCAmelCase_    (					self      :			int					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   4
        _SCREAMING_SNAKE_CASE =   1_4
        _SCREAMING_SNAKE_CASE =   1_6

        _SCREAMING_SNAKE_CASE =   floats_tensor((batch_size, num_features, seq_len)					).to(__a					)
        _SCREAMING_SNAKE_CASE =   torch.tensor([1_0] * batch_size					).to(__a					)

        return {"sample": noise, "timestep": time_step}



   @property
   def 							lowerCAmelCase_    (					self      :			str					):

        """simple docstring"""
        return (4, 1_4, 1_6)



   @property
   def 							lowerCAmelCase_    (					self      :			Tuple					):

        """simple docstring"""
        return (4, 1_4, 1_6)



   def 							lowerCAmelCase_    (					self      :			Tuple					):

        """simple docstring"""
        pass



   def 							lowerCAmelCase_    (					self      :			Optional[int]					):

        """simple docstring"""
        pass



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Any					):

        """simple docstring"""
        super().test_determinism()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Any					):

        """simple docstring"""
        super().test_outputs_equivalence()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			str					):

        """simple docstring"""
        super().test_from_save_pretrained()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Optional[int]					):

        """simple docstring"""
        super().test_from_save_pretrained_variant()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			List[Any]					):

        """simple docstring"""
        super().test_model_from_pretrained()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Tuple					):

        """simple docstring"""
        super().test_output()



   def 							lowerCAmelCase_    (					self      :			List[Any]					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   {
            'block_out_channels': (3_2, 6_4, 1_2_8, 2_5_6),
            'in_channels': 1_4,
            'out_channels': 1_4,
            'time_embedding_type': 'positional',
            'use_timestep_embedding': True,
            'flip_sin_to_cos': False,
            'freq_shift': 1.0,
            'out_block_type': 'OutConv1DBlock',
            'mid_block_type': 'MidResTemporalBlock1D',
            'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'),
            'up_block_types': ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D'),
            'act_fn': 'mish',
        }
        _SCREAMING_SNAKE_CASE =   self.dummy_input
        return init_dict, inputs_dict



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Tuple					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   UNetaDModel.from_pretrained(
            "bglick13/hopper-medium-v2-value-function-hor32"						,   output_loading_info=__a						,   subfolder="unet"					)
        self.assertIsNotNone(__a					)
        self.assertEqual(len(loading_info["missing_keys"]					)						,   0					)

        model.to(__a					)
        _SCREAMING_SNAKE_CASE =   model(**self.dummy_input					)

        assert image is not None, "Make sure output is not None"



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Dict					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   UNetaDModel.from_pretrained("bglick13/hopper-medium-v2-value-function-hor32"						,   subfolder="unet"					)
        torch.manual_seed(0					)
        if torch.cuda.is_available():
             torch.cuda.manual_seed_all(0					)

        _SCREAMING_SNAKE_CASE =   model.config.in_channels
        _SCREAMING_SNAKE_CASE =   1_6
        _SCREAMING_SNAKE_CASE =   torch.randn((1, seq_len, num_features)					).permute(
            0						,   2						,   1					)  # match original, we can update values and remove
        _SCREAMING_SNAKE_CASE =   torch.full((num_features,)						,   0					)

        with torch.no_grad():
             _SCREAMING_SNAKE_CASE =   model(__a						,   __a					).sample.permute(0						,   2						,   1					)

        _SCREAMING_SNAKE_CASE =   output[0, -3:, -3:].flatten()
        # fmt: off
        _SCREAMING_SNAKE_CASE =   torch.tensor([-2.1_3_7_1_7_2, 1.1_4_2_6_0_1_6, 0.3_6_8_8_6_8_7, -0.7_6_6_9_2_2, 0.7_3_0_3_1_4_6, 0.1_1_0_3_8_8_6_4, -0.4_7_6_0_6_3_3, 0.1_3_2_7_0_1_7_2, 0.0_2_5_9_1_3_4_8]					)
        # fmt: on
        self.assertTrue(torch.allclose(__a						,   __a						,   rtol=1e-3					)					)



   def 							lowerCAmelCase_    (					self      :			Tuple					):

        """simple docstring"""
        pass



   @slow
   def 							lowerCAmelCase_    (					self      :			Tuple					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   'harmonai/maestro-150k'
        _SCREAMING_SNAKE_CASE =   UNetaDModel.from_pretrained(__a						,   subfolder="unet"					)
        model.to(__a					)

        _SCREAMING_SNAKE_CASE =   6_5_5_3_6
        _SCREAMING_SNAKE_CASE =   torch.sin(torch.arange(__a					)[None, None, :].repeat(1						,   2						,   1					)					).to(__a					)
        _SCREAMING_SNAKE_CASE =   torch.tensor([1]					).to(__a					)

        with torch.no_grad():
             _SCREAMING_SNAKE_CASE =   model(__a						,   __a					).sample

        _SCREAMING_SNAKE_CASE =   output.abs().sum()
        _SCREAMING_SNAKE_CASE =   output.abs().max()

        assert (output_sum - 2_2_4.0_8_9_6).abs() < 0.5
        assert (output_max - 0.0_6_0_7).abs() < 4e-4







class 	lowercase_					(				lowerCAmelCase_  ,						lowerCAmelCase_  ,						unittest.TestCase     ):


   """simple docstring"""

   lowerCamelCase_       						=		UNetaDModel
   lowerCamelCase_       						=		'''sample'''



   @property
   def 							lowerCAmelCase_    (					self      :			List[str]					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   4
        _SCREAMING_SNAKE_CASE =   1_4
        _SCREAMING_SNAKE_CASE =   1_6

        _SCREAMING_SNAKE_CASE =   floats_tensor((batch_size, num_features, seq_len)					).to(__a					)
        _SCREAMING_SNAKE_CASE =   torch.tensor([1_0] * batch_size					).to(__a					)

        return {"sample": noise, "timestep": time_step}



   @property
   def 							lowerCAmelCase_    (					self      :			str					):

        """simple docstring"""
        return (4, 1_4, 1_6)



   @property
   def 							lowerCAmelCase_    (					self      :			int					):

        """simple docstring"""
        return (4, 1_4, 1)



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Optional[int]					):

        """simple docstring"""
        super().test_determinism()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			List[Any]					):

        """simple docstring"""
        super().test_outputs_equivalence()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Optional[int]					):

        """simple docstring"""
        super().test_from_save_pretrained()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			str					):

        """simple docstring"""
        super().test_from_save_pretrained_variant()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Tuple					):

        """simple docstring"""
        super().test_model_from_pretrained()



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			int					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   self.prepare_init_args_and_inputs_for_common()
        _SCREAMING_SNAKE_CASE =   self.model_class(**__a					)
        model.to(__a					)
        model.eval()

        with torch.no_grad():
             _SCREAMING_SNAKE_CASE =   model(**__a					)

             if isinstance(__a						,   __a					):
                  _SCREAMING_SNAKE_CASE =   output.sample

        self.assertIsNotNone(__a					)
        _SCREAMING_SNAKE_CASE =   torch.Size((inputs_dict["sample"].shape[0], 1)					)
        self.assertEqual(output.shape						,   __a						,   "Input and output shapes do not match"					)



   def 							lowerCAmelCase_    (					self      :			List[str]					):

        """simple docstring"""
        pass



   def 							lowerCAmelCase_    (					self      :			List[Any]					):

        """simple docstring"""
        pass



   def 							lowerCAmelCase_    (					self      :			Tuple					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   {
            'in_channels': 1_4,
            'out_channels': 1_4,
            'down_block_types': ['DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'],
            'up_block_types': [],
            'out_block_type': 'ValueFunction',
            'mid_block_type': 'ValueFunctionMidBlock1D',
            'block_out_channels': [3_2, 6_4, 1_2_8, 2_5_6],
            'layers_per_block': 1,
            'downsample_each_block': True,
            'use_timestep_embedding': True,
            'freq_shift': 1.0,
            'flip_sin_to_cos': False,
            'time_embedding_type': 'positional',
            'act_fn': 'mish',
        }
        _SCREAMING_SNAKE_CASE =   self.dummy_input
        return init_dict, inputs_dict



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Optional[int]					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   UNetaDModel.from_pretrained(
            "bglick13/hopper-medium-v2-value-function-hor32"						,   output_loading_info=__a						,   subfolder="value_function"					)
        self.assertIsNotNone(__a					)
        self.assertEqual(len(vf_loading_info["missing_keys"]					)						,   0					)

        value_function.to(__a					)
        _SCREAMING_SNAKE_CASE =   value_function(**self.dummy_input					)

        assert image is not None, "Make sure output is not None"



   @unittest.skipIf(torch_device == "mps"						,   "mish op not supported in MPS"					)
   def 							lowerCAmelCase_    (					self      :			Optional[int]					):

        """simple docstring"""
        _SCREAMING_SNAKE_CASE =   UNetaDModel.from_pretrained(
            "bglick13/hopper-medium-v2-value-function-hor32"						,   output_loading_info=__a						,   subfolder="value_function"					)
        torch.manual_seed(0					)
        if torch.cuda.is_available():
             torch.cuda.manual_seed_all(0					)

        _SCREAMING_SNAKE_CASE =   value_function.config.in_channels
        _SCREAMING_SNAKE_CASE =   1_4
        _SCREAMING_SNAKE_CASE =   torch.randn((1, seq_len, num_features)					).permute(
            0						,   2						,   1					)  # match original, we can update values and remove
        _SCREAMING_SNAKE_CASE =   torch.full((num_features,)						,   0					)

        with torch.no_grad():
             _SCREAMING_SNAKE_CASE =   value_function(__a						,   __a					).sample

        # fmt: off
        _SCREAMING_SNAKE_CASE =   torch.tensor([1_6_5.2_5] * seq_len					)
        # fmt: on
        self.assertTrue(torch.allclose(__a						,   __a						,   rtol=1e-3					)					)



   def 							lowerCAmelCase_    (					self      :			str					):

        """simple docstring"""
        pass







'''simple docstring'''



import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image
else:







 class 	lowercase_					:


    """simple docstring"""

    @staticmethod
    def 							lowerCAmelCase_    (					*__lowerCamelCase      :			Union[str, Any]						,   **__lowerCamelCase      :			str					):

       """simple docstring"""
       pass







@is_pipeline_test
@require_torch_or_tf
@require_vision
class 	lowercase_					(				unittest.TestCase     ):


   """simple docstring"""

   lowerCamelCase_       						=		MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
   lowerCamelCase_       						=		TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING



   def 							lowerCAmelCase_    (					self      :			Any						,   __lowerCamelCase      :			Tuple						,   __lowerCamelCase      :			Dict						,   __lowerCamelCase      :			Optional[Any]					):

      """simple docstring"""
      _SCREAMING_SNAKE_CASE =   ImageClassificationPipeline(model=__lowerCamelCase						,   image_processor=__lowerCamelCase						,   top_k=2					)
      _SCREAMING_SNAKE_CASE =   [
          Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					),
          "http://images.cocodataset.org/val2017/000000039769.jpg",
      ]
      return image_classifier, examples



   def 							lowerCAmelCase_    (					self      :			Any						,   __lowerCamelCase      :			Optional[Any]						,   __lowerCamelCase      :			Tuple					):

      """simple docstring"""
      _SCREAMING_SNAKE_CASE =   image_classifier("./tests/fixtures/tests_samples/COCO/000000039769.png"					)

      self.assertEqual(
          __lowerCamelCase						,   [
              {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
              {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
          ]						,   )

      import datasets

      _SCREAMING_SNAKE_CASE =   datasets.load_dataset("hf-internal-testing/fixtures_image_utils"						,   "image"						,   split="test"					)

      # Accepts URL + PIL.Image + lists
      _SCREAMING_SNAKE_CASE =   image_classifier(
          [
              Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					),
              "http://images.cocodataset.org/val2017/000000039769.jpg",
              # RGBA
              dataset[0]["file"],
              # LA
              dataset[1]["file"],
              # L
              dataset[2]["file"],
          ]					)
      self.assertEqual(
          __lowerCamelCase						,   [
              [
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
              ],
              [
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
              ],
              [
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
              ],
              [
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
              ],
              [
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
                  {"score": ANY(__lowerCamelCase					), "label": ANY(__lowerCamelCase					)},
              ],
          ]						,   )



   @require_torch
   def 							lowerCAmelCase_    (					self      :			Dict					):

      """simple docstring"""
      _SCREAMING_SNAKE_CASE =   "hf-internal-testing/tiny-random-vit"
      _SCREAMING_SNAKE_CASE =   pipeline("image-classification"						,   model=__lowerCamelCase					)

      _SCREAMING_SNAKE_CASE =   image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"					)
      self.assertEqual(
          nested_simplify(__lowerCamelCase						,   decimals=4					)						,   [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}]						,   )

      _SCREAMING_SNAKE_CASE =   image_classifier(
          [
              "http://images.cocodataset.org/val2017/000000039769.jpg",
              "http://images.cocodataset.org/val2017/000000039769.jpg",
          ]						,   top_k=2						,   )
      self.assertEqual(
          nested_simplify(__lowerCamelCase						,   decimals=4					)						,   [
              [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
              [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
          ]						,   )



   @require_tf
   def 							lowerCAmelCase_    (					self      :			Optional[Any]					):

      """simple docstring"""
      _SCREAMING_SNAKE_CASE =   "hf-internal-testing/tiny-random-vit"
      _SCREAMING_SNAKE_CASE =   pipeline("image-classification"						,   model=__lowerCamelCase						,   framework="tf"					)

      _SCREAMING_SNAKE_CASE =   image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"					)
      self.assertEqual(
          nested_simplify(__lowerCamelCase						,   decimals=4					)						,   [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}]						,   )

      _SCREAMING_SNAKE_CASE =   image_classifier(
          [
              "http://images.cocodataset.org/val2017/000000039769.jpg",
              "http://images.cocodataset.org/val2017/000000039769.jpg",
          ]						,   top_k=2						,   )
      self.assertEqual(
          nested_simplify(__lowerCamelCase						,   decimals=4					)						,   [
              [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
              [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
          ]						,   )



   def 							lowerCAmelCase_    (					self      :			Any					):

      """simple docstring"""
      _SCREAMING_SNAKE_CASE =   PreTrainedTokenizer()

      # Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
      _SCREAMING_SNAKE_CASE =   pipeline(
          "image-classification"						,   model="hf-internal-testing/tiny-random-vit"						,   tokenizer=__lowerCamelCase					)

      self.assertIs(image_classifier.tokenizer						,   __lowerCamelCase					)



   @slow
   @require_torch
   def 							lowerCAmelCase_    (					self      :			List[str]					):

      """simple docstring"""
      # Perceiver is not tested by `run_pipeline_test` properly.
      # That is because the type of feature_extractor and model preprocessor need to be kept
      # in sync, which is not the case in the current design
      _SCREAMING_SNAKE_CASE =   pipeline("image-classification"						,   model="deepmind/vision-perceiver-conv"					)
      _SCREAMING_SNAKE_CASE =   image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"					)
      self.assertEqual(
          nested_simplify(__lowerCamelCase						,   decimals=4					)						,   [
              {"score": 0.4_3_8_5, "label": "tabby, tabby cat"},
              {"score": 0.3_2_1, "label": "tiger cat"},
              {"score": 0.0_5_0_2, "label": "Egyptian cat"},
              {"score": 0.0_1_3_7, "label": "crib, cot"},
              {"score": 0.0_0_7, "label": "radiator"},
          ]						,   )

      _SCREAMING_SNAKE_CASE =   pipeline("image-classification"						,   model="deepmind/vision-perceiver-fourier"					)
      _SCREAMING_SNAKE_CASE =   image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"					)
      self.assertEqual(
          nested_simplify(__lowerCamelCase						,   decimals=4					)						,   [
              {"score": 0.5_6_5_8, "label": "tabby, tabby cat"},
              {"score": 0.1_3_0_9, "label": "tiger cat"},
              {"score": 0.0_7_2_2, "label": "Egyptian cat"},
              {"score": 0.0_7_0_7, "label": "remote control, remote"},
              {"score": 0.0_0_8_2, "label": "computer keyboard, keypad"},
          ]						,   )

      _SCREAMING_SNAKE_CASE =   pipeline("image-classification"						,   model="deepmind/vision-perceiver-learned"					)
      _SCREAMING_SNAKE_CASE =   image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"					)
      self.assertEqual(
          nested_simplify(__lowerCamelCase						,   decimals=4					)						,   [
              {"score": 0.3_0_2_2, "label": "tabby, tabby cat"},
              {"score": 0.2_3_6_2, "label": "Egyptian cat"},
              {"score": 0.1_8_5_6, "label": "tiger cat"},
              {"score": 0.0_3_2_4, "label": "remote control, remote"},
              {"score": 0.0_0_9_6, "label": "quilt, comforter, comfort, puff"},
          ]						,   )

