

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"\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    "				,       )
class 				UpperCAmelCase_		(			UpperCAmelCase__   ):
							"""simple docstring"""







							def 				__lowercase				(			self       ,							_a       )    ->    Union[str, Any]:

												if self.framework == "tf":
																	_a	:    str         =		tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()
												elif self.framework == "pt":
																	_a	:    List[str]         =		torch.nonzero(input_ids == self.tokenizer.mask_token_id       ,							as_tuple=snake_case_       )
												else:
																	raise ValueError('''Unsupported framework'''       )
												return masked_index


							def 				__lowercase				(			self       ,							_a       )    ->    Optional[int]:
												_a	:    List[str]         =		self.get_masked_index(snake_case_       )
												_a	:    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 				__lowercase				(			self       ,							_a       )    ->    List[str]:

												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 				__lowercase				(			self       ,							_a       ,							_a=None       ,							**_a       )    ->    Tuple:

												if return_tensors is None:
																	_a	:    Any         =		self.framework
												_a	:    Dict         =		self.tokenizer(snake_case_       ,							return_tensors=snake_case_       )
												self.ensure_exactly_one_mask_token(snake_case_       )
												return model_inputs


							def 				__lowercase				(			self       ,							_a       )    ->    Optional[Any]:
												_a	:    Dict         =		self.model(**snake_case_       )
												_a	:    Optional[int]         =		model_inputs['input_ids']
												return model_outputs


							def 				__lowercase				(			self       ,							_a       ,							_a=5       ,							_a=None       )    ->    Union[str, Any]:

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

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

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

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

																	_a	:    Any         =		tf.math.top_k(snake_case_       ,							k=snake_case_       )
																	_a	:    str         =		topk.values.numpy(), topk.indices.numpy()
												else:
																	_a	:    int         =		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

																	_a	:    Tuple         =		outputs[0, masked_index, :]
																	_a	:    List[str]         =		logits.softmax(dim=-1       )
																	if target_ids is not None:
																						_a	:    str         =		probs[..., target_ids]

																	_a	:    List[str]         =		probs.topk(snake_case_       )

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

																						_a	:    Union[str, Any]         =		p
																						# Filter padding out:
																						_a	:    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
																						_a	:    Any         =		self.tokenizer.decode(snake_case_       ,							skip_special_tokens=snake_case_       )
																						_a	:    Any         =		{'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 				__lowercase				(			self       ,							_a       ,							_a=None       )    ->    Any:

												if isinstance(snake_case_       ,							snake_case_       ):
																	_a	:    List[str]         =		[targets]
												try:
																	_a	:    Optional[int]         =		self.tokenizer.get_vocab()
												except Exception:
																	_a	:    int         =		{}
												_a	:    Tuple         =		[]
												for target in targets:
																	_a	:    int         =		vocab.get(snake_case_       ,							snake_case_       )
																	if id_ is None:
																						_a	:    Tuple         =		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
																						_a	:    str         =		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_       )
												_a	:    Tuple         =		list(set(snake_case_       )       )
												if len(snake_case_       ) == 0:
																	raise ValueError('''At least one target must be provided when passed.'''       )
												_a	:    Optional[Any]         =		np.array(snake_case_       )
												return target_ids


							def 				__lowercase				(			self       ,							_a=None       ,							_a=None       )    ->    int:
												_a	:    List[str]         =		{}

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

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

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase_     :						Union[str, Any]						=					logging.get_logger(__name__)

lowerCamelCase_     :						Optional[Any]						=					{
    'huggingface/informer-tourism-monthly': (
        'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json'
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}

class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_      : Tuple	    =   """informer"""
      lowercase_      : str	    =   {
          """hidden_size""": """d_model""",
          """num_attention_heads""": """encoder_attention_heads""",
          """num_hidden_layers""": """encoder_layers""",
      }

      def __init__(     self					,      snake_case_ = None					,      snake_case_ = None					,      snake_case_ = "student_t"					,      snake_case_ = "nll"					,      snake_case_ = 1					,      snake_case_ = None					,      snake_case_ = "mean"					,      snake_case_ = 0					,      snake_case_ = 0					,      snake_case_ = 0					,      snake_case_ = 0					,      snake_case_ = None					,      snake_case_ = None					,      snake_case_ = 6_4					,      snake_case_ = 3_2					,      snake_case_ = 3_2					,      snake_case_ = 2					,      snake_case_ = 2					,      snake_case_ = 2					,      snake_case_ = 2					,      snake_case_ = True					,      snake_case_ = "gelu"					,      snake_case_ = 0.05					,      snake_case_ = 0.1					,      snake_case_ = 0.1					,      snake_case_ = 0.1					,      snake_case_ = 0.1					,      snake_case_ = 1_0_0					,      snake_case_ = 0.02					,      snake_case_=True					,      snake_case_ = "prob"					,      snake_case_ = 5					,      snake_case_ = True					,      **snake_case_					,      ):

        """simple docstring"""

        A_  :       str										=  prediction_length
        A_  :       List[Any]										=  context_length or prediction_length
        A_  :       str										=  distribution_output
        A_  :       Dict										=  loss
        A_  :       Any										=  input_size
        A_  :       Union[str, Any]										=  num_time_features
        A_  :       Optional[Any]										=  lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
        A_  :       List[Any]										=  scaling
        A_  :       Tuple										=  num_dynamic_real_features
        A_  :       Any										=  num_static_real_features
        A_  :       str										=  num_static_categorical_features

        # set cardinality
        if cardinality and num_static_categorical_features > 0:
          if len(snake_case_  ) != num_static_categorical_features:
            raise ValueError(
                'The cardinality should be a list of the same length as `num_static_categorical_features`'  )
          A_  :       Optional[int]										=  cardinality
        else:
          A_  :       Optional[Any]										=  [0]

        # set embedding_dimension
        if embedding_dimension and num_static_categorical_features > 0:
          if len(snake_case_  ) != num_static_categorical_features:
            raise ValueError(
                'The embedding dimension should be a list of the same length as `num_static_categorical_features`'  )
          A_  :       Any										=  embedding_dimension
        else:
          A_  :       Optional[Any]										=  [min(5_0					,      (cat + 1) // 2  ) for cat in self.cardinality]

        A_  :       int										=  num_parallel_samples

        # Transformer architecture configuration
        A_  :       str										=  input_size * len(self.lags_sequence  ) + self._number_of_features
        A_  :       List[Any]										=  d_model
        A_  :       Dict										=  encoder_attention_heads
        A_  :       Dict										=  decoder_attention_heads
        A_  :       List[Any]										=  encoder_ffn_dim
        A_  :       Union[str, Any]										=  decoder_ffn_dim
        A_  :       int										=  encoder_layers
        A_  :       Any										=  decoder_layers

        A_  :       List[Any]										=  dropout
        A_  :       str										=  attention_dropout
        A_  :       Tuple										=  activation_dropout
        A_  :       List[str]										=  encoder_layerdrop
        A_  :       List[str]										=  decoder_layerdrop

        A_  :       str										=  activation_function
        A_  :       Optional[int]										=  init_std

        A_  :       List[Any]										=  use_cache

        # Informer
        A_  :       Tuple										=  attention_type
        A_  :       List[Any]										=  sampling_factor
        A_  :       Optional[int]										=  distil

        super().__init__(is_encoder_decoder=snake_case_					,      **snake_case_  )

      @property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        return (
            sum(self.embedding_dimension  )
            + self.num_dynamic_real_features
            + self.num_time_features
            + self.num_static_real_features
            + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
        )