

"""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						   =			logging.get_logger(__name__)





class     snake_case	(				__snake_case  ):

				def 							lowercase_     (	self							:				Any     ,  UpperCamelCase__							:				Any)->   List[Any]:



						'''simple docstring'''


						if isinstance(UpperCamelCase__     ,  UpperCamelCase__):
								__lowerCAmelCase:       str          =			[label.strip() for label in labels.split(",") if label.strip()]
						return labels




				def __call__(	self							:				Dict     ,  UpperCamelCase__							:				str     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				List[str])->   List[str]:



						'''simple docstring'''


						if len(UpperCamelCase__) == 0 or len(UpperCamelCase__) == 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(UpperCamelCase__))

						if isinstance(UpperCamelCase__     ,  UpperCamelCase__):
								__lowerCAmelCase:       Tuple          =			[sequences]

						__lowerCAmelCase:       Dict          =			[]
						for sequence in sequences:
								sequence_pairs.extend([[sequence, hypothesis_template.format(UpperCamelCase__)] for label in labels])

						return sequence_pairs, sequences





@add_end_docstrings(__snake_case  )
class     snake_case	(				__snake_case  ):

				def __init__(	self							:				Any     ,  UpperCamelCase__							:				Optional[Any]=ZeroShotClassificationArgumentHandler()     ,  *UpperCamelCase__							:				Dict     ,  **UpperCamelCase__							:				int)->   Tuple:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			args_parser
						super().__init__(*UpperCamelCase__     ,  **UpperCamelCase__)
						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							:				Any)->   Union[str, Any]:



						'''simple docstring'''


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

				def 							lowercase_     (	self							:				Optional[int]     ,  UpperCamelCase__							:				Tuple     ,  UpperCamelCase__							:				Union[str, Any]=True     ,  UpperCamelCase__							:				Union[str, Any]=True     ,  UpperCamelCase__							:				int=TruncationStrategy.ONLY_FIRST     ,  **UpperCamelCase__							:				Optional[Any])->   Any:



						'''simple docstring'''


						__lowerCAmelCase:       Any          =			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`")
								__lowerCAmelCase:       List[Any]          =			self.tokenizer.eos_token
						try:
								__lowerCAmelCase:       str          =			self.tokenizer(
								    UpperCamelCase__     ,  add_special_tokens=UpperCamelCase__     ,  return_tensors=UpperCamelCase__     ,  padding=UpperCamelCase__     ,  truncation=UpperCamelCase__     ,  )
						except Exception as e:
								if "too short" in str(UpperCamelCase__):
										# 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.

										__lowerCAmelCase:       Any          =			self.tokenizer(
										    UpperCamelCase__     ,  add_special_tokens=UpperCamelCase__     ,  return_tensors=UpperCamelCase__     ,  padding=UpperCamelCase__     ,  truncation=TruncationStrategy.DO_NOT_TRUNCATE     ,  )
								else:
										raise e

						return inputs

				def 							lowercase_     (	self							:				Dict     ,  **UpperCamelCase__							:				List[Any])->   List[Any]:



						'''simple docstring'''


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

						__lowerCAmelCase:       str          =			{}
						if "multi_label" in kwargs:
								__lowerCAmelCase:       List[str]          =			kwargs["multi_label"]
						return preprocess_params, {}, postprocess_params

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



						'''simple docstring'''


						if len(UpperCamelCase__) == 0:
								pass
						elif len(UpperCamelCase__) == 1 and "candidate_labels" not in kwargs:
								__lowerCAmelCase:       Optional[int]          =			args[0]
						else:
								raise ValueError(f"Unable to understand extra arguments {args}")

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

				def 							lowercase_     (	self							:				Union[str, Any]     ,  UpperCamelCase__							:				Optional[Any]     ,  UpperCamelCase__							:				List[str]=None     ,  UpperCamelCase__							:				str="This example is {}.")->   Any:



						'''simple docstring'''


						__lowerCAmelCase      , __lowerCAmelCase:       Optional[int]          =			self._args_parser(UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__)

						for i, (candidate_label, sequence_pair) in enumerate(zip(UpperCamelCase__     ,  UpperCamelCase__)):
								__lowerCAmelCase:       Optional[Any]          =			self._parse_and_tokenize([sequence_pair])

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

				def 							lowercase_     (	self							:				Tuple     ,  UpperCamelCase__							:				int)->   Any:



						'''simple docstring'''


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

						__lowerCAmelCase:       List[Any]          =			{
						    "candidate_label": candidate_label,
						    "sequence": sequence,
						    "is_last": inputs["is_last"],
						    **outputs,
						}
						return model_outputs




				def 							lowercase_     (	self							:				Dict     ,  UpperCamelCase__							:				str     ,  UpperCamelCase__							:				Any=False)->   Optional[int]:



						'''simple docstring'''


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

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

						__lowerCAmelCase:       List[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 packaging import version

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


__A						   =			logging.get_logger(__name__)

__A						   =			{
    "microsoft/beit-base-patch16-224-pt22k": (
        "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json"
    ),
    # See all BEiT models at https://huggingface.co/models?filter=beit
}





class     snake_case	(				__snake_case  ):
				SCREAMING_SNAKE_CASE_   :      Tuple         =  """beit"""

				def __init__(	self							:				List[Any]     ,  UpperCamelCase__							:				List[str]=8_1_9_2     ,  UpperCamelCase__							:				Dict=7_6_8     ,  UpperCamelCase__							:				List[str]=1_2     ,  UpperCamelCase__							:				Union[str, Any]=1_2     ,  UpperCamelCase__							:				Dict=3_0_7_2     ,  UpperCamelCase__							:				Optional[int]="gelu"     ,  UpperCamelCase__							:				Tuple=0.0     ,  UpperCamelCase__							:				Tuple=0.0     ,  UpperCamelCase__							:				Union[str, Any]=0.02     ,  UpperCamelCase__							:				Optional[Any]=1e-12     ,  UpperCamelCase__							:				str=2_2_4     ,  UpperCamelCase__							:				str=1_6     ,  UpperCamelCase__							:				Union[str, Any]=3     ,  UpperCamelCase__							:				Optional[int]=False     ,  UpperCamelCase__							:				int=False     ,  UpperCamelCase__							:				Optional[Any]=False     ,  UpperCamelCase__							:				Optional[Any]=False     ,  UpperCamelCase__							:				Dict=0.1     ,  UpperCamelCase__							:				List[Any]=0.1     ,  UpperCamelCase__							:				Any=True     ,  UpperCamelCase__							:				Optional[Any]=[3, 5, 7, 1_1]     ,  UpperCamelCase__							:				Optional[Any]=[1, 2, 3, 6]     ,  UpperCamelCase__							:				Optional[Any]=True     ,  UpperCamelCase__							:				Tuple=0.4     ,  UpperCamelCase__							:				Optional[Any]=2_5_6     ,  UpperCamelCase__							:				Optional[int]=1     ,  UpperCamelCase__							:				Optional[int]=False     ,  UpperCamelCase__							:				Optional[Any]=2_5_5     ,  **UpperCamelCase__							:				Optional[int]     ,  )->   int:



						'''simple docstring'''


						super().__init__(**UpperCamelCase__)

						__lowerCAmelCase:       str          =			vocab_size
						__lowerCAmelCase:       List[Any]          =			hidden_size
						__lowerCAmelCase:       str          =			num_hidden_layers
						__lowerCAmelCase:       Tuple          =			num_attention_heads
						__lowerCAmelCase:       Union[str, Any]          =			intermediate_size
						__lowerCAmelCase:       List[Any]          =			hidden_act
						__lowerCAmelCase:       Optional[Any]          =			hidden_dropout_prob
						__lowerCAmelCase:       List[Any]          =			attention_probs_dropout_prob
						__lowerCAmelCase:       str          =			initializer_range
						__lowerCAmelCase:       Optional[Any]          =			layer_norm_eps

						__lowerCAmelCase:       Any          =			image_size
						__lowerCAmelCase:       Any          =			patch_size
						__lowerCAmelCase:       Union[str, Any]          =			num_channels
						__lowerCAmelCase:       Tuple          =			use_mask_token
						__lowerCAmelCase:       Optional[Any]          =			use_absolute_position_embeddings
						__lowerCAmelCase:       List[Any]          =			use_relative_position_bias
						__lowerCAmelCase:       Optional[Any]          =			use_shared_relative_position_bias
						__lowerCAmelCase:       List[str]          =			layer_scale_init_value
						__lowerCAmelCase:       str          =			drop_path_rate
						__lowerCAmelCase:       str          =			use_mean_pooling
						# decode head attributes (semantic segmentation)
						__lowerCAmelCase:       Optional[Any]          =			out_indices
						__lowerCAmelCase:       Union[str, Any]          =			pool_scales
						# auxiliary head attributes (semantic segmentation)
						__lowerCAmelCase:       List[str]          =			use_auxiliary_head
						__lowerCAmelCase:       Union[str, Any]          =			auxiliary_loss_weight
						__lowerCAmelCase:       Optional[int]          =			auxiliary_channels
						__lowerCAmelCase:       Dict          =			auxiliary_num_convs
						__lowerCAmelCase:       List[Any]          =			auxiliary_concat_input
						__lowerCAmelCase:       str          =			semantic_loss_ignore_index





class     snake_case	(				__snake_case  ):
				SCREAMING_SNAKE_CASE_   :      Optional[Any]         =  version.parse("""1.11"""  )

				@property
				def 							lowercase_     (	self							:				str)->   Mapping[str, Mapping[int, str]]:



						'''simple docstring'''


						return OrderedDict(
						    [
						        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
						    ])




				@property
				def 							lowercase_     (	self							:				Any)->   float:



						'''simple docstring'''


						return 1e-4


