


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


UpperCAmelCase_				:			Dict   =	logging.get_logger(__name__)
@add_end_docstrings(
    lowercase__						,   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 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	GenericTensor					)		->      np.ndarray:
             if self.framework == "tf":
                    a_ :		Optional[Any]							=  tf.where(input_ids == self.tokenizer.mask_token_id					).numpy()
             elif self.framework == "pt":
                    a_ :		Dict							=  torch.nonzero(input_ids == self.tokenizer.mask_token_id					,							as_tuple=SCREAMING_SNAKE_CASE__					)
             else:
                    raise ValueError('Unsupported framework'					)
             return masked_index
      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	GenericTensor					)		->      np.ndarray:
             a_ :		List[str]							=  self.get_masked_index(SCREAMING_SNAKE_CASE__					)
             a_ :		Optional[Any]							=  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 	SCREAMING_SNAKE_CASE							(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	GenericTensor					)		->      Tuple:
             if isinstance(SCREAMING_SNAKE_CASE__					,							SCREAMING_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(SCREAMING_SNAKE_CASE__					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	str					,							SCREAMING_SNAKE_CASE__    :	int=None					,							**SCREAMING_SNAKE_CASE__    :	Tuple					)		->      Dict[str, GenericTensor]:
             if return_tensors is None:
                    a_ :		str							=  self.framework
             a_ :		Tuple							=  self.tokenizer(SCREAMING_SNAKE_CASE__					,							return_tensors=SCREAMING_SNAKE_CASE__					)
             self.ensure_exactly_one_mask_token(SCREAMING_SNAKE_CASE__					)
             return model_inputs
      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					)		->      str:
             a_ :		Dict							=  self.model(**SCREAMING_SNAKE_CASE__					)
             a_ :		List[Any]							=  model_inputs['input_ids']
             return model_outputs
      def 	SCREAMING_SNAKE_CASE							(	self    :	int					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	str=5					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=None					)		->      Optional[Any]:
             # Cap top_k if there are targets
             if target_ids is not None and target_ids.shape[0] < top_k:
                    a_ :		str							=  target_ids.shape[0]
             a_ :		Dict							=  model_outputs['input_ids'][0]
             a_ :		Tuple							=  model_outputs['logits']

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

                    a_ :		Any							=  outputs.numpy()

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

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

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

                    a_ :		str							=  probs.topk(SCREAMING_SNAKE_CASE__					)

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

                           a_ :		Optional[int]							=  p
                           # Filter padding out:
                           a_ :		Optional[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
                           a_ :		Union[str, Any]							=  self.tokenizer.decode(SCREAMING_SNAKE_CASE__					,							skip_special_tokens=SCREAMING_SNAKE_CASE__					)
                           a_ :		List[str]							=  {'score': v, 'token': p, 'token_str': self.tokenizer.decode([p]					), 'sequence': sequence}
                           row.append(SCREAMING_SNAKE_CASE__					)
                    result.append(SCREAMING_SNAKE_CASE__					)
             if single_mask:
                    return result[0]
             return result
      def 	SCREAMING_SNAKE_CASE							(	self    :	int					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	int=None					)		->      str:
             if isinstance(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					):
                    a_ :		Union[str, Any]							=  [targets]
             try:
                    a_ :		Union[str, Any]							=  self.tokenizer.get_vocab()
             except Exception:
                    a_ :		Optional[int]							=  {}
             a_ :		Any							=  []
             for target in targets:
                    a_ :		Optional[int]							=  vocab.get(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					)
                    if id_ is None:
                           a_ :		str							=  self.tokenizer(
                               SCREAMING_SNAKE_CASE__					,							add_special_tokens=SCREAMING_SNAKE_CASE__					,							return_attention_mask=SCREAMING_SNAKE_CASE__					,							return_token_type_ids=SCREAMING_SNAKE_CASE__					,							max_length=1					,							truncation=SCREAMING_SNAKE_CASE__					,							)['input_ids']
                           if len(SCREAMING_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_ :		Optional[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_					)
             a_ :		Optional[int]							=  list(set(SCREAMING_SNAKE_CASE__					)					)
             if len(SCREAMING_SNAKE_CASE__					) == 0:
                    raise ValueError('At least one target must be provided when passed.'					)
             a_ :		List[str]							=  np.array(SCREAMING_SNAKE_CASE__					)
             return target_ids
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	Any=None					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=None					)		->      List[str]:
             a_ :		Any							=  {}

             if targets is not None:
                    a_ :		List[str]							=  self.get_target_ids(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					)
                    a_ :		Any							=  target_ids

             if top_k is not None:
                    a_ :		Tuple							=  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    :	int					,							SCREAMING_SNAKE_CASE__    :	List[str]					,							*SCREAMING_SNAKE_CASE__    :	List[Any]					,							**SCREAMING_SNAKE_CASE__    :	Dict					)		->      Dict:
             a_ :		Optional[Any]							=  super().__call__(SCREAMING_SNAKE_CASE__					,							**SCREAMING_SNAKE_CASE__					)
             if isinstance(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					) and len(SCREAMING_SNAKE_CASE__					) == 1:
                    return outputs[0]
             return outputs






