



'''simple docstring'''




import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch
			from torch import nn

			from transformers import MaskFormerSwinBackbone
			from transformers.models.maskformer import MaskFormerSwinModel

class     UpperCamelCase_				:





	def __init__(						self	,	A	,	A=13	,	A=32	,	A=2	,	A=3	,	A=16	,	A=[1, 2, 1]	,	A=[2, 2, 4]	,	A=2	,	A=2.0	,	A=True	,	A=0.0	,	A=0.0	,	A=0.1	,	A="gelu"	,	A=False	,	A=True	,	A=0.0_2	,	A=1e-5	,	A=True	,	A=None	,	A=True	,	A=10	,	A=8	,	A=["stage1", "stage2", "stage3"]	,	A=[1, 2, 3]	,	)    ->    int:
								UpperCAmelCase  :	Dict							  =	parent
								UpperCAmelCase  :	Union[str, Any]							  =	batch_size
								UpperCAmelCase  :	str							  =	image_size
								UpperCAmelCase  :	int							  =	patch_size
								UpperCAmelCase  :	int							  =	num_channels
								UpperCAmelCase  :	Tuple							  =	embed_dim
								UpperCAmelCase  :	Union[str, Any]							  =	depths
								UpperCAmelCase  :	str							  =	num_heads
								UpperCAmelCase  :	Any							  =	window_size
								UpperCAmelCase  :	Union[str, Any]							  =	mlp_ratio
								UpperCAmelCase  :	List[Any]							  =	qkv_bias
								UpperCAmelCase  :	str							  =	hidden_dropout_prob
								UpperCAmelCase  :	List[str]							  =	attention_probs_dropout_prob
								UpperCAmelCase  :	Dict							  =	drop_path_rate
								UpperCAmelCase  :	List[Any]							  =	hidden_act
								UpperCAmelCase  :	Optional[int]							  =	use_absolute_embeddings
								UpperCAmelCase  :	Optional[int]							  =	patch_norm
								UpperCAmelCase  :	int							  =	layer_norm_eps
								UpperCAmelCase  :	Optional[int]							  =	initializer_range
								UpperCAmelCase  :	Tuple							  =	is_training
								UpperCAmelCase  :	List[str]							  =	scope
								UpperCAmelCase  :	str							  =	use_labels
								UpperCAmelCase  :	List[Any]							  =	type_sequence_label_size
								UpperCAmelCase  :	Union[str, Any]							  =	encoder_stride
								UpperCAmelCase  :	Optional[int]							  =	out_features
								UpperCAmelCase  :	List[str]							  =	out_indices





	def 				_lowercase(						self					)    ->    Optional[Any]:
								UpperCAmelCase  :	Union[str, Any]							  =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

								UpperCAmelCase  :	str							  =	None
								if self.use_labels:
															UpperCAmelCase  :	str							  =	ids_tensor([self.batch_size]	,	self.type_sequence_label_size					)

								UpperCAmelCase  :	Any							  =	self.get_config()

								return config, pixel_values, labels





	def 				_lowercase(						self					)    ->    Optional[Any]:
								return MaskFormerSwinConfig(
								    image_size=self.image_size	,	patch_size=self.patch_size	,	num_channels=self.num_channels	,	embed_dim=self.embed_dim	,	depths=self.depths	,	num_heads=self.num_heads	,	window_size=self.window_size	,	mlp_ratio=self.mlp_ratio	,	qkv_bias=self.qkv_bias	,	hidden_dropout_prob=self.hidden_dropout_prob	,	attention_probs_dropout_prob=self.attention_probs_dropout_prob	,	drop_path_rate=self.drop_path_rate	,	hidden_act=self.hidden_act	,	use_absolute_embeddings=self.use_absolute_embeddings	,	path_norm=self.patch_norm	,	layer_norm_eps=self.layer_norm_eps	,	initializer_range=self.initializer_range	,	encoder_stride=self.encoder_stride	,	out_features=self.out_features	,	out_indices=self.out_indices	,	)





	def 				_lowercase(						self	,	A	,	A	,	A					)    ->    Tuple:
								UpperCAmelCase  :	int							  =	MaskFormerSwinModel(config=_lowerCAmelCase					)
								model.to(_lowerCAmelCase					)
								model.eval()
								UpperCAmelCase  :	List[Any]							  =	model(_lowerCAmelCase					)

								UpperCAmelCase  :	Optional[int]							  =	((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths					) - 1))
								UpperCAmelCase  :	Any							  =	int(config.embed_dim * 2 ** (len(config.depths					) - 1)					)

								self.parent.assertEqual(result.last_hidden_state.shape	,	(self.batch_size, expected_seq_len, expected_dim)					)





	def 				_lowercase(						self	,	A	,	A	,	A					)    ->    Dict:
								UpperCAmelCase  :	Tuple							  =	MaskFormerSwinBackbone(config=_lowerCAmelCase					)
								model.to(_lowerCAmelCase					)
								model.eval()
								UpperCAmelCase  :	Dict							  =	model(_lowerCAmelCase					)

								# verify feature maps
								self.parent.assertEqual(len(result.feature_maps					)	,	len(config.out_features					)					)
								self.parent.assertListEqual(list(result.feature_maps[0].shape					)	,	[13, 16, 16, 16]					)

								# verify channels
								self.parent.assertEqual(len(model.channels					)	,	len(config.out_features					)					)
								self.parent.assertListEqual(model.channels	,	[16, 32, 64]					)

								# verify ValueError
								with self.parent.assertRaises(_lowerCAmelCase					):
															UpperCAmelCase  :	Union[str, Any]							  =	["""stem"""]
															UpperCAmelCase  :	Dict							  =	MaskFormerSwinBackbone(config=_lowerCAmelCase					)






	def 				_lowercase(						self					)    ->    Tuple:
								UpperCAmelCase  :	Dict							  =	self.prepare_config_and_inputs()
								UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	Any							  =	config_and_inputs
								UpperCAmelCase  :	Tuple							  =	{"""pixel_values""": pixel_values}
								return config, inputs_dict




