


"""simple docstring"""

import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    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.
UpperCAmelCase__  							={"LayoutLMv2Config", "LayoutLMv3Config"}





@is_pipeline_test
class    lowerCamelCase__						(		unittest.TestCase    ):
      a :     Dict											=		MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
      a :     List[str]											=		TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

      if model_mapping is not None:
            a :     List[Any]											=		{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
      if tf_model_mapping is not None:
            a :     Union[str, Any]											=		{
                config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
            }
      def SCREAMING_SNAKE_CASE_	(		self	:	Tuple      ,       A_	:	Tuple      ,       A_	:	List[str]      ,       A_	:	str							):






       '''simple docstring'''


       __lowercase									=	ZeroShotClassificationPipeline(
           model=A_      ,       tokenizer=A_      ,       candidate_labels=["""polics""", """health"""]							)
       return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict      ,       A_	:	Dict      ,       A_	:	Optional[Any]							):






       '''simple docstring'''


       __lowercase									=	classifier("""Who are you voting for in 2020?"""      ,       candidate_labels="""politics"""							)
       self.assertEqual(A_      ,       {"""sequence""": ANY(A_							), """labels""": [ANY(A_							)], """scores""": [ANY(A_							)]}							)

       # No kwarg
       __lowercase									=	classifier("""Who are you voting for in 2020?"""      ,       ["""politics"""]							)
       self.assertEqual(A_      ,       {"""sequence""": ANY(A_							), """labels""": [ANY(A_							)], """scores""": [ANY(A_							)]}							)

       __lowercase									=	classifier("""Who are you voting for in 2020?"""      ,       candidate_labels=["""politics"""]							)
       self.assertEqual(A_      ,       {"""sequence""": ANY(A_							), """labels""": [ANY(A_							)], """scores""": [ANY(A_							)]}							)

       __lowercase									=	classifier("""Who are you voting for in 2020?"""      ,       candidate_labels="""politics, public health"""							)
       self.assertEqual(
           A_      ,       {"""sequence""": ANY(A_							), """labels""": [ANY(A_							), ANY(A_							)], """scores""": [ANY(A_							), ANY(A_							)]}							)
       self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""]							)							)      ,       1.0							)

       __lowercase									=	classifier("""Who are you voting for in 2020?"""      ,       candidate_labels=["""politics""", """public health"""]							)
       self.assertEqual(
           A_      ,       {"""sequence""": ANY(A_							), """labels""": [ANY(A_							), ANY(A_							)], """scores""": [ANY(A_							), ANY(A_							)]}							)
       self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""]							)							)      ,       1.0							)

       __lowercase									=	classifier(
           """Who are you voting for in 2020?"""      ,       candidate_labels="""politics"""      ,       hypothesis_template="""This text is about {}"""							)
       self.assertEqual(A_      ,       {"""sequence""": ANY(A_							), """labels""": [ANY(A_							)], """scores""": [ANY(A_							)]}							)

       # https://github.com/huggingface/transformers/issues/13846
       __lowercase									=	classifier(["""I am happy"""]      ,       ["""positive""", """negative"""]							)
       self.assertEqual(
           A_      ,       [
               {"""sequence""": ANY(A_							), """labels""": [ANY(A_							), ANY(A_							)], """scores""": [ANY(A_							), ANY(A_							)]}
               for i in range(1							)
           ]      ,       )
       __lowercase									=	classifier(["""I am happy""", """I am sad"""]      ,       ["""positive""", """negative"""]							)
       self.assertEqual(
           A_      ,       [
               {"""sequence""": ANY(A_							), """labels""": [ANY(A_							), ANY(A_							)], """scores""": [ANY(A_							), ANY(A_							)]}
               for i in range(2							)
           ]      ,       )

       with self.assertRaises(A_							):
        classifier(""""""      ,       candidate_labels="""politics"""							)

       with self.assertRaises(A_							):
        classifier(A_      ,       candidate_labels="""politics"""							)

       with self.assertRaises(A_							):
        classifier("""Who are you voting for in 2020?"""      ,       candidate_labels=""""""							)

       with self.assertRaises(A_							):
        classifier("""Who are you voting for in 2020?"""      ,       candidate_labels=A_							)

       with self.assertRaises(A_							):
        classifier(
            """Who are you voting for in 2020?"""      ,       candidate_labels="""politics"""      ,       hypothesis_template="""Not formatting template"""      ,       )

       with self.assertRaises(A_							):
        classifier(
            """Who are you voting for in 2020?"""      ,       candidate_labels="""politics"""      ,       hypothesis_template=A_      ,       )

       self.run_entailment_id(A_							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[Any]      ,       A_	:	Pipeline							):






       '''simple docstring'''


       __lowercase									=	zero_shot_classifier.model.config
       __lowercase									=	config.labelaid
       __lowercase									=	zero_shot_classifier.entailment_id

       __lowercase									=	{"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2}
       self.assertEqual(zero_shot_classifier.entailment_id      ,       -1							)

       __lowercase									=	{"""entailment""": 0, """neutral""": 1, """contradiction""": 2}
       self.assertEqual(zero_shot_classifier.entailment_id      ,       0							)

       __lowercase									=	{"""ENTAIL""": 0, """NON-ENTAIL""": 1}
       self.assertEqual(zero_shot_classifier.entailment_id      ,       0							)

       __lowercase									=	{"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0}
       self.assertEqual(zero_shot_classifier.entailment_id      ,       2							)

       __lowercase									=	original_labelaid
       self.assertEqual(A_      ,       zero_shot_classifier.entailment_id							)
      @require_torch
      def SCREAMING_SNAKE_CASE_	(		self	:	Any							):






       '''simple docstring'''


       __lowercase									=	pipeline(
           """zero-shot-classification"""      ,       model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""      ,       framework="""pt"""      ,       )
       # There was a regression in 4.10 for this
       # Adding a test so we don't make the mistake again.
       # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
       zero_shot_classifier(
           """Who are you voting for in 2020?""" * 1_0_0      ,       candidate_labels=["""politics""", """public health""", """science"""]							)
      @require_torch
      def SCREAMING_SNAKE_CASE_	(		self	:	Union[str, Any]							):






       '''simple docstring'''


       __lowercase									=	pipeline(
           """zero-shot-classification"""      ,       model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""      ,       framework="""pt"""      ,       )
       __lowercase									=	zero_shot_classifier(
           """Who are you voting for in 2020?"""      ,       candidate_labels=["""politics""", """public health""", """science"""]							)

       self.assertEqual(
           nested_simplify(A_							)      ,       {
               """sequence""": """Who are you voting for in 2020?""",
               """labels""": ["""science""", """public health""", """politics"""],
               """scores""": [0.3_33, 0.3_33, 0.3_33],
           }      ,       )
      @require_tf
      def SCREAMING_SNAKE_CASE_	(		self	:	List[str]							):






       '''simple docstring'''


       __lowercase									=	pipeline(
           """zero-shot-classification"""      ,       model="""sshleifer/tiny-distilbert-base-cased-distilled-squad"""      ,       framework="""tf"""      ,       )
       __lowercase									=	zero_shot_classifier(
           """Who are you voting for in 2020?"""      ,       candidate_labels=["""politics""", """public health""", """science"""]							)

       self.assertEqual(
           nested_simplify(A_							)      ,       {
               """sequence""": """Who are you voting for in 2020?""",
               """labels""": ["""science""", """public health""", """politics"""],
               """scores""": [0.3_33, 0.3_33, 0.3_33],
           }      ,       )
      @slow
      @require_torch
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase									=	pipeline("""zero-shot-classification"""      ,       model="""roberta-large-mnli"""      ,       framework="""pt"""							)
       __lowercase									=	zero_shot_classifier(
           """Who are you voting for in 2020?"""      ,       candidate_labels=["""politics""", """public health""", """science"""]							)

       self.assertEqual(
           nested_simplify(A_							)      ,       {
               """sequence""": """Who are you voting for in 2020?""",
               """labels""": ["""politics""", """public health""", """science"""],
               """scores""": [0.9_76, 0.0_15, 0.0_09],
           }      ,       )
       __lowercase									=	zero_shot_classifier(
           """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"""
           """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"""
           """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based"""
           """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"""
           """ machine translation tasks show these models to be superior in quality while being more parallelizable"""
           """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"""
           """ English-to-German translation task, improving over the existing best results, including ensembles by"""
           """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"""
           """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"""
           """ fraction of the training costs of the best models from the literature. We show that the Transformer"""
           """ generalizes well to other tasks by applying it successfully to English constituency parsing both with"""
           """ large and limited training data."""      ,       candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""]      ,       multi_label=A_      ,       )
       self.assertEqual(
           nested_simplify(A_							)      ,       {
               """sequence""": (
                   """The dominant sequence transduction models are based on complex recurrent or convolutional neural"""
                   """ networks in an encoder-decoder configuration. The best performing models also connect the"""
                   """ encoder and decoder through an attention mechanism. We propose a new simple network"""
                   """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"""
                   """ and convolutions entirely. Experiments on two machine translation tasks show these models to be"""
                   """ superior in quality while being more parallelizable and requiring significantly less time to"""
                   """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"""
                   """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"""
                   """ English-to-French translation task, our model establishes a new single-model state-of-the-art"""
                   """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"""
                   """ costs of the best models from the literature. We show that the Transformer generalizes well to"""
                   """ other tasks by applying it successfully to English constituency parsing both with large and"""
                   """ limited training data."""
               ),
               """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""],
               """scores""": [0.8_17, 0.7_13, 0.0_18, 0.0_18],
           }      ,       )






      @slow
      @require_tf
      def SCREAMING_SNAKE_CASE_	(		self	:	List[Any]							):






       '''simple docstring'''


       __lowercase									=	pipeline("""zero-shot-classification"""      ,       model="""roberta-large-mnli"""      ,       framework="""tf"""							)
       __lowercase									=	zero_shot_classifier(
           """Who are you voting for in 2020?"""      ,       candidate_labels=["""politics""", """public health""", """science"""]							)

       self.assertEqual(
           nested_simplify(A_							)      ,       {
               """sequence""": """Who are you voting for in 2020?""",
               """labels""": ["""politics""", """public health""", """science"""],
               """scores""": [0.9_76, 0.0_15, 0.0_09],
           }      ,       )
       __lowercase									=	zero_shot_classifier(
           """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"""
           """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"""
           """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based"""
           """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"""
           """ machine translation tasks show these models to be superior in quality while being more parallelizable"""
           """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"""
           """ English-to-German translation task, improving over the existing best results, including ensembles by"""
           """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"""
           """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"""
           """ fraction of the training costs of the best models from the literature. We show that the Transformer"""
           """ generalizes well to other tasks by applying it successfully to English constituency parsing both with"""
           """ large and limited training data."""      ,       candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""]      ,       multi_label=A_      ,       )
       self.assertEqual(
           nested_simplify(A_							)      ,       {
               """sequence""": (
                   """The dominant sequence transduction models are based on complex recurrent or convolutional neural"""
                   """ networks in an encoder-decoder configuration. The best performing models also connect the"""
                   """ encoder and decoder through an attention mechanism. We propose a new simple network"""
                   """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"""
                   """ and convolutions entirely. Experiments on two machine translation tasks show these models to be"""
                   """ superior in quality while being more parallelizable and requiring significantly less time to"""
                   """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"""
                   """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"""
                   """ English-to-French translation task, our model establishes a new single-model state-of-the-art"""
                   """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"""
                   """ costs of the best models from the literature. We show that the Transformer generalizes well to"""
                   """ other tasks by applying it successfully to English constituency parsing both with large and"""
                   """ limited training data."""
               ),
               """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""],
               """scores""": [0.8_17, 0.7_13, 0.0_18, 0.0_18],
           }      ,       )




