


"""simple docstring"""



import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
__snake_case       =       {"""LayoutLMv2Config""", """LayoutLMv3Config"""}







@is_pipeline_test
class _lowerCAmelCase							( unittest.TestCase      ):
   __UpperCAmelCase					:			List[str]				    =    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
   __UpperCAmelCase					:			str				    =    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

   if model_mapping is not None:
      __UpperCAmelCase					:			int				    =    {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
   if tf_model_mapping is not None:
      __UpperCAmelCase					:			int				    =    {
          config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
      }







   @require_torch
   def 					lowerCamelCase						(      self		)      ->						List[Any]:

       '''simple docstring'''




       snake_case       : Dict    =       pipeline(
           task="text-classification"		,      model="hf-internal-testing/tiny-random-distilbert"		,      framework="pt"		)

       snake_case       : int    =       text_classifier("This is great !"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "LABEL_0", "score": 0.504}]		)

       snake_case       : int    =       text_classifier("This is great !"		,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]		)

       snake_case       : Dict    =       text_classifier(["This is great !", "This is bad"]		,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      [
               [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
               [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
           ]		,      )

       snake_case       : Optional[Any]    =       text_classifier("This is great !"		,      top_k=1		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "LABEL_0", "score": 0.504}]		)

       # Legacy behavior
       snake_case       : Tuple    =       text_classifier("This is great !"		,      return_all_scores=UpperCamelCase__		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "LABEL_0", "score": 0.504}]		)

       snake_case       : Any    =       text_classifier("This is great !"		,      return_all_scores=UpperCamelCase__		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      [[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]]		)

       snake_case       : str    =       text_classifier(["This is great !", "Something else"]		,      return_all_scores=UpperCamelCase__		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      [
               [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
               [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
           ]		,      )

       snake_case       : str    =       text_classifier(["This is great !", "Something else"]		,      return_all_scores=UpperCamelCase__		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      [
               {"label": "LABEL_0", "score": 0.504},
               {"label": "LABEL_0", "score": 0.504},
           ]		,      )







   @require_torch
   def 					lowerCamelCase						(      self		)      ->						Any:

       '''simple docstring'''




       import torch

       snake_case       : List[Any]    =       pipeline(
           task="text-classification"		,      model="hf-internal-testing/tiny-random-distilbert"		,      framework="pt"		,      device=torch.device("cpu"		)		,      )

       snake_case       : int    =       text_classifier("This is great !"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "LABEL_0", "score": 0.504}]		)







   @require_tf
   def 					lowerCamelCase						(      self		)      ->						Optional[int]:

       '''simple docstring'''




       snake_case       : Any    =       pipeline(
           task="text-classification"		,      model="hf-internal-testing/tiny-random-distilbert"		,      framework="tf"		)

       snake_case       : Dict    =       text_classifier("This is great !"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "LABEL_0", "score": 0.504}]		)







   @slow
   @require_torch
   def 					lowerCamelCase						(      self		)      ->						List[str]:

       '''simple docstring'''




       snake_case       : int    =       pipeline("text-classification"		)

       snake_case       : List[str]    =       text_classifier("This is great !"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "POSITIVE", "score": 1.0}]		)
       snake_case       : Any    =       text_classifier("This is bad !"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "NEGATIVE", "score": 1.0}]		)
       snake_case       : Union[str, Any]    =       text_classifier("Birds are a type of animal"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "POSITIVE", "score": 0.988}]		)







   @slow
   @require_tf
   def 					lowerCamelCase						(      self		)      ->						List[Any]:

       '''simple docstring'''




       snake_case       : Optional[int]    =       pipeline("text-classification"		,      framework="tf"		)

       snake_case       : List[str]    =       text_classifier("This is great !"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "POSITIVE", "score": 1.0}]		)
       snake_case       : Tuple    =       text_classifier("This is bad !"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "NEGATIVE", "score": 1.0}]		)
       snake_case       : Optional[Any]    =       text_classifier("Birds are a type of animal"		)
       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": "POSITIVE", "score": 0.988}]		)







   def 					lowerCamelCase						(      self		,      UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)      ->						Any:

       '''simple docstring'''




       snake_case       : Dict    =       TextClassificationPipeline(model=UpperCamelCase__		,      tokenizer=UpperCamelCase__		)
       return text_classifier, ["HuggingFace is in", "This is another test"]







   def 					lowerCamelCase						(      self		,      UpperCamelCase__		,      UpperCamelCase__		)      ->						Dict:

       '''simple docstring'''




       snake_case       : Optional[Any]    =       text_classifier.model
       # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
       snake_case       : Optional[Any]    =       "HuggingFace is in"
       snake_case       : Optional[Any]    =       text_classifier(UpperCamelCase__		)

       self.assertEqual(nested_simplify(UpperCamelCase__		)		,      [{"label": ANY(UpperCamelCase__		), "score": ANY(UpperCamelCase__		)}]		)
       self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()		)

       snake_case       : Optional[int]    =       ["HuggingFace is in ", "Paris is in France"]
       snake_case       : List[Any]    =       text_classifier(UpperCamelCase__		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      [{"label": ANY(UpperCamelCase__		), "score": ANY(UpperCamelCase__		)}, {"label": ANY(UpperCamelCase__		), "score": ANY(UpperCamelCase__		)}]		,      )
       self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()		)
       self.assertTrue(outputs[1]["label"] in model.config.idalabel.values()		)

       # Forcing to get all results with `top_k=None`
       # This is NOT the legacy format
       snake_case       : List[str]    =       text_classifier(UpperCamelCase__		,      top_k=UpperCamelCase__		)
       snake_case       : List[str]    =       len(model.config.idalabel.values()		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      [[{"label": ANY(UpperCamelCase__		), "score": ANY(UpperCamelCase__		)}] * N, [{"label": ANY(UpperCamelCase__		), "score": ANY(UpperCamelCase__		)}] * N]		,      )

       snake_case       : Tuple    =       {"text": "HuggingFace is in ", "text_pair": "Paris is in France"}
       snake_case       : str    =       text_classifier(UpperCamelCase__		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      {"label": ANY(UpperCamelCase__		), "score": ANY(UpperCamelCase__		)}		,      )
       self.assertTrue(outputs["label"] in model.config.idalabel.values()		)

       # This might be used a text pair, but tokenizer + pipe interaction
       # makes it hard to understand that it's not using the pair properly
       # https://github.com/huggingface/transformers/issues/17305
       # We disabled this usage instead as it was outputting wrong outputs.
       snake_case       : List[Any]    =       [["HuggingFace is in ", "Paris is in France"]]
       with self.assertRaises(UpperCamelCase__		):
           text_classifier(UpperCamelCase__		)

       # This used to be valid for doing text pairs
       # We're keeping it working because of backward compatibility
       snake_case       : Dict    =       text_classifier([[["HuggingFace is in ", "Paris is in France"]]]		)
       self.assertEqual(
           nested_simplify(UpperCamelCase__		)		,      [{"label": ANY(UpperCamelCase__		), "score": ANY(UpperCamelCase__		)}]		,      )
       self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()		)









