
'''simple docstring'''



from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
						from PIL import Image

						from ..image_utils import load_image

if is_torch_available():
						from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
						from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
						from ..tf_utils import stable_softmax

_lowercase          =						logging.get_logger(__name__)




@add_end_docstrings(_SCREAMING_SNAKE_CASE					)
class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						def __init__(   self       ,  **_lowercase ):

												"""simple docstring"""



												super().__init__(**_lowercase )

												requires_backends(self       ,  """vision""" )
												self.check_model_type(
												    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
												    if self.framework == """tf"""
												    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING )




						def __call__(   self       ,  _lowercase       ,  **_lowercase ):

												"""simple docstring"""



												return super().__call__(_lowercase       ,  **_lowercase )




						def    _lowercase      (   self       ,  **_lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					{}
												if "candidate_labels" in kwargs:
																		_lowerCAmelCase    		=					kwargs["""candidate_labels"""]
												if "hypothesis_template" in kwargs:
																		_lowerCAmelCase    		=					kwargs["""hypothesis_template"""]

												return preprocess_params, {}, {}




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase=None       ,  _lowercase="This is a photo of {}." ):

												"""simple docstring"""



												_lowerCAmelCase    		=					load_image(_lowercase )
												_lowerCAmelCase    		=					self.image_processor(images=[image]       ,  return_tensors=self.framework )
												_lowerCAmelCase    		=					candidate_labels
												_lowerCAmelCase    		=					[hypothesis_template.format(_lowercase ) for x in candidate_labels]
												_lowerCAmelCase    		=					self.tokenizer(_lowercase       ,  return_tensors=self.framework       ,  padding=_lowercase )
												_lowerCAmelCase    		=					[text_inputs]
												return inputs




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					model_inputs.pop("""candidate_labels""" )
												_lowerCAmelCase    		=					model_inputs.pop("""text_inputs""" )
												if isinstance(text_inputs[0]       ,  _lowercase ):
																		_lowerCAmelCase    		=					text_inputs[0]
												else:
																		# Batching case.
																		_lowerCAmelCase    		=					text_inputs[0][0]

												_lowerCAmelCase    		=					self.model(**_lowercase       ,  **_lowercase )

												_lowerCAmelCase    		=					{
												    """candidate_labels""": candidate_labels,
												    """logits""": outputs.logits_per_image,
												}
												return model_outputs




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					model_outputs.pop("""candidate_labels""" )
												_lowerCAmelCase    		=					model_outputs["""logits"""][0]
												if self.framework == "pt":
																		_lowerCAmelCase    		=					logits.softmax(dim=-1 ).squeeze(-1 )
																		_lowerCAmelCase    		=					probs.tolist()
																		if not isinstance(_lowercase       ,  _lowercase ):
																								_lowerCAmelCase    		=					[scores]
												elif self.framework == "tf":
																		_lowerCAmelCase    		=					stable_softmax(_lowercase       ,  axis=-1 )
																		_lowerCAmelCase    		=					probs.numpy().tolist()
												else:
																		raise ValueError(F'Unsupported framework: {self.framework}' )

												_lowerCAmelCase    		=					[
												    {"""score""": score, """label""": candidate_label}
												    for score, candidate_label in sorted(zip(_lowercase       ,  _lowercase )       ,  key=lambda _lowercase : -x[0] )
												]
												return result






import torch