import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


UpperCAmelCase_				:			str   =	logging.get_logger(__name__)

UpperCAmelCase_				:			str   =	{
    'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json',
}
class 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      snake_case__    :					int					       =						'''instructblip_vision_model'''
      def __init__(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	List[Any]=1_4_0_8					,							SCREAMING_SNAKE_CASE__    :	int=6_1_4_4					,							SCREAMING_SNAKE_CASE__    :	Dict=3_9					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]=1_6					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]=2_2_4					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=1_4					,							SCREAMING_SNAKE_CASE__    :	List[Any]="gelu"					,							SCREAMING_SNAKE_CASE__    :	List[str]=1E-6					,							SCREAMING_SNAKE_CASE__    :	Tuple=0.0					,							SCREAMING_SNAKE_CASE__    :	List[str]=1E-10					,							SCREAMING_SNAKE_CASE__    :	str=True					,							**SCREAMING_SNAKE_CASE__    :	Dict					,							)		->      int:
             super().__init__(**SCREAMING_SNAKE_CASE__					)

             a_ :		List[str]							=  hidden_size
             a_ :		Any							=  intermediate_size
             a_ :		str							=  num_hidden_layers
             a_ :		Dict							=  num_attention_heads
             a_ :		str							=  patch_size
             a_ :		Any							=  image_size
             a_ :		Dict							=  initializer_range
             a_ :		List[Any]							=  attention_dropout
             a_ :		Union[str, Any]							=  layer_norm_eps
             a_ :		Optional[Any]							=  hidden_act
             a_ :		Optional[Any]							=  qkv_bias

      @classmethod
      def 	SCREAMING_SNAKE_CASE							(	cls    :	Any					,							SCREAMING_SNAKE_CASE__    :	Union[str, os.PathLike]					,							**SCREAMING_SNAKE_CASE__    :	List[str]					)		->      "PretrainedConfig":
             cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__					)

             a_							,		a_ :		Dict							=  cls.get_config_dict(SCREAMING_SNAKE_CASE__					,							**SCREAMING_SNAKE_CASE__					)

             # get the vision config dict if we are loading from InstructBlipConfig
             if config_dict.get('model_type'					) == "instructblip":
                    a_ :		List[Any]							=  config_dict['vision_config']

             if "model_type" in config_dict and hasattr(cls					,							'model_type'					) and config_dict["model_type"] != cls.model_type:
                    logger.warning(
                        F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
                        F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""					)

             return cls.from_dict(SCREAMING_SNAKE_CASE__					,							**SCREAMING_SNAKE_CASE__					)