@require_torch
class     UpperCamelCase_				(							_lowerCAmelCase   ,  _lowerCAmelCase   ,  unittest.TestCase    ):
	lowercase    =				(
	    (
	        MaskFormerSwinModel,
	        MaskFormerSwinBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase    =				{'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {}
	lowercase    =				False
	lowercase    =				False
	lowercase    =				False
	lowercase    =				False
	lowercase    =				False





	def 				_lowercase(						self					)    ->    Dict:
								UpperCAmelCase  :	Optional[Any]							  =	MaskFormerSwinModelTester(self					)
								UpperCAmelCase  :	Dict							  =	ConfigTester(self	,	config_class=_lowerCAmelCase	,	embed_dim=37					)





	@require_torch_multi_gpu
	@unittest.skip(
	    reason=(
	        """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
	        """ `nn.DataParallel`"""
	    )					)
	def 				_lowercase(						self					)    ->    List[str]:
								pass





	def 				_lowercase(						self					)    ->    Tuple:
								self.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()





	def 				_lowercase(						self					)    ->    List[Any]:
								return





	def 				_lowercase(						self					)    ->    List[str]:
								UpperCAmelCase  :	Union[str, Any]							  =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_lowerCAmelCase					)





	def 				_lowercase(						self					)    ->    Optional[int]:
								UpperCAmelCase  :	List[Any]							  =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_backbone(*_lowerCAmelCase					)





	@unittest.skip("""Swin does not use inputs_embeds"""					)
	def 				_lowercase(						self					)    ->    List[str]:
								pass





	@unittest.skip("""Swin does not support feedforward chunking"""					)
	def 				_lowercase(						self					)    ->    Any:
								pass





	def 				_lowercase(						self					)    ->    List[str]:
								UpperCAmelCase  ,  UpperCAmelCase  :	Union[str, Any]							  =	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase  :	List[str]							  =	model_class(_lowerCAmelCase					)
															self.assertIsInstance(model.get_input_embeddings()	,	(nn.Module)					)
															UpperCAmelCase  :	str							  =	model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(_lowerCAmelCase	,	nn.Linear					)					)





	def 				_lowercase(						self					)    ->    List[Any]:
								UpperCAmelCase  ,  UpperCAmelCase  :	Tuple							  =	self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase  :	str							  =	model_class(_lowerCAmelCase					)
															UpperCAmelCase  :	Union[str, Any]							  =	inspect.signature(model.forward					)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															UpperCAmelCase  :	str							  =	[*signature.parameters.keys()]

															UpperCAmelCase  :	Optional[int]							  =	["""pixel_values"""]
															self.assertListEqual(arg_names[:1]	,	_lowerCAmelCase					)





	@unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""					)
	def 				_lowercase(						self					)    ->    List[str]:
								pass





	@unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone"""					)
	def 				_lowercase(						self					)    ->    List[str]:
								pass





	def 				_lowercase(						self	,	A	,	A	,	A	,	A					)    ->    Optional[int]:
								UpperCAmelCase  :	List[Any]							  =	model_class(_lowerCAmelCase					)
								model.to(_lowerCAmelCase					)
								model.eval()

								with torch.no_grad():
															UpperCAmelCase  :	Dict							  =	model(**self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase					)					)

								UpperCAmelCase  :	List[Any]							  =	outputs.hidden_states

								UpperCAmelCase  :	Any							  =	getattr(
								    self.model_tester	,	"""expected_num_hidden_layers"""	,	len(self.model_tester.depths					) + 1					)
								self.assertEqual(len(_lowerCAmelCase					)	,	_lowerCAmelCase					)

								# Swin has a different seq_length
								UpperCAmelCase  :	str							  =	(
								    config.patch_size
								    if isinstance(config.patch_size	,	collections.abc.Iterable					)
								    else (config.patch_size, config.patch_size)
								)

								UpperCAmelCase  :	List[str]							  =	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]					)	,	[num_patches, self.model_tester.embed_dim]	,	)





	def 				_lowercase(						self					)    ->    Optional[Any]:
								UpperCAmelCase  ,  UpperCAmelCase  :	Optional[int]							  =	self.model_tester.prepare_config_and_inputs_for_common()

								UpperCAmelCase  :	int							  =	(
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size	,	collections.abc.Iterable					)
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)

								for model_class in self.all_model_classes:
															UpperCAmelCase  :	Any							  =	True
															self.check_hidden_states_output(_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase					)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															UpperCAmelCase  :	str							  =	True

															self.check_hidden_states_output(_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase					)





	def 				_lowercase(						self					)    ->    Optional[Any]:
								UpperCAmelCase  ,  UpperCAmelCase  :	Tuple							  =	self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase  :	Dict							  =	3

								UpperCAmelCase  :	Union[str, Any]							  =	(
								    self.model_tester.image_size
								    if isinstance(self.model_tester.image_size	,	collections.abc.Iterable					)
								    else (self.model_tester.image_size, self.model_tester.image_size)
								)
								UpperCAmelCase  :	Optional[int]							  =	(
								    config.patch_size
								    if isinstance(config.patch_size	,	collections.abc.Iterable					)
								    else (config.patch_size, config.patch_size)
								)

								UpperCAmelCase  :	Optional[int]							  =	image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
								UpperCAmelCase  :	Dict							  =	image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

								for model_class in self.all_model_classes:
															UpperCAmelCase  :	List[Any]							  =	True
															self.check_hidden_states_output(_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase	,	(padded_height, padded_width)					)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															UpperCAmelCase  :	int							  =	True
															self.check_hidden_states_output(_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase	,	(padded_height, padded_width)					)





	@unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""					)
	def 				_lowercase(						self					)    ->    Optional[Any]:
								pass





	@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""					)
	def 				_lowercase(						self					)    ->    List[str]:
								pass





	@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""					)
	def 				_lowercase(						self					)    ->    Tuple:
								pass






	def 				_lowercase(						self					)    ->    Tuple:
								UpperCAmelCase  ,  UpperCAmelCase  :	str							  =	self.model_tester.prepare_config_and_inputs_for_common()

								def set_nan_tensor_to_zero(A					):
															UpperCAmelCase  :	str							  =	0
															return t

								def check_equivalence(A	,	A	,	A	,	A={}					):
															with torch.no_grad():
																						UpperCAmelCase  :	Union[str, Any]							  =	model(**_lowerCAmelCase	,	return_dict=_lowerCAmelCase	,	**_lowerCAmelCase					)
																						UpperCAmelCase  :	Optional[Any]							  =	model(**_lowerCAmelCase	,	return_dict=_lowerCAmelCase	,	**_lowerCAmelCase					).to_tuple()

																						def recursive_check(A	,	A					):
																													if isinstance(_lowerCAmelCase	,	(List, Tuple)					):
																																				for tuple_iterable_value, dict_iterable_value in zip(_lowerCAmelCase	,	_lowerCAmelCase					):
																																											recursive_check(_lowerCAmelCase	,	_lowerCAmelCase					)
																													elif isinstance(_lowerCAmelCase	,	_lowerCAmelCase					):
																																				for tuple_iterable_value, dict_iterable_value in zip(
																																				    tuple_object.values()	,	dict_object.values()					):
																																											recursive_check(_lowerCAmelCase	,	_lowerCAmelCase					)
																													elif tuple_object is None:
																																				return
																													else:
																																				self.assertTrue(
																																				    torch.allclose(
																																				        set_nan_tensor_to_zero(_lowerCAmelCase					)	,	set_nan_tensor_to_zero(_lowerCAmelCase					)	,	atol=1e-5					)	,	msg=(
																																				        """Tuple and dict output are not equal. Difference:"""
																																				        f''' {torch.max(torch.abs(tuple_object - dict_object					)					)}. Tuple has `nan`:'''
																																				        f''' {torch.isnan(_lowerCAmelCase					).any()} and `inf`: {torch.isinf(_lowerCAmelCase					)}. Dict has'''
																																				        f''' `nan`: {torch.isnan(_lowerCAmelCase					).any()} and `inf`: {torch.isinf(_lowerCAmelCase					)}.'''
																																				    )	,	)

																						recursive_check(_lowerCAmelCase	,	_lowerCAmelCase					)

								for model_class in self.all_model_classes:
															UpperCAmelCase  :	Optional[Any]							  =	model_class(_lowerCAmelCase					)
															model.to(_lowerCAmelCase					)
															model.eval()

															UpperCAmelCase  :	Optional[Any]							  =	self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase					)
															UpperCAmelCase  :	List[Any]							  =	self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase					)
															check_equivalence(_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase					)

															UpperCAmelCase  :	Any							  =	self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase	,	return_labels=_lowerCAmelCase					)
															UpperCAmelCase  :	Dict							  =	self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase	,	return_labels=_lowerCAmelCase					)
															check_equivalence(_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase					)

															UpperCAmelCase  :	str							  =	self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase					)
															UpperCAmelCase  :	str							  =	self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase					)
															check_equivalence(_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase	,	{"""output_hidden_states""": True}					)

															UpperCAmelCase  :	Optional[int]							  =	self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase	,	return_labels=_lowerCAmelCase					)
															UpperCAmelCase  :	str							  =	self._prepare_for_class(_lowerCAmelCase	,	_lowerCAmelCase	,	return_labels=_lowerCAmelCase					)
															check_equivalence(_lowerCAmelCase	,	_lowerCAmelCase	,	_lowerCAmelCase	,	{"""output_hidden_states""": True}					)




