



"""simple docstring"""

from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


A_						:    Optional[int]				=      logging.get_logger(__name__)
class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	def 			_lowerCAmelCase     (      self				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Tuple    )						->	Tuple:





					"""simple docstring"""


					if isinstance(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    ):
									SCREAMING_SNAKE_CASE						:							int							=     [label.strip() for label in labels.split(','    ) if label.strip()]
					return labels







	def __call__(      self				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Any     ,       _SCREAMING_SNAKE_CASE				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       Tuple    )						->	Dict:





					"""simple docstring"""


					if len(_SCREAMING_SNAKE_CASE    ) == 0 or len(_SCREAMING_SNAKE_CASE    ) == 0:
									raise ValueError('You must include at least one label and at least one sequence.'    )
					if hypothesis_template.format(labels[0]    ) == hypothesis_template:
									raise ValueError(
									    (
									        'The provided hypothesis_template "{}" was not able to be formatted with the target labels. '
									        'Make sure the passed template includes formatting syntax such as {{}} where the label should go.'
									    ).format(_SCREAMING_SNAKE_CASE    )    )

					if isinstance(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    ):
									SCREAMING_SNAKE_CASE						:							Tuple							=     [sequences]

					SCREAMING_SNAKE_CASE						:							int							=     []
					for sequence in sequences:
									sequence_pairs.extend([[sequence, hypothesis_template.format(_SCREAMING_SNAKE_CASE    )] for label in labels]    )

					return sequence_pairs, sequences




