


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      snake_case__	:
							@staticmethod
							def 			UpperCamelCase_    (	*_UpperCAmelCase  ,   **_UpperCAmelCase   ):




													"""simple docstring"""




													pass



@is_pipeline_test
@require_torch_or_tf
@require_vision
class      snake_case__	(   unittest.TestCase	):
				__lowerCAmelCase		=   MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
				__lowerCAmelCase		=   TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				Dict				=   ImageClassificationPipeline(model=_UpperCAmelCase  ,   image_processor=_UpperCAmelCase  ,   top_k=2   )
										__magic_name__					:				str				=   [
										    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   ),
										    'http://images.cocodataset.org/val2017/000000039769.jpg',
										]
										return image_classifier, examples
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				int				=   image_classifier('./tests/fixtures/tests_samples/COCO/000000039769.png'   )

										self.assertEqual(
										    _UpperCAmelCase  ,   [
										        {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										        {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										    ]  ,   )

										import datasets

										__magic_name__					:				Optional[Any]				=   datasets.load_dataset('hf-internal-testing/fixtures_image_utils'  ,   'image'  ,   split='test'   )

										# Accepts URL + PIL.Image + lists
										__magic_name__					:				List[Any]				=   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(
										    _UpperCAmelCase  ,   [
										        [
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										        ],
										        [
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										        ],
										        [
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										        ],
										        [
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										        ],
										        [
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										            {'score': ANY(_UpperCAmelCase   ), 'label': ANY(_UpperCAmelCase   )},
										        ],
										    ]  ,   )
				@require_torch
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Union[str, Any]				=   'hf-internal-testing/tiny-random-vit'
										__magic_name__					:				str				=   pipeline('image-classification'  ,   model=_UpperCAmelCase   )

										__magic_name__					:				str				=   image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'   )
										self.assertEqual(
										    nested_simplify(_UpperCAmelCase  ,   decimals=4   )  ,   [{'label': 'LABEL_1', 'score': 0.574}, {'label': 'LABEL_0', 'score': 0.426}]  ,   )

										__magic_name__					:				Dict				=   image_classifier(
										    [
										        'http://images.cocodataset.org/val2017/000000039769.jpg',
										        'http://images.cocodataset.org/val2017/000000039769.jpg',
										    ]  ,   top_k=2  ,   )
										self.assertEqual(
										    nested_simplify(_UpperCAmelCase  ,   decimals=4   )  ,   [
										        [{'label': 'LABEL_1', 'score': 0.574}, {'label': 'LABEL_0', 'score': 0.426}],
										        [{'label': 'LABEL_1', 'score': 0.574}, {'label': 'LABEL_0', 'score': 0.426}],
										    ]  ,   )
				@require_tf
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				List[str]				=   'hf-internal-testing/tiny-random-vit'
										__magic_name__					:				Optional[int]				=   pipeline('image-classification'  ,   model=_UpperCAmelCase  ,   framework='tf'   )

										__magic_name__					:				Any				=   image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'   )
										self.assertEqual(
										    nested_simplify(_UpperCAmelCase  ,   decimals=4   )  ,   [{'label': 'LABEL_1', 'score': 0.574}, {'label': 'LABEL_0', 'score': 0.426}]  ,   )

										__magic_name__					:				Dict				=   image_classifier(
										    [
										        'http://images.cocodataset.org/val2017/000000039769.jpg',
										        'http://images.cocodataset.org/val2017/000000039769.jpg',
										    ]  ,   top_k=2  ,   )
										self.assertEqual(
										    nested_simplify(_UpperCAmelCase  ,   decimals=4   )  ,   [
										        [{'label': 'LABEL_1', 'score': 0.574}, {'label': 'LABEL_0', 'score': 0.426}],
										        [{'label': 'LABEL_1', 'score': 0.574}, {'label': 'LABEL_0', 'score': 0.426}],
										    ]  ,   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Tuple				=   PreTrainedTokenizer()

										# Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
										__magic_name__					:				Optional[Any]				=   pipeline(
										    'image-classification'  ,   model='hf-internal-testing/tiny-random-vit'  ,   tokenizer=_UpperCAmelCase   )

										self.assertIs(image_classifier.tokenizer  ,   _UpperCAmelCase   )





				@slow
				@require_torch
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Dict				=   pipeline('image-classification'  ,   model='deepmind/vision-perceiver-conv'   )
										__magic_name__					:				List[str]				=   image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'   )
										self.assertEqual(
										    nested_simplify(_UpperCAmelCase  ,   decimals=4   )  ,   [
										        {'score': 0.4385, 'label': 'tabby, tabby cat'},
										        {'score': 0.321, 'label': 'tiger cat'},
										        {'score': 0.0502, 'label': 'Egyptian cat'},
										        {'score': 0.0137, 'label': 'crib, cot'},
										        {'score': 0.007, 'label': 'radiator'},
										    ]  ,   )

										__magic_name__					:				int				=   pipeline('image-classification'  ,   model='deepmind/vision-perceiver-fourier'   )
										__magic_name__					:				Optional[int]				=   image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'   )
										self.assertEqual(
										    nested_simplify(_UpperCAmelCase  ,   decimals=4   )  ,   [
										        {'score': 0.5658, 'label': 'tabby, tabby cat'},
										        {'score': 0.1309, 'label': 'tiger cat'},
										        {'score': 0.0722, 'label': 'Egyptian cat'},
										        {'score': 0.0707, 'label': 'remote control, remote'},
										        {'score': 0.0082, 'label': 'computer keyboard, keypad'},
										    ]  ,   )

										__magic_name__					:				Any				=   pipeline('image-classification'  ,   model='deepmind/vision-perceiver-learned'   )
										__magic_name__					:				str				=   image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'   )
										self.assertEqual(
										    nested_simplify(_UpperCAmelCase  ,   decimals=4   )  ,   [
										        {'score': 0.3022, 'label': 'tabby, tabby cat'},
										        {'score': 0.2362, 'label': 'Egyptian cat'},
										        {'score': 0.1856, 'label': 'tiger cat'},
										        {'score': 0.0324, 'label': 'remote control, remote'},
										        {'score': 0.0096, 'label': 'quilt, comforter, comfort, puff'},
										    ]  ,   )






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      snake_case__	(   unittest.TestCase	):
				__lowerCAmelCase		=   '''hf-internal-testing/tiny-stable-diffusion-pipe'''
				__lowerCAmelCase		=   1
				__lowerCAmelCase		=   77
				__lowerCAmelCase		=   32
				__lowerCAmelCase		=   4
				__lowerCAmelCase		=   __lowerCAmelCase		=   64
				__lowerCAmelCase		=   torch.manual_seed(0	)
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase=0.9999   ):




										"""simple docstring"""




										__magic_name__					:				List[Any]				=   UNetaDConditionModel.from_pretrained(self.model_id  ,   subfolder='unet'   )
										__magic_name__					:				int				=   unet.to(_UpperCAmelCase   )
										__magic_name__					:				Optional[int]				=   EMAModel(unet.parameters()  ,   decay=_UpperCAmelCase  ,   model_cls=_UpperCAmelCase  ,   model_config=unet.config   )
										return unet, ema_unet
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				List[str]				=   torch.randn(
										    self.batch_size  ,   self.num_in_channels  ,   self.latent_height  ,   self.latent_width  ,   generator=self.generator   ).to(_UpperCAmelCase   )
										__magic_name__					:				List[str]				=   torch.randint(0  ,   1000  ,   size=(self.batch_size,)  ,   generator=self.generator   ).to(_UpperCAmelCase   )
										__magic_name__					:				Any				=   torch.randn(
										    self.batch_size  ,   self.prompt_length  ,   self.text_encoder_hidden_dim  ,   generator=self.generator   ).to(_UpperCAmelCase   )
										return noisy_latents, timesteps, encoder_hidden_states
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				Any				=   {}
										for k, param in unet.state_dict().items():
																__magic_name__					:				str				=   torch.randn_like(_UpperCAmelCase   ) + (param * torch.randn_like(_UpperCAmelCase   ))
																updated_state_dict.update({k: updated_param}   )
										unet.load_state_dict(_UpperCAmelCase   )
										return unet
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__		,			__magic_name__					:				int				=   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 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__		,			__magic_name__					:				Union[str, Any]				=   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()   )
										__magic_name__					:				Any				=   list(unet.parameters()   )
										for s_param, param in zip(ema_unet.shadow_params  ,   _UpperCAmelCase   ):
																assert torch.allclose(_UpperCAmelCase  ,   _UpperCAmelCase   )

										# 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  ,   _UpperCAmelCase   ):
																assert torch.allclose(_UpperCAmelCase  ,   _UpperCAmelCase   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__		,			__magic_name__					:				Optional[Any]				=   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.
										__magic_name__					:				Any				=   self.simulate_backprop(_UpperCAmelCase   )

										# 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.
										__magic_name__					:				Any				=   list(unet_pseudo_updated_step_one.parameters()   )
										for s_param, param in zip(ema_unet.shadow_params  ,   _UpperCAmelCase   ):
																assert ~torch.allclose(_UpperCAmelCase  ,   _UpperCAmelCase   )

										# 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  ,   _UpperCAmelCase   ):
																assert ~torch.allclose(_UpperCAmelCase  ,   _UpperCAmelCase   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__		,			__magic_name__					:				List[str]				=   self.get_models()

										# First backprop + EMA
										__magic_name__					:				int				=   self.simulate_backprop(_UpperCAmelCase   )
										ema_unet.step(unet_step_one.parameters()   )
										__magic_name__					:				Any				=   ema_unet.shadow_params

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

										for step_one, step_two in zip(_UpperCAmelCase  ,   _UpperCAmelCase   ):
																assert ~torch.allclose(_UpperCAmelCase  ,   _UpperCAmelCase   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__		,			__magic_name__					:				Optional[Any]				=   self.get_models(decay=0.0   )
										__magic_name__					:				str				=   self.simulate_backprop(_UpperCAmelCase   )
										ema_unet.step(unet_step_one.parameters()   )
										__magic_name__					:				List[Any]				=   ema_unet.shadow_params

										__magic_name__					:				Optional[Any]				=   self.simulate_backprop(_UpperCAmelCase   )
										ema_unet.step(unet_step_two.parameters()   )
										__magic_name__					:				Optional[Any]				=   ema_unet.shadow_params

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





				@skip_mps
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__		,			__magic_name__					:				Optional[int]				=   self.get_models()
										__magic_name__		,			__magic_name__		,			__magic_name__					:				str				=   self.get_dummy_inputs()

										with tempfile.TemporaryDirectory() as tmpdir:
																ema_unet.save_pretrained(_UpperCAmelCase   )
																__magic_name__					:				Optional[int]				=   UNetaDConditionModel.from_pretrained(_UpperCAmelCase  ,   model_cls=_UpperCAmelCase   )
																__magic_name__					:				str				=   loaded_unet.to(unet.device   )

										# Since no EMA step has been performed the outputs should match.
										__magic_name__					:				Union[str, Any]				=   unet(_UpperCAmelCase  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ).sample
										__magic_name__					:				List[Any]				=   loaded_unet(_UpperCAmelCase  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ).sample

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