@require_torch
class     UpperCamelCase_				(							unittest.TestCase   ,  _lowerCAmelCase    ):
	lowercase    =				(MaskFormerSwinBackbone,) if is_torch_available() else ()
	lowercase    =				MaskFormerSwinConfig





	def 				_lowercase(						self					)    ->    Optional[int]:
								UpperCAmelCase  :	List[Any]							  =	MaskFormerSwinModelTester(self					)






	def 				_lowercase(						self					)    ->    List[str]:
								UpperCAmelCase  ,  UpperCAmelCase  :	str							  =	self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase  :	str							  =	inputs_dict["""pixel_values"""].shape[0]

								for backbone_class in self.all_model_classes:
															UpperCAmelCase  :	int							  =	backbone_class(_lowerCAmelCase					)
															backbone.to(_lowerCAmelCase					)
															backbone.eval()

															UpperCAmelCase  :	Union[str, Any]							  =	backbone(**_lowerCAmelCase					)

															# Test default outputs and verify feature maps
															self.assertIsInstance(outputs.feature_maps	,	_lowerCAmelCase					)
															self.assertTrue(len(outputs.feature_maps					) == len(backbone.channels					)					)
															for feature_map, n_channels in zip(outputs.feature_maps	,	backbone.channels					):
																						self.assertTrue(feature_map.shape[:2]	,	(batch_size, n_channels)					)
															self.assertIsNone(outputs.hidden_states					)
															self.assertIsNone(outputs.attentions					)

															# Test output_hidden_states=True
															UpperCAmelCase  :	Dict							  =	backbone(**_lowerCAmelCase	,	output_hidden_states=_lowerCAmelCase					)
															self.assertIsNotNone(outputs.hidden_states					)
															self.assertTrue(len(outputs.hidden_states					)	,	len(backbone.stage_names					)					)
															# We skip the stem layer
															for hidden_states, n_channels in zip(outputs.hidden_states[1:]	,	backbone.channels					):
																						for hidden_state in hidden_states:
																													# Hidden states are in the format (batch_size, (height * width), n_channels)
																													UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	Optional[int]							  =	hidden_state.shape
																													self.assertTrue((h_batch_size, h_n_channels)	,	(batch_size, n_channels)					)

            # Test output_attentions=True
															if self.has_attentions:
																						UpperCAmelCase  :	str							  =	backbone(**_lowerCAmelCase	,	output_attentions=_lowerCAmelCase					)
																						self.assertIsNotNone(outputs.attentions					)






