



"""simple docstring"""

from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
			import tensorflow as tf

			from ..tf_utils import stable_softmax


if is_torch_available():
			import torch


a_			   =					logging.get_logger(__name__)







@add_end_docstrings(
    _UpperCAmelCase					,    R"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """					,    )
class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						def 						__UpperCamelCase							(self   ,		lowercase__       ):
											if self.framework == "tf":
																snake_case_					:		Union[str, Any] 					=					tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()
											elif self.framework == "pt":
																snake_case_					:		str 					=					torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,		as_tuple=lowercase__       )
											else:
																raise ValueError("""Unsupported framework"""       )
											return masked_index







						def 						__UpperCamelCase							(self   ,		lowercase__       ):
											snake_case_					:		Optional[int] 					=					self.get_masked_index(lowercase__       )
											snake_case_					:		Tuple 					=					np.prod(masked_index.shape       )
											if numel < 1:
																raise PipelineException(
																    """fill-mask"""   ,		self.model.base_model_prefix   ,		f'No mask_token ({self.tokenizer.mask_token}) found on the input'   ,		)







						def 						__UpperCamelCase							(self   ,		lowercase__       ):
											if isinstance(lowercase__   ,		lowercase__       ):
																for model_input in model_inputs:
																					self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0]       )
											else:
																for input_ids in model_inputs["input_ids"]:
																					self._ensure_exactly_one_mask_token(lowercase__       )







						def 						__UpperCamelCase							(self   ,		lowercase__   ,		lowercase__=None   ,		**lowercase__       ):
											if return_tensors is None:
																snake_case_					:		str 					=					self.framework
											snake_case_					:		Dict 					=					self.tokenizer(lowercase__   ,		return_tensors=lowercase__       )
											self.ensure_exactly_one_mask_token(lowercase__       )
											return model_inputs







						def 						__UpperCamelCase							(self   ,		lowercase__       ):
											snake_case_					:		Tuple 					=					self.model(**lowercase__       )
											snake_case_					:		Optional[Any] 					=					model_inputs["""input_ids"""]
											return model_outputs







						def 						__UpperCamelCase							(self   ,		lowercase__   ,		lowercase__=5   ,		lowercase__=None       ):
											# Cap top_k if there are targets
											if target_ids is not None and target_ids.shape[0] < top_k:
																snake_case_					:		List[str] 					=					target_ids.shape[0]
											snake_case_					:		Union[str, Any] 					=					model_outputs["""input_ids"""][0]
											snake_case_					:		str 					=					model_outputs["""logits"""]

											if self.framework == "tf":
																snake_case_					:		Optional[int] 					=					tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()[:, 0]

																snake_case_					:		Union[str, Any] 					=					outputs.numpy()

																snake_case_					:		Dict 					=					outputs[0, masked_index, :]
																snake_case_					:		Optional[Any] 					=					stable_softmax(lowercase__   ,		axis=-1       )
																if target_ids is not None:
																					snake_case_					:		Tuple 					=					tf.gather_nd(tf.squeeze(lowercase__   ,		0       )   ,		target_ids.reshape(-1   ,		1       )       )
																					snake_case_					:		List[str] 					=					tf.expand_dims(lowercase__   ,		0       )

																snake_case_					:		str 					=					tf.math.top_k(lowercase__   ,		k=lowercase__       )
																snake_case_					,			snake_case_					:		Any 					=					topk.values.numpy(), topk.indices.numpy()
											else:
																snake_case_					:		List[Any] 					=					torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,		as_tuple=lowercase__       ).squeeze(-1       )
																# Fill mask pipeline supports only one ${mask_token} per sample

																snake_case_					:		List[Any] 					=					outputs[0, masked_index, :]
																snake_case_					:		Any 					=					logits.softmax(dim=-1       )
																if target_ids is not None:
																					snake_case_					:		int 					=					probs[..., target_ids]

																snake_case_					,			snake_case_					:		Dict 					=					probs.topk(lowercase__       )

											snake_case_					:		Tuple 					=					[]
											snake_case_					:		Union[str, Any] 					=					values.shape[0] == 1
											for i, (_values, _predictions) in enumerate(zip(values.tolist()   ,		predictions.tolist()       )       ):
																snake_case_					:		int 					=					[]
																for v, p in zip(_values   ,		_predictions       ):
																					# Copy is important since we're going to modify this array in place
																					snake_case_					:		Any 					=					input_ids.numpy().copy()
																					if target_ids is not None:
																										snake_case_					:		int 					=					target_ids[p].tolist()

																					snake_case_					:		Union[str, Any] 					=					p
																					# Filter padding out:
																					snake_case_					:		int 					=					tokens[np.where(tokens != self.tokenizer.pad_token_id       )]
																					# Originally we skip special tokens to give readable output.
																					# For multi masks though, the other [MASK] would be removed otherwise
																					# making the output look odd, so we add them back
																					snake_case_					:		Dict 					=					self.tokenizer.decode(lowercase__   ,		skip_special_tokens=lowercase__       )
																					snake_case_					:		List[str] 					=					{"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]       ), """sequence""": sequence}
																					row.append(lowercase__       )
																result.append(lowercase__       )
											if single_mask:
																return result[0]
											return result







						def 						__UpperCamelCase							(self   ,		lowercase__   ,		lowercase__=None       ):
											if isinstance(lowercase__   ,		lowercase__       ):
																snake_case_					:		Union[str, Any] 					=					[targets]
											try:
																snake_case_					:		Union[str, Any] 					=					self.tokenizer.get_vocab()
											except Exception:
																snake_case_					:		Any 					=					{}
											snake_case_					:		Optional[int] 					=					[]
											for target in targets:
																snake_case_					:		Optional[Any] 					=					vocab.get(lowercase__   ,		lowercase__       )
																if id_ is None:
																					snake_case_					:		int 					=					self.tokenizer(
																					    lowercase__   ,		add_special_tokens=lowercase__   ,		return_attention_mask=lowercase__   ,		return_token_type_ids=lowercase__   ,		max_length=1   ,		truncation=lowercase__   ,		)["""input_ids"""]
																					if len(lowercase__       ) == 0:
																										logger.warning(
																										    f'The specified target token `{target}` does not exist in the model vocabulary. '
																										    """We cannot replace it with anything meaningful, ignoring it"""       )
																										continue
																					snake_case_					:		int 					=					input_ids[0]
																					# XXX: If users encounter this pass
																					# it becomes pretty slow, so let's make sure
																					# The warning enables them to fix the input to
																					# get faster performance.
																					logger.warning(
																					    f'The specified target token `{target}` does not exist in the model vocabulary. '
																					    f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_       )}`.'       )
																target_ids.append(id_       )
											snake_case_					:		str 					=					list(set(lowercase__       )       )
											if len(lowercase__       ) == 0:
																raise ValueError("""At least one target must be provided when passed."""       )
											snake_case_					:		List[str] 					=					np.array(lowercase__       )
											return target_ids







						def 						__UpperCamelCase							(self   ,		lowercase__=None   ,		lowercase__=None       ):
											snake_case_					:		List[Any] 					=					{}

											if targets is not None:
																snake_case_					:		Union[str, Any] 					=					self.get_target_ids(lowercase__   ,		lowercase__       )
																snake_case_					:		Optional[Any] 					=					target_ids

											if top_k is not None:
																snake_case_					:		List[str] 					=					top_k

											if self.tokenizer.mask_token_id is None:
																raise PipelineException(
																    """fill-mask"""   ,		self.model.base_model_prefix   ,		"""The tokenizer does not define a `mask_token`."""       )
											return {}, {}, postprocess_params







						def __call__(self   ,		lowercase__   ,		*lowercase__   ,		**lowercase__       ):
											snake_case_					:		Tuple 					=					super().__call__(lowercase__   ,		**lowercase__       )
											if isinstance(lowercase__   ,		lowercase__       ) and len(lowercase__       ) == 1:
																return outputs[0]
											return outputs









"""simple docstring"""

import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import CONFIG_MAPPING


a_			   =					logging.get_logger(__name__)







class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						_A		:							Optional[int]							       =		"""upernet"""







						def __init__(self   ,		lowercase__=None   ,		lowercase__=5_12   ,		lowercase__=0.02   ,		lowercase__=[1, 2, 3, 6]   ,		lowercase__=True   ,		lowercase__=0.4   ,		lowercase__=3_84   ,		lowercase__=2_56   ,		lowercase__=1   ,		lowercase__=False   ,		lowercase__=2_55   ,		**lowercase__   ,		):
											super().__init__(**lowercase__       )

											if backbone_config is None:
																logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""       )
																snake_case_					:		List[Any] 					=					CONFIG_MAPPING["""resnet"""](out_features=["""stage1""", """stage2""", """stage3""", """stage4"""]       )
											elif isinstance(lowercase__   ,		lowercase__       ):
																snake_case_					:		Tuple 					=					backbone_config.get("""model_type"""       )
																snake_case_					:		List[str] 					=					CONFIG_MAPPING[backbone_model_type]
																snake_case_					:		List[Any] 					=					config_class.from_dict(lowercase__       )

											snake_case_					:		List[Any] 					=					backbone_config
											snake_case_					:		Optional[Any] 					=					hidden_size
											snake_case_					:		Any 					=					initializer_range
											snake_case_					:		str 					=					pool_scales
											snake_case_					:		Dict 					=					use_auxiliary_head
											snake_case_					:		str 					=					auxiliary_loss_weight
											snake_case_					:		List[str] 					=					auxiliary_in_channels
											snake_case_					:		Optional[Any] 					=					auxiliary_channels
											snake_case_					:		Any 					=					auxiliary_num_convs
											snake_case_					:		List[Any] 					=					auxiliary_concat_input
											snake_case_					:		List[str] 					=					loss_ignore_index







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Dict 					=					copy.deepcopy(self.__dict__       )
											snake_case_					:		Union[str, Any] 					=					self.backbone_config.to_dict()
											snake_case_					:		Any 					=					self.__class__.model_type
											return output