class 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      snake_case__    :					List[Any]					       =						'''instructblip_qformer'''
      def __init__(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]=3_0_5_2_2					,							SCREAMING_SNAKE_CASE__    :	str=7_6_8					,							SCREAMING_SNAKE_CASE__    :	List[str]=1_2					,							SCREAMING_SNAKE_CASE__    :	Any=1_2					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=3_0_7_2					,							SCREAMING_SNAKE_CASE__    :	List[str]="gelu"					,							SCREAMING_SNAKE_CASE__    :	Dict=0.1					,							SCREAMING_SNAKE_CASE__    :	int=0.1					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=5_1_2					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]=0.02					,							SCREAMING_SNAKE_CASE__    :	int=1E-12					,							SCREAMING_SNAKE_CASE__    :	Dict=0					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]="absolute"					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]=2					,							SCREAMING_SNAKE_CASE__    :	str=1_4_0_8					,							**SCREAMING_SNAKE_CASE__    :	Dict					,							)		->      Optional[Any]:
             super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__					,							**SCREAMING_SNAKE_CASE__					)

             a_ :		Union[str, Any]							=  vocab_size
             a_ :		List[str]							=  hidden_size
             a_ :		Any							=  num_hidden_layers
             a_ :		Dict							=  num_attention_heads
             a_ :		Optional[int]							=  hidden_act
             a_ :		List[str]							=  intermediate_size
             a_ :		Tuple							=  hidden_dropout_prob
             a_ :		Union[str, Any]							=  attention_probs_dropout_prob
             a_ :		List[str]							=  max_position_embeddings
             a_ :		List[str]							=  initializer_range
             a_ :		Any							=  layer_norm_eps
             a_ :		Tuple							=  position_embedding_type
             a_ :		List[str]							=  cross_attention_frequency
             a_ :		Union[str, Any]							=  encoder_hidden_size

      @classmethod
      def 	SCREAMING_SNAKE_CASE							(	cls    :	str					,							SCREAMING_SNAKE_CASE__    :	Union[str, os.PathLike]					,							**SCREAMING_SNAKE_CASE__    :	Union[str, Any]					)		->      "PretrainedConfig":
             cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__					)

             a_							,		a_ :		Union[str, Any]							=  cls.get_config_dict(SCREAMING_SNAKE_CASE__					,							**SCREAMING_SNAKE_CASE__					)

             # get the qformer config dict if we are loading from InstructBlipConfig
             if config_dict.get('model_type'					) == "instructblip":
                    a_ :		Dict							=  config_dict['qformer_config']

             if "model_type" in config_dict and hasattr(cls					,							'model_type'					) and config_dict["model_type"] != cls.model_type:
                    logger.warning(
                        F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
                        F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""					)

             return cls.from_dict(SCREAMING_SNAKE_CASE__					,							**SCREAMING_SNAKE_CASE__					)
class 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      snake_case__    :					Union[str, Any]					       =						'''instructblip'''
      snake_case__    :					List[str]					       =						True
      def __init__(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]=None					,							SCREAMING_SNAKE_CASE__    :	Dict=None					,							SCREAMING_SNAKE_CASE__    :	List[Any]=None					,							SCREAMING_SNAKE_CASE__    :	int=3_2					,							**SCREAMING_SNAKE_CASE__    :	Union[str, Any]					)		->      Tuple:
             super().__init__(**SCREAMING_SNAKE_CASE__					)

             if vision_config is None:
                    a_ :		Dict							=  {}
                    logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.'					)

             if qformer_config is None:
                    a_ :		List[str]							=  {}
                    logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.'					)

             if text_config is None:
                    a_ :		Any							=  {}
                    logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).'					)

             a_ :		int							=  InstructBlipVisionConfig(**SCREAMING_SNAKE_CASE__					)
             a_ :		int							=  InstructBlipQFormerConfig(**SCREAMING_SNAKE_CASE__					)
             a_ :		Optional[Any]							=  text_config['model_type'] if 'model_type' in text_config else 'opt'
             a_ :		List[Any]							=  CONFIG_MAPPING[text_model_type](**SCREAMING_SNAKE_CASE__					)

             a_ :		Tuple							=  self.text_config.tie_word_embeddings
             a_ :		List[Any]							=  self.text_config.is_encoder_decoder

             a_ :		Optional[Any]							=  num_query_tokens
             a_ :		int							=  self.vision_config.hidden_size
             a_ :		List[str]							=  self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
             a_ :		Optional[int]							=  1.0
             a_ :		Any							=  0.02
      @classmethod
      def 	SCREAMING_SNAKE_CASE							(	cls    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	InstructBlipVisionConfig					,							SCREAMING_SNAKE_CASE__    :	InstructBlipQFormerConfig					,							SCREAMING_SNAKE_CASE__    :	PretrainedConfig					,							**SCREAMING_SNAKE_CASE__    :	List[str]					,							)		->      Any:
             return cls(
                 vision_config=vision_config.to_dict()					,							qformer_config=qformer_config.to_dict()					,							text_config=text_config.to_dict()					,							**SCREAMING_SNAKE_CASE__					,							)

      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					)		->      Union[str, Any]:
             a_ :		List[Any]							=  copy.deepcopy(self.__dict__					)
             a_ :		Optional[int]							=  self.vision_config.to_dict()
             a_ :		Optional[Any]							=  self.qformer_config.to_dict()
             a_ :		Union[str, Any]							=  self.text_config.to_dict()
             a_ :		Optional[Any]							=  self.__class__.model_type
             return output