'''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     :    List[str]      						=					logging.get_logger(__name__)

class     UpperCamelCase_				(							__magic_name__    ):





	def 				_lowercase(						self	,	A					)    ->    Optional[int]:
								if isinstance(A	,	A					):
															UpperCAmelCase  :	Union[str, Any]							  =	[label.strip() for label in labels.split(""","""					) if label.strip()]
								return labels






	def __call__(						self	,	A	,	A	,	A					)    ->    str:
								if len(A					) == 0 or len(A					) == 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(A					)					)

								if isinstance(A	,	A					):
															UpperCAmelCase  :	Tuple							  =	[sequences]

								UpperCAmelCase  :	Optional[Any]							  =	[]
								for sequence in sequences:
															sequence_pairs.extend([[sequence, hypothesis_template.format(A					)] for label in labels]					)

								return sequence_pairs, sequences




@add_end_docstrings(__magic_name__    )
class     UpperCamelCase_				(							__magic_name__    ):





	def __init__(						self	,	A=ZeroShotClassificationArgumentHandler()	,	*A	,	**A					)    ->    Optional[int]:
								UpperCAmelCase  :	Tuple							  =	args_parser
								super().__init__(*A	,	**A					)
								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 				_lowercase(						self					)    ->    List[Any]:
								for label, ind in self.model.config.labelaid.items():
															if label.lower().startswith("""entail"""					):
																						return ind
								return -1





	def 				_lowercase(						self	,	A	,	A=True	,	A=True	,	A=TruncationStrategy.ONLY_FIRST	,	**A					)    ->    str:
								UpperCAmelCase  :	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`"""					)
															UpperCAmelCase  :	Any							  =	self.tokenizer.eos_token
								try:
															UpperCAmelCase  :	Tuple							  =	self.tokenizer(
															    A	,	add_special_tokens=A	,	return_tensors=A	,	padding=A	,	truncation=A	,	)
								except Exception as e:
															if "too short" in str(A					):
																						# 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.

																						UpperCAmelCase  :	List[str]							  =	self.tokenizer(
																						    A	,	add_special_tokens=A	,	return_tensors=A	,	padding=A	,	truncation=TruncationStrategy.DO_NOT_TRUNCATE	,	)
															else:
																						raise e

								return inputs





	def 				_lowercase(						self	,	**A					)    ->    Tuple:
								if kwargs.get("""multi_class"""	,	A					) is not None:
															UpperCAmelCase  :	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."""					)
								UpperCAmelCase  :	int							  =	{}
								if "candidate_labels" in kwargs:
															UpperCAmelCase  :	Tuple							  =	self._args_parser._parse_labels(kwargs["""candidate_labels"""]					)
								if "hypothesis_template" in kwargs:
															UpperCAmelCase  :	List[Any]							  =	kwargs["""hypothesis_template"""]

								UpperCAmelCase  :	Dict							  =	{}
								if "multi_label" in kwargs:
															UpperCAmelCase  :	Union[str, Any]							  =	kwargs["""multi_label"""]
								return preprocess_params, {}, postprocess_params





	def __call__(						self	,	A	,	*A	,	**A	,	)    ->    Tuple:
								if len(A					) == 0:
															pass
								elif len(A					) == 1 and "candidate_labels" not in kwargs:
															UpperCAmelCase  :	Optional[Any]							  =	args[0]
								else:
															raise ValueError(f'''Unable to understand extra arguments {args}'''					)

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





	def 				_lowercase(						self	,	A	,	A=None	,	A="This example is {}."					)    ->    List[Any]:
								UpperCAmelCase  ,  UpperCAmelCase  :	List[Any]							  =	self._args_parser(A	,	A	,	A					)

								for i, (candidate_label, sequence_pair) in enumerate(zip(A	,	A					)					):
															UpperCAmelCase  :	Any							  =	self._parse_and_tokenize([sequence_pair]					)

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





	def 				_lowercase(						self	,	A					)    ->    Optional[int]:
								UpperCAmelCase  :	Optional[Any]							  =	inputs["""candidate_label"""]
								UpperCAmelCase  :	Tuple							  =	inputs["""sequence"""]
								UpperCAmelCase  :	List[Any]							  =	{k: inputs[k] for k in self.tokenizer.model_input_names}
								UpperCAmelCase  :	Tuple							  =	self.model(**A					)

								UpperCAmelCase  :	Optional[int]							  =	{
								    """candidate_label""": candidate_label,
								    """sequence""": sequence,
								    """is_last""": inputs["""is_last"""],
								    **outputs,
								}
								return model_outputs






	def 				_lowercase(						self	,	A	,	A=False					)    ->    List[str]:
								UpperCAmelCase  :	Dict							  =	[outputs["""candidate_label"""] for outputs in model_outputs]
								UpperCAmelCase  :	List[Any]							  =	[outputs["""sequence"""] for outputs in model_outputs]
								UpperCAmelCase  :	List[Any]							  =	np.concatenate([output["""logits"""].numpy() for output in model_outputs]					)
								UpperCAmelCase  :	Optional[Any]							  =	logits.shape[0]
								UpperCAmelCase  :	int							  =	len(A					)
								UpperCAmelCase  :	List[Any]							  =	N // n
								UpperCAmelCase  :	int							  =	logits.reshape((num_sequences, n, -1)					)

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

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