from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):
						lowerCAmelCase__			      =(KDPMaDiscreteScheduler,)
						lowerCAmelCase__			      =10



						def 	__a					(			self	:   Dict					,							**snake_case__	:   str  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							{
								    'num_train_timesteps': 11_00,
								    'beta_start': 0.00_01,
								    'beta_end': 0.02,
								    'beta_schedule': 'linear',
								}

								config.update(**snake_case__  )
								return config



						def 	__a					(			self	:   str  ):

								"""simple docstring"""

								for timesteps in [10, 50, 1_00, 10_00]:
										self.check_over_configs(num_train_timesteps=snake_case__  )



						def 	__a					(			self	:   List[Any]  ):

								"""simple docstring"""

								for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01]					,							[0.00_02, 0.0_02, 0.02]  ):
										self.check_over_configs(beta_start=snake_case__					,							beta_end=snake_case__  )



						def 	__a					(			self	:   Optional[int]  ):

								"""simple docstring"""

								for schedule in ["linear", "scaled_linear"]:
										self.check_over_configs(beta_schedule=snake_case__  )



						def 	__a					(			self	:   Optional[Any]  ):

								"""simple docstring"""

								for prediction_type in ["epsilon", "v_prediction"]:
										self.check_over_configs(prediction_type=snake_case__  )



						def 	__a					(			self	:   Optional[Any]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							self.scheduler_classes[0]
								SCREAMING_SNAKE_CASE_					      =							self.get_scheduler_config(prediction_type='v_prediction'  )
								SCREAMING_SNAKE_CASE_					      =							scheduler_class(**snake_case__  )

								scheduler.set_timesteps(self.num_inference_steps  )

								SCREAMING_SNAKE_CASE_					      =							self.dummy_model()
								SCREAMING_SNAKE_CASE_					      =							self.dummy_sample_deter * scheduler.init_noise_sigma
								SCREAMING_SNAKE_CASE_					      =							sample.to(snake_case__  )

								for i, t in enumerate(scheduler.timesteps  ):
										SCREAMING_SNAKE_CASE_					      =							scheduler.scale_model_input(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							model(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							scheduler.step(snake_case__					,							snake_case__					,							snake_case__  )
										SCREAMING_SNAKE_CASE_					      =							output.prev_sample

								SCREAMING_SNAKE_CASE_					      =							torch.sum(torch.abs(snake_case__  )  )
								SCREAMING_SNAKE_CASE_					      =							torch.mean(torch.abs(snake_case__  )  )

								if torch_device in ["cpu", "mps"]:
										assert abs(result_sum.item() - 4.69_34e-07  ) < 1e-2
										assert abs(result_mean.item() - 6.11_12e-10  ) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 4.6_93_42_86_50_17_09_72e-07  ) < 1e-2
										assert abs(result_mean.item() - 0.00_02  ) < 1e-3



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

								"""simple docstring"""

								if torch_device == "mps":
										return
								SCREAMING_SNAKE_CASE_					      =							self.scheduler_classes[0]
								SCREAMING_SNAKE_CASE_					      =							self.get_scheduler_config()
								SCREAMING_SNAKE_CASE_					      =							scheduler_class(**snake_case__  )

								scheduler.set_timesteps(self.num_inference_steps  )

								SCREAMING_SNAKE_CASE_					      =							self.dummy_model()
								SCREAMING_SNAKE_CASE_					      =							self.dummy_sample_deter * scheduler.init_noise_sigma
								SCREAMING_SNAKE_CASE_					      =							sample.to(snake_case__  )

								for i, t in enumerate(scheduler.timesteps  ):
										SCREAMING_SNAKE_CASE_					      =							scheduler.scale_model_input(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							model(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							scheduler.step(snake_case__					,							snake_case__					,							snake_case__  )
										SCREAMING_SNAKE_CASE_					      =							output.prev_sample

								SCREAMING_SNAKE_CASE_					      =							torch.sum(torch.abs(snake_case__  )  )
								SCREAMING_SNAKE_CASE_					      =							torch.mean(torch.abs(snake_case__  )  )

								if torch_device in ["cpu", "mps"]:
										assert abs(result_sum.item() - 20.41_25  ) < 1e-2
										assert abs(result_mean.item() - 0.02_66  ) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 20.41_25  ) < 1e-2
										assert abs(result_mean.item() - 0.02_66  ) < 1e-3






						def 	__a					(			self	:   Optional[int]  ):

								"""simple docstring"""

								if torch_device == "mps":
										return
								SCREAMING_SNAKE_CASE_					      =							self.scheduler_classes[0]
								SCREAMING_SNAKE_CASE_					      =							self.get_scheduler_config()
								SCREAMING_SNAKE_CASE_					      =							scheduler_class(**snake_case__  )

								scheduler.set_timesteps(self.num_inference_steps					,							device=snake_case__  )

								SCREAMING_SNAKE_CASE_					      =							self.dummy_model()
								SCREAMING_SNAKE_CASE_					      =							self.dummy_sample_deter.to(snake_case__  ) * scheduler.init_noise_sigma

								for t in scheduler.timesteps:
										SCREAMING_SNAKE_CASE_					      =							scheduler.scale_model_input(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							model(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							scheduler.step(snake_case__					,							snake_case__					,							snake_case__  )
										SCREAMING_SNAKE_CASE_					      =							output.prev_sample

								SCREAMING_SNAKE_CASE_					      =							torch.sum(torch.abs(snake_case__  )  )
								SCREAMING_SNAKE_CASE_					      =							torch.mean(torch.abs(snake_case__  )  )

								if str(snake_case__  ).startswith('cpu'  ):
										# The following sum varies between 148 and 156 on mps. Why?
										assert abs(result_sum.item() - 20.41_25  ) < 1e-2
										assert abs(result_mean.item() - 0.02_66  ) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 20.41_25  ) < 1e-2
										assert abs(result_mean.item() - 0.02_66  ) < 1e-3