
"""simple docstring"""


from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


A_    							=					logging.get_logger(__name__)

# General docstring
A_    							=					'RegNetConfig'

# Base docstring
A_    							=					'facebook/regnet-y-040'
A_    							=					[1, 1088, 7, 7]

# Image classification docstring
A_    							=					'facebook/regnet-y-040'
A_    							=					'tabby, tabby cat'

A_    							=					[
    'facebook/regnet-y-040',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase = 3							,						UpperCAmelCase = 1							,						UpperCAmelCase = 1							,						UpperCAmelCase = "relu"							,						):
							super().__init__()
							lowerCamelCase_					=  nn.Convad(
							    UpperCamelCase__							,						UpperCamelCase__							,						kernel_size=UpperCamelCase__							,						stride=UpperCamelCase__							,						padding=kernel_size // 2							,						groups=UpperCamelCase__							,						bias=UpperCamelCase__							,						)
							lowerCamelCase_					=  nn.BatchNormad(UpperCamelCase__   )
							lowerCamelCase_					=  ACTaFN[activation] if activation is not None else nn.Identity()





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							lowerCamelCase_					=  self.convolution(UpperCamelCase__   )
							lowerCamelCase_					=  self.normalization(UpperCamelCase__   )
							lowerCamelCase_					=  self.activation(UpperCamelCase__   )
							return hidden_state




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase   ):
							super().__init__()
							lowerCamelCase_					=  RegNetConvLayer(
							    config.num_channels							,						config.embedding_size							,						kernel_size=3							,						stride=2							,						activation=config.hidden_act   )
							lowerCamelCase_					=  config.num_channels





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							lowerCamelCase_					=  pixel_values.shape[1]
							if num_channels != self.num_channels:
										raise ValueError(
										    '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.'''   )
							lowerCamelCase_					=  self.embedder(UpperCamelCase__   )
							return hidden_state




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase = 2   ):
							super().__init__()
							lowerCamelCase_					=  nn.Convad(UpperCamelCase__							,						UpperCamelCase__							,						kernel_size=1							,						stride=UpperCamelCase__							,						bias=UpperCamelCase__   )
							lowerCamelCase_					=  nn.BatchNormad(UpperCamelCase__   )





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							lowerCamelCase_					=  self.convolution(UpperCamelCase__   )
							lowerCamelCase_					=  self.normalization(UpperCamelCase__   )
							return hidden_state




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase   ):
							super().__init__()

							lowerCamelCase_					=  nn.AdaptiveAvgPoolad((1, 1)   )
							lowerCamelCase_					=  nn.Sequential(
							    nn.Convad(UpperCamelCase__							,						UpperCamelCase__							,						kernel_size=1   )							,						nn.ReLU()							,						nn.Convad(UpperCamelCase__							,						UpperCamelCase__							,						kernel_size=1   )							,						nn.Sigmoid()							,						)





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							lowerCamelCase_					=  self.pooler(UpperCamelCase__   )
							lowerCamelCase_					=  self.attention(UpperCamelCase__   )
							lowerCamelCase_					=  hidden_state * attention
							return hidden_state




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase = 1   ):
							super().__init__()
							lowerCamelCase_					=  in_channels != out_channels or stride != 1
							lowerCamelCase_					=  max(1							,						out_channels // config.groups_width   )
							lowerCamelCase_					=  (
							    RegNetShortCut(UpperCamelCase__							,						UpperCamelCase__							,						stride=UpperCamelCase__   ) if should_apply_shortcut else nn.Identity()
							)
							lowerCamelCase_					=  nn.Sequential(
							    RegNetConvLayer(UpperCamelCase__							,						UpperCamelCase__							,						kernel_size=1							,						activation=config.hidden_act   )							,						RegNetConvLayer(UpperCamelCase__							,						UpperCamelCase__							,						stride=UpperCamelCase__							,						groups=UpperCamelCase__							,						activation=config.hidden_act   )							,						RegNetConvLayer(UpperCamelCase__							,						UpperCamelCase__							,						kernel_size=1							,						activation=UpperCamelCase__   )							,						)
							lowerCamelCase_					=  ACTaFN[config.hidden_act]





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							lowerCamelCase_					=  hidden_state
							lowerCamelCase_					=  self.layer(UpperCamelCase__   )
							lowerCamelCase_					=  self.shortcut(UpperCamelCase__   )
							hidden_state += residual
							lowerCamelCase_					=  self.activation(UpperCamelCase__   )
							return hidden_state




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase = 1   ):
							super().__init__()
							lowerCamelCase_					=  in_channels != out_channels or stride != 1
							lowerCamelCase_					=  max(1							,						out_channels // config.groups_width   )
							lowerCamelCase_					=  (
							    RegNetShortCut(UpperCamelCase__							,						UpperCamelCase__							,						stride=UpperCamelCase__   ) if should_apply_shortcut else nn.Identity()
							)
							lowerCamelCase_					=  nn.Sequential(
							    RegNetConvLayer(UpperCamelCase__							,						UpperCamelCase__							,						kernel_size=1							,						activation=config.hidden_act   )							,						RegNetConvLayer(UpperCamelCase__							,						UpperCamelCase__							,						stride=UpperCamelCase__							,						groups=UpperCamelCase__							,						activation=config.hidden_act   )							,						RegNetSELayer(UpperCamelCase__							,						reduced_channels=int(round(in_channels / 4   )   )   )							,						RegNetConvLayer(UpperCamelCase__							,						UpperCamelCase__							,						kernel_size=1							,						activation=UpperCamelCase__   )							,						)
							lowerCamelCase_					=  ACTaFN[config.hidden_act]





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							lowerCamelCase_					=  hidden_state
							lowerCamelCase_					=  self.layer(UpperCamelCase__   )
							lowerCamelCase_					=  self.shortcut(UpperCamelCase__   )
							hidden_state += residual
							lowerCamelCase_					=  self.activation(UpperCamelCase__   )
							return hidden_state




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase = 2							,						UpperCAmelCase = 2							,						):
							super().__init__()

							lowerCamelCase_					=  RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer

							lowerCamelCase_					=  nn.Sequential(
							    # downsampling is done in the first layer with stride of 2
							    layer(
							        UpperCamelCase__							,						UpperCamelCase__							,						UpperCamelCase__							,						stride=UpperCamelCase__							,						)							,						*[layer(UpperCamelCase__							,						UpperCamelCase__							,						UpperCamelCase__   ) for _ in range(depth - 1   )]							,						)





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):
							lowerCamelCase_					=  self.layers(UpperCamelCase__   )
							return hidden_state