"""simple docstring"""



import torch

from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest







class _lowerCAmelCase							( snake_case_      ):
   __UpperCAmelCase					:			List[str]				    =    (KDPMaDiscreteScheduler,)
   __UpperCAmelCase					:			List[Any]				    =    10







   def 					lowerCamelCase						(      self		,      **UpperCamelCase__		)      ->						Optional[int]:

       '''simple docstring'''




       snake_case       : List[str]    =       {
           "num_train_timesteps": 1100,
           "beta_start": 0.0001,
           "beta_end": 0.02,
           "beta_schedule": "linear",
       }

       config.update(**UpperCamelCase__		)
       return config







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

       '''simple docstring'''




       for timesteps in [10, 50, 100, 1000]:
           self.check_over_configs(num_train_timesteps=UpperCamelCase__		)







   def 					lowerCamelCase						(      self		)      ->						str:

       '''simple docstring'''




       for beta_start, beta_end in zip([0.00001, 0.0001, 0.001]		,      [0.0002, 0.002, 0.02]		):
           self.check_over_configs(beta_start=UpperCamelCase__		,      beta_end=UpperCamelCase__		)







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

       '''simple docstring'''




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







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

       '''simple docstring'''




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







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

       '''simple docstring'''




       snake_case       : str    =       self.scheduler_classes[0]
       snake_case       : str    =       self.get_scheduler_config(prediction_type="v_prediction"		)
       snake_case       : Dict    =       scheduler_class(**UpperCamelCase__		)

       scheduler.set_timesteps(self.num_inference_steps		)

       snake_case       : List[Any]    =       self.dummy_model()
       snake_case       : List[str]    =       self.dummy_sample_deter * scheduler.init_noise_sigma
       snake_case       : Optional[Any]    =       sample.to(UpperCamelCase__		)

       for i, t in enumerate(scheduler.timesteps		):
           snake_case       : int    =       scheduler.scale_model_input(UpperCamelCase__		,      UpperCamelCase__		)

           snake_case       : int    =       model(UpperCamelCase__		,      UpperCamelCase__		)

           snake_case       : Optional[Any]    =       scheduler.step(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)
           snake_case       : Optional[Any]    =       output.prev_sample

       snake_case       : Optional[Any]    =       torch.sum(torch.abs(UpperCamelCase__		)		)
       snake_case       : Any    =       torch.mean(torch.abs(UpperCamelCase__		)		)

       if torch_device in ["cpu", "mps"]:
           assert abs(result_sum.item() - 4.6934e-07		) < 1e-2
           assert abs(result_mean.item() - 6.1112e-10		) < 1e-3
       else:
           # CUDA
           assert abs(result_sum.item() - 4.693_4286_5017_0972e-07		) < 1e-2
           assert abs(result_mean.item() - 0.0002		) < 1e-3







   def 					lowerCamelCase						(      self		)      ->						Dict:

       '''simple docstring'''




       if torch_device == "mps":
           return
       snake_case       : Optional[Any]    =       self.scheduler_classes[0]
       snake_case       : Optional[int]    =       self.get_scheduler_config()
       snake_case       : Dict    =       scheduler_class(**UpperCamelCase__		)

       scheduler.set_timesteps(self.num_inference_steps		)

       snake_case       : List[Any]    =       self.dummy_model()
       snake_case       : Union[str, Any]    =       self.dummy_sample_deter * scheduler.init_noise_sigma
       snake_case       : List[str]    =       sample.to(UpperCamelCase__		)

       for i, t in enumerate(scheduler.timesteps		):
           snake_case       : List[Any]    =       scheduler.scale_model_input(UpperCamelCase__		,      UpperCamelCase__		)

           snake_case       : Optional[int]    =       model(UpperCamelCase__		,      UpperCamelCase__		)

           snake_case       : Optional[int]    =       scheduler.step(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)
           snake_case       : int    =       output.prev_sample

       snake_case       : int    =       torch.sum(torch.abs(UpperCamelCase__		)		)
       snake_case       : Union[str, Any]    =       torch.mean(torch.abs(UpperCamelCase__		)		)

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







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

       '''simple docstring'''




       if torch_device == "mps":
           return
       snake_case       : Any    =       self.scheduler_classes[0]
       snake_case       : Any    =       self.get_scheduler_config()
       snake_case       : Union[str, Any]    =       scheduler_class(**UpperCamelCase__		)

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

       snake_case       : Optional[Any]    =       self.dummy_model()
       snake_case       : Optional[int]    =       self.dummy_sample_deter.to(UpperCamelCase__		) * scheduler.init_noise_sigma

       for t in scheduler.timesteps:
           snake_case       : Optional[Any]    =       scheduler.scale_model_input(UpperCamelCase__		,      UpperCamelCase__		)

           snake_case       : Any    =       model(UpperCamelCase__		,      UpperCamelCase__		)

           snake_case       : List[Any]    =       scheduler.step(UpperCamelCase__		,      UpperCamelCase__		,      UpperCamelCase__		)
           snake_case       : Dict    =       output.prev_sample

       snake_case       : Dict    =       torch.sum(torch.abs(UpperCamelCase__		)		)
       snake_case       : str    =       torch.mean(torch.abs(UpperCamelCase__		)		)

       if str(UpperCamelCase__		).startswith("cpu"		):
           # The following sum varies between 148 and 156 on mps. Why?
           assert abs(result_sum.item() - 20.4125		) < 1e-2
           assert abs(result_mean.item() - 0.0266		) < 1e-3
       else:
           # CUDA
           assert abs(result_sum.item() - 20.4125		) < 1e-2
           assert abs(result_mean.item() - 0.0266		) < 1e-3