@add_end_docstrings(_lowerCamelCase )
class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	def __init__(      self				:       int     ,       _SCREAMING_SNAKE_CASE				:       int=ZeroShotClassificationArgumentHandler()     ,       *_SCREAMING_SNAKE_CASE				:       str     ,       **_SCREAMING_SNAKE_CASE				:       int    )						->	Union[str, Any]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Tuple							=     args_parser
					super().__init__(*_SCREAMING_SNAKE_CASE     ,       **_SCREAMING_SNAKE_CASE    )
					if self.entailment_id == -1:
									logger.warning(
									    'Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to '
									    '-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.'    )





	@property
	def 			_lowerCAmelCase     (      self				:       str    )						->	Any:





					"""simple docstring"""


					for label, ind in self.model.config.labelaid.items():
									if label.lower().startswith('entail'    ):
													return ind
					return -1





	def 			_lowerCAmelCase     (      self				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]=True     ,       _SCREAMING_SNAKE_CASE				:       Dict=True     ,       _SCREAMING_SNAKE_CASE				:       Any=TruncationStrategy.ONLY_FIRST     ,       **_SCREAMING_SNAKE_CASE				:       Tuple    )						->	str:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Tuple							=     self.framework
					if self.tokenizer.pad_token is None:
									# Override for tokenizers not supporting padding
									logger.error(
									    'Tokenizer was not supporting padding necessary for zero-shot, attempting to use '
									    ' `pad_token=eos_token`'    )
									SCREAMING_SNAKE_CASE						:							Optional[int]							=     self.tokenizer.eos_token
					try:
									SCREAMING_SNAKE_CASE						:							int							=     self.tokenizer(
									    _SCREAMING_SNAKE_CASE     ,       add_special_tokens=_SCREAMING_SNAKE_CASE     ,       return_tensors=_SCREAMING_SNAKE_CASE     ,       padding=_SCREAMING_SNAKE_CASE     ,       truncation=_SCREAMING_SNAKE_CASE     ,       )
					except Exception as e:
									if "too short" in str(_SCREAMING_SNAKE_CASE    ):
													# tokenizers might yell that we want to truncate
													# to a value that is not even reached by the input.
													# In that case we don't want to truncate.
													# It seems there's not a really better way to catch that
													# exception.

													SCREAMING_SNAKE_CASE						:							List[Any]							=     self.tokenizer(
													    _SCREAMING_SNAKE_CASE     ,       add_special_tokens=_SCREAMING_SNAKE_CASE     ,       return_tensors=_SCREAMING_SNAKE_CASE     ,       padding=_SCREAMING_SNAKE_CASE     ,       truncation=TruncationStrategy.DO_NOT_TRUNCATE     ,       )
									else:
													raise e

					return inputs





	def 			_lowerCAmelCase     (      self				:       Dict     ,       **_SCREAMING_SNAKE_CASE				:       Optional[Any]    )						->	List[str]:





					"""simple docstring"""


					if kwargs.get('multi_class'     ,       _SCREAMING_SNAKE_CASE    ) is not None:
									SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     kwargs['multi_class']
									logger.warning(
									    'The `multi_class` argument has been deprecated and renamed to `multi_label`. '
									    '`multi_class` will be removed in a future version of Transformers.'    )
					SCREAMING_SNAKE_CASE						:							List[Any]							=     {}
					if "candidate_labels" in kwargs:
									SCREAMING_SNAKE_CASE						:							Tuple							=     self._args_parser._parse_labels(kwargs['candidate_labels']    )
					if "hypothesis_template" in kwargs:
									SCREAMING_SNAKE_CASE						:							List[Any]							=     kwargs['hypothesis_template']

					SCREAMING_SNAKE_CASE						:							List[str]							=     {}
					if "multi_label" in kwargs:
									SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     kwargs['multi_label']
					return preprocess_params, {}, postprocess_params





	def __call__(      self				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       Union[str, List[str]]     ,       *_SCREAMING_SNAKE_CASE				:       Tuple     ,       **_SCREAMING_SNAKE_CASE				:       List[Any]     ,       )						->	List[Any]:





					"""simple docstring"""


					if len(_SCREAMING_SNAKE_CASE    ) == 0:
									pass
					elif len(_SCREAMING_SNAKE_CASE    ) == 1 and "candidate_labels" not in kwargs:
									SCREAMING_SNAKE_CASE						:							List[str]							=     args[0]
					else:
									raise ValueError(f"""Unable to understand extra arguments {args}"""    )

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





	def 			_lowerCAmelCase     (      self				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       int=None     ,       _SCREAMING_SNAKE_CASE				:       str="This example is {}."    )						->	Any:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							Optional[Any]							=     self._args_parser(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )

					for i, (candidate_label, sequence_pair) in enumerate(zip(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )    ):
									SCREAMING_SNAKE_CASE						:							Tuple							=     self._parse_and_tokenize([sequence_pair]    )

									yield {
									    "candidate_label": candidate_label,
									    "sequence": sequences[0],
									    "is_last": i == len(_SCREAMING_SNAKE_CASE    ) - 1,
									    **model_input,
									}





	def 			_lowerCAmelCase     (      self				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Any    )						->	Optional[int]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							List[Any]							=     inputs['candidate_label']
					SCREAMING_SNAKE_CASE						:							int							=     inputs['sequence']
					SCREAMING_SNAKE_CASE						:							int							=     {k: inputs[k] for k in self.tokenizer.model_input_names}
					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     self.model(**_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Tuple							=     {
					    'candidate_label': candidate_label,
					    'sequence': sequence,
					    'is_last': inputs['is_last'],
					    **outputs,
					}
					return model_outputs







	def 			_lowerCAmelCase     (      self				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Any     ,       _SCREAMING_SNAKE_CASE				:       str=False    )						->	int:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Tuple							=     [outputs['candidate_label'] for outputs in model_outputs]
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     [outputs['sequence'] for outputs in model_outputs]
					SCREAMING_SNAKE_CASE						:							Optional[int]							=     np.concatenate([output['logits'].numpy() for output in model_outputs]    )
					SCREAMING_SNAKE_CASE						:							Any							=     logits.shape[0]
					SCREAMING_SNAKE_CASE						:							List[str]							=     len(_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							Tuple							=     N // n
					SCREAMING_SNAKE_CASE						:							str							=     logits.reshape((num_sequences, n, -1)    )

					if multi_label or len(_SCREAMING_SNAKE_CASE    ) == 1:
									# softmax over the entailment vs. contradiction dim for each label independently
									SCREAMING_SNAKE_CASE						:							Dict							=     self.entailment_id
									SCREAMING_SNAKE_CASE						:							Any							=     -1 if entailment_id == 0 else 0
									SCREAMING_SNAKE_CASE						:							Dict							=     reshaped_outputs[..., [contradiction_id, entailment_id]]
									SCREAMING_SNAKE_CASE						:							Tuple							=     np.exp(_SCREAMING_SNAKE_CASE    ) / np.exp(_SCREAMING_SNAKE_CASE    ).sum(-1     ,       keepdims=_SCREAMING_SNAKE_CASE    )
									SCREAMING_SNAKE_CASE						:							Any							=     scores[..., 1]
					else:
									# softmax the "entailment" logits over all candidate labels
									SCREAMING_SNAKE_CASE						:							Optional[int]							=     reshaped_outputs[..., self.entailment_id]
									SCREAMING_SNAKE_CASE						:							Any							=     np.exp(_SCREAMING_SNAKE_CASE    ) / np.exp(_SCREAMING_SNAKE_CASE    ).sum(-1     ,       keepdims=_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     list(reversed(scores[0].argsort()    )    )
					return {
					    "sequence": sequences[0],
					    "labels": [candidate_labels[i] for i in top_inds],
					    "scores": scores[0, top_inds].tolist(),
					}










"""simple docstring"""

from collections import OrderedDict
from typing import Mapping

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


A_						:    Any				=      logging.get_logger(__name__)

A_						:    Optional[int]				=      {
    'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json',
    'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json',
    'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json',
    'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json',
    'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json',
    'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json',
    'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json',
    'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json',
    'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json',
}
class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	_SCREAMING_SNAKE_CASE	:		int  						= '''xmod'''





	def __init__(      self				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       Tuple=30_522     ,       _SCREAMING_SNAKE_CASE				:       Tuple=768     ,       _SCREAMING_SNAKE_CASE				:       Optional[int]=12     ,       _SCREAMING_SNAKE_CASE				:       List[str]=12     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]=3_072     ,       _SCREAMING_SNAKE_CASE				:       Any="gelu"     ,       _SCREAMING_SNAKE_CASE				:       List[Any]=0.1     ,       _SCREAMING_SNAKE_CASE				:       Dict=0.1     ,       _SCREAMING_SNAKE_CASE				:       str=512     ,       _SCREAMING_SNAKE_CASE				:       Tuple=2     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]=0.0_2     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]=1E-1_2     ,       _SCREAMING_SNAKE_CASE				:       List[str]=1     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]=0     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]=2     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]="absolute"     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]=True     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]=None     ,       _SCREAMING_SNAKE_CASE				:       str=False     ,       _SCREAMING_SNAKE_CASE				:       Dict=2     ,       _SCREAMING_SNAKE_CASE				:       str=False     ,       _SCREAMING_SNAKE_CASE				:       int=True     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]=True     ,       _SCREAMING_SNAKE_CASE				:       Tuple=("en_XX",)     ,       _SCREAMING_SNAKE_CASE				:       Optional[int]=None     ,       **_SCREAMING_SNAKE_CASE				:       List[Any]     ,       )						->	List[str]:





					"""simple docstring"""


					super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE     ,       bos_token_id=_SCREAMING_SNAKE_CASE     ,       eos_token_id=_SCREAMING_SNAKE_CASE     ,       **_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Any							=     vocab_size
					SCREAMING_SNAKE_CASE						:							Any							=     hidden_size
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     num_hidden_layers
					SCREAMING_SNAKE_CASE						:							str							=     num_attention_heads
					SCREAMING_SNAKE_CASE						:							List[Any]							=     hidden_act
					SCREAMING_SNAKE_CASE						:							Any							=     intermediate_size
					SCREAMING_SNAKE_CASE						:							Any							=     hidden_dropout_prob
					SCREAMING_SNAKE_CASE						:							str							=     attention_probs_dropout_prob
					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     max_position_embeddings
					SCREAMING_SNAKE_CASE						:							str							=     type_vocab_size
					SCREAMING_SNAKE_CASE						:							List[str]							=     initializer_range
					SCREAMING_SNAKE_CASE						:							Optional[int]							=     layer_norm_eps
					SCREAMING_SNAKE_CASE						:							Tuple							=     position_embedding_type
					SCREAMING_SNAKE_CASE						:							int							=     use_cache
					SCREAMING_SNAKE_CASE						:							Optional[int]							=     classifier_dropout
					SCREAMING_SNAKE_CASE						:							List[Any]							=     pre_norm
					SCREAMING_SNAKE_CASE						:							int							=     adapter_reduction_factor
					SCREAMING_SNAKE_CASE						:							List[Any]							=     adapter_layer_norm
					SCREAMING_SNAKE_CASE						:							Any							=     adapter_reuse_layer_norm
					SCREAMING_SNAKE_CASE						:							Any							=     ln_before_adapter
					SCREAMING_SNAKE_CASE						:							Tuple							=     list(_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							List[Any]							=     default_language




class     lowerCAmelCase__						(	_lowerCamelCase ):


	'''simple docstring'''







	@property
	def 			_lowerCAmelCase     (      self				:       Union[str, Any]    )						->	Mapping[str, Mapping[int, str]]:





					"""simple docstring"""


					if self.task == "multiple-choice":
									SCREAMING_SNAKE_CASE						:							Optional[int]							=     {0: 'batch', 1: 'choice', 2: 'sequence'}
					else:
									SCREAMING_SNAKE_CASE						:							List[str]							=     {0: 'batch', 1: 'sequence'}
					return OrderedDict(
					    [
					        ('input_ids', dynamic_axis),
					        ('attention_mask', dynamic_axis),
					    ]    )