class  __lowerCamelCase  ( nn.Module			):




				def __init__(				self							,						UpperCAmelCase   ):
							super().__init__()
							lowerCamelCase_					=  nn.ModuleList([]   )
							# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
							self.stages.append(
							    RegNetStage(
							        UpperCamelCase__							,						config.embedding_size							,						config.hidden_sizes[0]							,						stride=2 if config.downsample_in_first_stage else 1							,						depth=config.depths[0]							,						)   )
							lowerCamelCase_					=  zip(config.hidden_sizes							,						config.hidden_sizes[1:]   )
							for (in_channels, out_channels), depth in zip(UpperCamelCase__							,						config.depths[1:]   ):
										self.stages.append(RegNetStage(UpperCamelCase__							,						UpperCamelCase__							,						UpperCamelCase__							,						depth=UpperCamelCase__   )   )





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase = False							,						UpperCAmelCase = True   ):
							lowerCamelCase_					=  () if output_hidden_states else None

							for stage_module in self.stages:
										if output_hidden_states:
													lowerCamelCase_					=  hidden_states + (hidden_state,)

										lowerCamelCase_					=  stage_module(UpperCamelCase__   )

							if output_hidden_states:
										lowerCamelCase_					=  hidden_states + (hidden_state,)

							if not return_dict:
										return tuple(v for v in [hidden_state, hidden_states] if v is not None   )

							return BaseModelOutputWithNoAttention(last_hidden_state=UpperCamelCase__							,						hidden_states=UpperCamelCase__   )




class  __lowerCamelCase  ( _A			):
				a__:      List[Any]          =    RegNetConfig
				a__:      Union[str, Any]          =    'regnet'
				a__:      Optional[int]          =    'pixel_values'
				a__:      int          =    True




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase   ):






							if isinstance(UpperCamelCase__							,						nn.Convad   ):
										nn.init.kaiming_normal_(module.weight							,						mode='''fan_out'''							,						nonlinearity='''relu'''   )
							elif isinstance(UpperCamelCase__							,						(nn.BatchNormad, nn.GroupNorm)   ):
										nn.init.constant_(module.weight							,						1   )
										nn.init.constant_(module.bias							,						0   )





				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase=False   ):






							if isinstance(UpperCamelCase__							,						UpperCamelCase__   ):
										lowerCamelCase_					=  value

A_    							=					R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

A_    							=					R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n'