"""simple docstring"""

import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCAmelCase__  							=logging.get_logger(__name__)

UpperCAmelCase__  							={
    "nvidia/segformer-b0-finetuned-ade-512-512": (
        "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json"
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}





class    lowerCamelCase__						(		_a    ):
      a :     Optional[int]											=		"""segformer"""
      def __init__(		self	:	str      ,       A_	:	Optional[int]=3      ,       A_	:	Any=4      ,       A_	:	Optional[int]=[2, 2, 2, 2]      ,       A_	:	str=[8, 4, 2, 1]      ,       A_	:	Any=[3_2, 6_4, 1_6_0, 2_5_6]      ,       A_	:	Union[str, Any]=[7, 3, 3, 3]      ,       A_	:	Any=[4, 2, 2, 2]      ,       A_	:	int=[1, 2, 5, 8]      ,       A_	:	Union[str, Any]=[4, 4, 4, 4]      ,       A_	:	Optional[Any]="gelu"      ,       A_	:	List[str]=0.0      ,       A_	:	Any=0.0      ,       A_	:	Optional[Any]=0.1      ,       A_	:	List[str]=0.02      ,       A_	:	Tuple=0.1      ,       A_	:	Optional[Any]=1e-6      ,       A_	:	Optional[int]=2_5_6      ,       A_	:	Optional[Any]=2_5_5      ,       **A_	:	Union[str, Any]      ,       ):






       '''simple docstring'''


       super().__init__(**A_							)

       if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
        warnings.warn(
            """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be"""
            """ removed, as the behaviour will default to that of reshape_last_stage = True."""      ,       A_      ,       )

       __lowercase									=	num_channels
       __lowercase									=	num_encoder_blocks
       __lowercase									=	depths
       __lowercase									=	sr_ratios
       __lowercase									=	hidden_sizes
       __lowercase									=	patch_sizes
       __lowercase									=	strides
       __lowercase									=	mlp_ratios
       __lowercase									=	num_attention_heads
       __lowercase									=	hidden_act
       __lowercase									=	hidden_dropout_prob
       __lowercase									=	attention_probs_dropout_prob
       __lowercase									=	classifier_dropout_prob
       __lowercase									=	initializer_range
       __lowercase									=	drop_path_rate
       __lowercase									=	layer_norm_eps
       __lowercase									=	decoder_hidden_size
       __lowercase									=	kwargs.get("""reshape_last_stage"""      ,       A_							)
       __lowercase									=	semantic_loss_ignore_index






class    lowerCamelCase__						(		_a    ):
      a :     List[str]											=		version.parse("""1.11"""    )
      @property
      def SCREAMING_SNAKE_CASE_	(		self	:	Any							):






       '''simple docstring'''


       return OrderedDict(
           [
               ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
           ]							)
      @property
      def SCREAMING_SNAKE_CASE_	(		self	:	int							):






       '''simple docstring'''


       return 1e-4






      @property
      def SCREAMING_SNAKE_CASE_	(		self	:	int							):






       '''simple docstring'''


       return 1_2
