

'''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


lowerCAmelCase__						:       Optional[Any]										=						logging.get_logger(__name__)




@add_end_docstrings(
    SCREAMING_SNAKE_CASE			,			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     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




						def       __magic_name__							(							self					:      Dict			,			snake_case_					:      GenericTensor  ):



								'''simple docstring'''



								if self.framework == "tf":
										snake_case__						:       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=snake_case_  )
								else:
										raise ValueError('''Unsupported framework'''  )
								return masked_index







						def       __magic_name__							(							self					:      List[str]			,			snake_case_					:      GenericTensor  ):



								'''simple docstring'''



								snake_case__						:       Tuple       						=  self.get_masked_index(snake_case_  )
								snake_case__						:       str       						=  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       __magic_name__							(							self					:      Optional[int]			,			snake_case_					:      GenericTensor  ):



								'''simple docstring'''



								if isinstance(snake_case_			,			snake_case_  ):
										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(snake_case_  )







						def       __magic_name__							(							self					:      Union[str, Any]			,			snake_case_					:      str			,			snake_case_					:      Optional[int]=None			,			**snake_case_					:      Tuple  ):



								'''simple docstring'''



								if return_tensors is None:
										snake_case__						:       List[Any]       						=  self.framework
								snake_case__						:       Any       						=  self.tokenizer(snake_case_			,			return_tensors=snake_case_  )
								self.ensure_exactly_one_mask_token(snake_case_  )
								return model_inputs







						def       __magic_name__							(							self					:      Union[str, Any]			,			snake_case_					:      str  ):



								'''simple docstring'''



								snake_case__						:       Union[str, Any]       						=  self.model(**snake_case_  )
								snake_case__						:       Union[str, Any]       						=  model_inputs['''input_ids''']
								return model_outputs







						def       __magic_name__							(							self					:      Dict			,			snake_case_					:      Optional[Any]			,			snake_case_					:      List[Any]=5			,			snake_case_					:      List[Any]=None  ):



								'''simple docstring'''



								if target_ids is not None and target_ids.shape[0] < top_k:
										snake_case__						:       List[Any]       						=  target_ids.shape[0]
								snake_case__						:       int       						=  model_outputs['''input_ids'''][0]
								snake_case__						:       Optional[Any]       						=  model_outputs['''logits''']

								if self.framework == "tf":
										snake_case__						:       str       						=  tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()[:, 0]

										snake_case__						:       int       						=  outputs.numpy()

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

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

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

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

								snake_case__						:       Tuple       						=  []
								snake_case__						:       int       						=  values.shape[0] == 1
								for i, (_values, _predictions) in enumerate(zip(values.tolist()			,			predictions.tolist()  )  ):
										snake_case__						:       Dict       						=  []
										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__						:       Optional[int]       						=  target_ids[p].tolist()

												snake_case__						:       Any       						=  p
												# Filter padding out:
												snake_case__						:       List[Any]       						=  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__						:       Optional[int]       						=  self.tokenizer.decode(snake_case_			,			skip_special_tokens=snake_case_  )
												snake_case__						:       int       						=  {'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]  ), '''sequence''': sequence}
												row.append(snake_case_  )
										result.append(snake_case_  )
								if single_mask:
										return result[0]
								return result







						def       __magic_name__							(							self					:      Optional[int]			,			snake_case_					:      Dict			,			snake_case_					:      Any=None  ):



								'''simple docstring'''



								if isinstance(snake_case_			,			snake_case_  ):
										snake_case__						:       int       						=  [targets]
								try:
										snake_case__						:       Any       						=  self.tokenizer.get_vocab()
								except Exception:
										snake_case__						:       Union[str, Any]       						=  {}
								snake_case__						:       Any       						=  []
								for target in targets:
										snake_case__						:       int       						=  vocab.get(snake_case_			,			snake_case_  )
										if id_ is None:
												snake_case__						:       Dict       						=  self.tokenizer(
												    snake_case_			,			add_special_tokens=snake_case_			,			return_attention_mask=snake_case_			,			return_token_type_ids=snake_case_			,			max_length=1			,			truncation=snake_case_			,			)['''input_ids''']
												if len(snake_case_  ) == 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__						:       Union[str, Any]       						=  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__						:       List[str]       						=  list(set(snake_case_  )  )
								if len(snake_case_  ) == 0:
										raise ValueError('''At least one target must be provided when passed.'''  )
								snake_case__						:       List[Any]       						=  np.array(snake_case_  )
								return target_ids







						def       __magic_name__							(							self					:      Optional[int]			,			snake_case_					:      List[str]=None			,			snake_case_					:      str=None  ):



								'''simple docstring'''



								snake_case__						:       Optional[int]       						=  {}

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

								if top_k is not None:
										snake_case__						:       Dict       						=  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					:      List[str]			,			snake_case_					:      Dict			,			*snake_case_					:      Union[str, Any]			,			**snake_case_					:      int  ):



								'''simple docstring'''



								snake_case__						:       int       						=  super().__call__(snake_case_			,			**snake_case_  )
								if isinstance(snake_case_			,			snake_case_  ) and len(snake_case_  ) == 1:
										return outputs[0]
								return outputs






'''simple docstring'''


from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
					import timm


if is_torch_available():
					from torch import Tensor




class     a			(				SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




						__UpperCAmelCase			     =    """pixel_values"""
						__UpperCAmelCase			     =    False
						__UpperCAmelCase			     =    TimmBackboneConfig







						def __init__(							self					:      str			,			snake_case_					:      str			,			**snake_case_					:      Dict  ):



								'''simple docstring'''



								requires_backends(self			,			'''timm'''  )
								super().__init__(snake_case_  )
								snake_case__						:       List[str]       						=  config

								if config.backbone is None:
										raise ValueError('''backbone is not set in the config. Please set it to a timm model name.'''  )

								if config.backbone not in timm.list_models():
										raise ValueError(F"""backbone {config.backbone} is not supported by timm."""  )

								if hasattr(snake_case_			,			'''out_features'''  ) and config.out_features is not None:
										raise ValueError('''out_features is not supported by TimmBackbone. Please use out_indices instead.'''  )

								snake_case__						:       Dict       						=  getattr(snake_case_			,			'''use_pretrained_backbone'''			,			snake_case_  )
								if pretrained is None:
										raise ValueError('''use_pretrained_backbone is not set in the config. Please set it to True or False.'''  )

								# We just take the final layer by default. This matches the default for the transformers models.
								snake_case__						:       int       						=  config.out_indices if getattr(snake_case_			,			'''out_indices'''			,			snake_case_  ) is not None else (-1,)

								snake_case__						:       Any       						=  timm.create_model(
								    config.backbone			,			pretrained=snake_case_			,			features_only=config.features_only			,			in_chans=config.num_channels			,			out_indices=snake_case_			,			**snake_case_			,			)
								# These are used to control the output of the model when called. If output_hidden_states is True, then
								# return_layers is modified to include all layers.
								snake_case__						:       str       						=  self._backbone.return_layers
								snake_case__						:       List[Any]       						=  {layer['''module''']: str(snake_case_  ) for i, layer in enumerate(self._backbone.feature_info.info  )}
								super()._init_backbone(snake_case_  )







						@classmethod
						def       __magic_name__							(							cls					:      Union[str, Any]			,			snake_case_					:      Union[str, Any]			,			*snake_case_					:      Optional[Any]			,			**snake_case_					:      Optional[Any]  ):



								'''simple docstring'''



								requires_backends(cls			,			['''vision''', '''timm''']  )
								from ...models.timm_backbone import TimmBackboneConfig

								snake_case__						:       Dict       						=  kwargs.pop('''config'''			,			TimmBackboneConfig()  )

								snake_case__						:       Optional[Any]       						=  kwargs.pop('''use_timm_backbone'''			,			snake_case_  )
								if not use_timm:
										raise ValueError('''use_timm_backbone must be True for timm backbones'''  )

								snake_case__						:       List[Any]       						=  kwargs.pop('''num_channels'''			,			config.num_channels  )
								snake_case__						:       Optional[Any]       						=  kwargs.pop('''features_only'''			,			config.features_only  )
								snake_case__						:       Tuple       						=  kwargs.pop('''use_pretrained_backbone'''			,			config.use_pretrained_backbone  )
								snake_case__						:       Union[str, Any]       						=  kwargs.pop('''out_indices'''			,			config.out_indices  )
								snake_case__						:       int       						=  TimmBackboneConfig(
								    backbone=snake_case_			,			num_channels=snake_case_			,			features_only=snake_case_			,			use_pretrained_backbone=snake_case_			,			out_indices=snake_case_			,			)
								return super()._from_config(snake_case_			,			**snake_case_  )







						def       __magic_name__							(							self					:      List[str]			,			snake_case_					:      Union[str, Any]  ):



								'''simple docstring'''



								pass







						def       __magic_name__							(							self					:      Optional[int]			,			snake_case_					:      Union[str, Any]			,			snake_case_					:      Tuple=None			,			snake_case_					:      Tuple=None			,			snake_case_					:      Optional[Any]=None			,			**snake_case_					:      List[str]  ):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  return_dict if return_dict is not None else self.config.use_return_dict
								snake_case__						:       Optional[int]       						=  (
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								snake_case__						:       int       						=  output_attentions if output_attentions is not None else self.config.output_attentions

								if output_attentions:
										raise ValueError('''Cannot output attentions for timm backbones at the moment'''  )

								if output_hidden_states:
										# We modify the return layers to include all the stages of the backbone
										snake_case__						:       Any       						=  self._all_layers
										snake_case__						:       str       						=  self._backbone(snake_case_			,			**snake_case_  )
										snake_case__						:       Tuple       						=  self._return_layers
										snake_case__						:       str       						=  tuple(hidden_states[i] for i in self.out_indices  )
								else:
										snake_case__						:       Dict       						=  self._backbone(snake_case_			,			**snake_case_  )
										snake_case__						:       Any       						=  None

								snake_case__						:       Union[str, Any]       						=  tuple(snake_case_  )
								snake_case__						:       Optional[int]       						=  tuple(snake_case_  ) if hidden_states is not None else None

								if not return_dict:
										snake_case__						:       List[str]       						=  (feature_maps,)
										if output_hidden_states:
												snake_case__						:       Optional[int]       						=  output + (hidden_states,)
										return output

								return BackboneOutput(feature_maps=snake_case_			,			hidden_states=snake_case_			,			attentions=snake_case_  )