@add_start_docstrings(
    'The bare RegNet model outputting raw features without any specific head on top.'						,	_A						,	)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class  __lowerCamelCase  ( _A			):




				def __init__(				self							,						UpperCAmelCase   ):
							super().__init__(UpperCamelCase__   )
							lowerCamelCase_					=  config
							lowerCamelCase_					=  RegNetEmbeddings(UpperCamelCase__   )
							lowerCamelCase_					=  RegNetEncoder(UpperCamelCase__   )
							lowerCamelCase_					=  nn.AdaptiveAvgPoolad((1, 1)   )
							# Initialize weights and apply final processing
							self.post_init()





				@add_start_docstrings_to_model_forward(UpperCamelCase__   )
				@add_code_sample_docstrings(
				    checkpoint=_CHECKPOINT_FOR_DOC							,						output_type=UpperCamelCase__							,						config_class=_CONFIG_FOR_DOC							,						modality='''vision'''							,						expected_output=_EXPECTED_OUTPUT_SHAPE							,						)
				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase = None							,						UpperCAmelCase = None   ):
							lowerCamelCase_					=  (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							lowerCamelCase_					=  return_dict if return_dict is not None else self.config.use_return_dict

							lowerCamelCase_					=  self.embedder(UpperCamelCase__   )

							lowerCamelCase_					=  self.encoder(
							    UpperCamelCase__							,						output_hidden_states=UpperCamelCase__							,						return_dict=UpperCamelCase__   )

							lowerCamelCase_					=  encoder_outputs[0]

							lowerCamelCase_					=  self.pooler(UpperCamelCase__   )

							if not return_dict:
										return (last_hidden_state, pooled_output) + encoder_outputs[1:]

							return BaseModelOutputWithPoolingAndNoAttention(
							    last_hidden_state=UpperCamelCase__							,						pooler_output=UpperCamelCase__							,						hidden_states=encoder_outputs.hidden_states							,						)




@add_start_docstrings(
    '\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '						,	_A						,	)
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class  __lowerCamelCase  ( _A			):




				def __init__(				self							,						UpperCAmelCase   ):
							super().__init__(UpperCamelCase__   )
							lowerCamelCase_					=  config.num_labels
							lowerCamelCase_					=  RegNetModel(UpperCamelCase__   )
							# classification head
							lowerCamelCase_					=  nn.Sequential(
							    nn.Flatten()							,						nn.Linear(config.hidden_sizes[-1]							,						config.num_labels   ) if config.num_labels > 0 else nn.Identity()							,						)
							# initialize weights and apply final processing
							self.post_init()





				@add_start_docstrings_to_model_forward(UpperCamelCase__   )
				@add_code_sample_docstrings(
				    checkpoint=_IMAGE_CLASS_CHECKPOINT							,						output_type=UpperCamelCase__							,						config_class=_CONFIG_FOR_DOC							,						expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT							,						)
				def        UpperCAmelCase__						(				self							,						UpperCAmelCase = None							,						UpperCAmelCase = None							,						UpperCAmelCase = None							,						UpperCAmelCase = None							,						):
							lowerCamelCase_					=  return_dict if return_dict is not None else self.config.use_return_dict

							lowerCamelCase_					=  self.regnet(UpperCamelCase__							,						output_hidden_states=UpperCamelCase__							,						return_dict=UpperCamelCase__   )

							lowerCamelCase_					=  outputs.pooler_output if return_dict else outputs[1]

							lowerCamelCase_					=  self.classifier(UpperCamelCase__   )

							lowerCamelCase_					=  None

							if labels is not None:
										if self.config.problem_type is None:
													if self.num_labels == 1:
																lowerCamelCase_					=  '''regression'''
													elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																lowerCamelCase_					=  '''single_label_classification'''
													else:
																lowerCamelCase_					=  '''multi_label_classification'''
										if self.config.problem_type == "regression":
													lowerCamelCase_					=  MSELoss()
													if self.num_labels == 1:
																lowerCamelCase_					=  loss_fct(logits.squeeze()							,						labels.squeeze()   )
													else:
																lowerCamelCase_					=  loss_fct(UpperCamelCase__							,						UpperCamelCase__   )
										elif self.config.problem_type == "single_label_classification":
													lowerCamelCase_					=  CrossEntropyLoss()
													lowerCamelCase_					=  loss_fct(logits.view(-1							,						self.num_labels   )							,						labels.view(-1   )   )
										elif self.config.problem_type == "multi_label_classification":
													lowerCamelCase_					=  BCEWithLogitsLoss()
													lowerCamelCase_					=  loss_fct(UpperCamelCase__							,						UpperCamelCase__   )

							if not return_dict:
										lowerCamelCase_					=  (logits,) + outputs[2:]
										return (loss,) + output if loss is not None else output

							return ImageClassifierOutputWithNoAttention(loss=UpperCamelCase__							,						logits=UpperCamelCase__							,						hidden_states=outputs.hidden_states   )





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.
__lowerCAmelCase     :	Optional[Any]       			=  {'LayoutLMv2Config', 'LayoutLMv3Config'}




@is_pipeline_test
class 			UpperCAmelCase_     (					unittest.TestCase	):


  '''simple docstring'''







  a__       			=						MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
  a__       			=						TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

  if model_mapping is not None:
    a__       			=						{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
  if tf_model_mapping is not None:
    a__       			=						{
        config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
    }
  def 				_lowercase				(					self     :					Dict     ,				UpperCamelCase__     :					Tuple     ,				UpperCamelCase__     :					Optional[int]     ,				UpperCamelCase__     :					List[str]       )     ->      List[str]:







    """simple docstring"""






    __magic_name__								=			ZeroShotClassificationPipeline(
        model=UpperCamelCase__     ,				tokenizer=UpperCamelCase__     ,				candidate_labels=["""polics""", """health"""]       )
    return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]
  def 				_lowercase				(					self     :					int     ,				UpperCamelCase__     :					Any     ,				UpperCamelCase__     :					List[Any]       )     ->      str:







    """simple docstring"""






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

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

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

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

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

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

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

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

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

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

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

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

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

    self.run_entailment_id(UpperCamelCase__       )
  def 				_lowercase				(					self     :					Dict     ,				UpperCamelCase__     :					Pipeline       )     ->      Dict:







    """simple docstring"""






    __magic_name__								=			zero_shot_classifier.model.config
    __magic_name__								=			config.labelaid
    __magic_name__								=			zero_shot_classifier.entailment_id

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

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

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

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

    __magic_name__								=			original_labelaid
    self.assertEqual(UpperCamelCase__     ,				zero_shot_classifier.entailment_id       )
  @require_torch
  def 				_lowercase				(					self     :					Optional[int]       )     ->      Union[str, Any]:







    """simple docstring"""






    __magic_name__								=			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?""" * 100     ,				candidate_labels=["""politics""", """public health""", """science"""]       )
  @require_torch
  def 				_lowercase				(					self     :					Optional[int]       )     ->      Tuple:







    """simple docstring"""






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

    self.assertEqual(
        nested_simplify(UpperCamelCase__       )     ,				{
            """sequence""": """Who are you voting for in 2020?""",
            """labels""": ["""science""", """public health""", """politics"""],
            """scores""": [0.333, 0.333, 0.333],
        }     ,				)
  @require_tf
  def 				_lowercase				(					self     :					Optional[Any]       )     ->      List[str]:







    """simple docstring"""






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

    self.assertEqual(
        nested_simplify(UpperCamelCase__       )     ,				{
            """sequence""": """Who are you voting for in 2020?""",
            """labels""": ["""science""", """public health""", """politics"""],
            """scores""": [0.333, 0.333, 0.333],
        }     ,				)
  @slow
  @require_torch
  def 				_lowercase				(					self     :					Any       )     ->      List[Any]:







    """simple docstring"""






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

    self.assertEqual(
        nested_simplify(UpperCamelCase__       )     ,				{
            """sequence""": """Who are you voting for in 2020?""",
            """labels""": ["""politics""", """public health""", """science"""],
            """scores""": [0.976, 0.015, 0.009],
        }     ,				)
    __magic_name__								=			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=UpperCamelCase__     ,				)
    self.assertEqual(
        nested_simplify(UpperCamelCase__       )     ,				{
            """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.817, 0.713, 0.018, 0.018],
        }     ,				)





  @slow
  @require_tf
  def 				_lowercase				(					self     :					str       )     ->      Optional[Any]:







    """simple docstring"""






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

    self.assertEqual(
        nested_simplify(UpperCamelCase__       )     ,				{
            """sequence""": """Who are you voting for in 2020?""",
            """labels""": ["""politics""", """public health""", """science"""],
            """scores""": [0.976, 0.015, 0.009],
        }     ,				)
    __magic_name__								=			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=UpperCamelCase__     ,				)
    self.assertEqual(
        nested_simplify(UpperCamelCase__       )     ,				{
            """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.817, 0.713, 0.018, 0.018],
        }     ,				)

