



from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
    from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


__UpperCAmelCase			  =			logging.get_logger(__name__)

__UpperCAmelCase			  =			{
    '''bigscience/bloom''': '''https://huggingface.co/bigscience/bloom/resolve/main/config.json''',
    '''bigscience/bloom-560m''': '''https://huggingface.co/bigscience/bloom-560m/blob/main/config.json''',
    '''bigscience/bloom-1b1''': '''https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json''',
    '''bigscience/bloom-1b7''': '''https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json''',
    '''bigscience/bloom-3b''': '''https://huggingface.co/bigscience/bloom-3b/blob/main/config.json''',
    '''bigscience/bloom-7b1''': '''https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json''',
}



class 							lowerCAmelCase_						(    a__				):
       UpperCAmelCase__							:   Any  	=    "bloom"
       UpperCAmelCase__							:   List[Any]  	=    ["past_key_values"]
       UpperCAmelCase__							:   Any  	=    {
           "num_hidden_layers": "n_layer",
           "num_attention_heads": "n_head",
       }
       def __init__(     self,     SCREAMING_SNAKE_CASE_=25_0880,     SCREAMING_SNAKE_CASE_=64,     SCREAMING_SNAKE_CASE_=2,     SCREAMING_SNAKE_CASE_=8,     SCREAMING_SNAKE_CASE_=1e-5,     SCREAMING_SNAKE_CASE_=0.02,     SCREAMING_SNAKE_CASE_=True,     SCREAMING_SNAKE_CASE_=1,     SCREAMING_SNAKE_CASE_=2,     SCREAMING_SNAKE_CASE_=False,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=1,     SCREAMING_SNAKE_CASE_=False,     **SCREAMING_SNAKE_CASE_,     )	->						Dict:
          UpperCamelCase       :    List[Any]		      =      vocab_size
          # Backward compatibility with n_embed kwarg
          UpperCamelCase       :    Optional[Any]		      =      kwargs.pop('n_embed',     SCREAMING_SNAKE_CASE_			)
          UpperCamelCase       :    Optional[Any]		      =      hidden_size if n_embed is None else n_embed
          UpperCamelCase       :    Dict		      =      n_layer
          UpperCamelCase       :    Optional[int]		      =      n_head
          UpperCamelCase       :    Union[str, Any]		      =      layer_norm_epsilon
          UpperCamelCase       :    Dict		      =      initializer_range
          UpperCamelCase       :    Optional[int]		      =      use_cache
          UpperCamelCase       :    int		      =      pretraining_tp
          UpperCamelCase       :    Union[str, Any]		      =      apply_residual_connection_post_layernorm
          UpperCamelCase       :    Optional[int]		      =      hidden_dropout
          UpperCamelCase       :    List[str]		      =      attention_dropout

          UpperCamelCase       :    List[str]		      =      bos_token_id
          UpperCamelCase       :    Optional[int]		      =      eos_token_id
          UpperCamelCase       :    int		      =      slow_but_exact

          super().__init__(bos_token_id=SCREAMING_SNAKE_CASE_,     eos_token_id=SCREAMING_SNAKE_CASE_,     **SCREAMING_SNAKE_CASE_			)






class 							lowerCAmelCase_						(    a__				):
       UpperCAmelCase__							:   Tuple  	=    version.parse("1.12"				)
       def __init__(     self,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_ = "default",     SCREAMING_SNAKE_CASE_ = None,     SCREAMING_SNAKE_CASE_ = False,     )	->						Dict:
          super().__init__(SCREAMING_SNAKE_CASE_,     task=SCREAMING_SNAKE_CASE_,     patching_specs=SCREAMING_SNAKE_CASE_,     use_past=SCREAMING_SNAKE_CASE_			)
          if not getattr(self._config,     'pad_token_id',     SCREAMING_SNAKE_CASE_			):
             # TODO: how to do that better?
             UpperCamelCase       :    int		      =      0
       @property
       def    snake_case_			(     self			)	->						Mapping[str, Mapping[int, str]]:
          UpperCamelCase       :    Union[str, Any]		      =      OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}			)
          if self.use_past:
             # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
             self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_,     direction='inputs',     inverted_values_shape=SCREAMING_SNAKE_CASE_			)
             UpperCamelCase       :    List[str]		      =      {0: 'batch', 1: 'past_sequence + sequence'}
          else:
             UpperCamelCase       :    Any		      =      {0: 'batch', 1: 'sequence'}

          return common_inputs
       @property
       def    snake_case_			(     self			)	->						int:
          return self._config.n_layer
       @property
       def    snake_case_			(     self			)	->						int:
          return self._config.n_head
       @property
       def    snake_case_			(     self			)	->						float:
          return 1e-3
       def    snake_case_			(     self,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_ = -1,     SCREAMING_SNAKE_CASE_ = -1,     SCREAMING_SNAKE_CASE_ = False,     SCREAMING_SNAKE_CASE_ = None,     )	->						Mapping[str, Any]:
          UpperCamelCase       :    Union[str, Any]		      =      super(SCREAMING_SNAKE_CASE_,     self			).generate_dummy_inputs(
              SCREAMING_SNAKE_CASE_,     batch_size=SCREAMING_SNAKE_CASE_,     seq_length=SCREAMING_SNAKE_CASE_,     is_pair=SCREAMING_SNAKE_CASE_,     framework=SCREAMING_SNAKE_CASE_			)

          # We need to order the input in the way they appears in the forward()
          UpperCamelCase       :    int		      =      OrderedDict({'input_ids': common_inputs['input_ids']}			)

          # Need to add the past_keys
          if self.use_past:
             if not is_torch_available():
                raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'			)
             else:
                import torch

                UpperCamelCase      ,	UpperCamelCase       :    Optional[Any]		      =      common_inputs['input_ids'].shape
                # Not using the same length for past_key_values
                UpperCamelCase       :    Dict		      =      seqlen + 2
                UpperCamelCase       :    Optional[int]		      =      self._config.hidden_size // self.num_attention_heads
                UpperCamelCase       :    Optional[int]		      =      (
                    batch * self.num_attention_heads,
                    head_dim,
                    past_key_values_length,
                )
                UpperCamelCase       :    List[Any]		      =      (
                    batch * self.num_attention_heads,
                    past_key_values_length,
                    head_dim,
                )
                UpperCamelCase       :    Any		      =      [
                    (torch.zeros(SCREAMING_SNAKE_CASE_			), torch.zeros(SCREAMING_SNAKE_CASE_			)) for _ in range(self.num_layers			)
                ]

          UpperCamelCase       :    Optional[Any]		      =      common_inputs['attention_mask']
          if self.use_past:
             UpperCamelCase       :    List[Any]		      =      ordered_inputs['attention_mask'].dtype
             UpperCamelCase       :    str		      =      torch.cat(
                 [ordered_inputs['attention_mask'], torch.ones(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     dtype=SCREAMING_SNAKE_CASE_			)],     dim=1			)

          return ordered_inputs






       @property
       def    snake_case_			(     self			)	->						int:
          return 13






'''simple docstring'''



from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
     from PIL import Image

     from ..image_utils import load_image

if is_tf_available():
     import tensorflow as tf

     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
     from ..tf_utils import stable_softmax

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

_UpperCamelCase						:  Optional[int]							       =				logging.get_logger(__name__)



@add_end_docstrings(a_			)
class 				_snake_case					(   a_			):

  def __init__(				self      , *_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      super().__init__(*_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	)
      requires_backends(self      , 'vision'	)
      self.check_model_type(
          TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
          if self.framework == 'tf'
          else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING	)

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE=None	):





      '''simple docstring'''

      lowerCAmelCase 						=							{}
      if top_k is not None:
          lowerCAmelCase 						=							top_k
      return {}, {}, postprocess_params

  def __call__(				self      , _SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

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

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							load_image(_SCREAMING_SNAKE_CASE	)
      lowerCAmelCase 						=							self.image_processor(images=_SCREAMING_SNAKE_CASE      , return_tensors=self.framework	)
      return model_inputs

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model(**_SCREAMING_SNAKE_CASE	)
      return model_outputs


  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE=5	):





      '''simple docstring'''

      if top_k > self.model.config.num_labels:
          lowerCAmelCase 						=							self.model.config.num_labels

      if self.framework == "pt":
          lowerCAmelCase 						=							model_outputs.logits.softmax(-1	)[0]
          lowerCAmelCase						,   lowerCAmelCase 						=							probs.topk(_SCREAMING_SNAKE_CASE	)
      elif self.framework == "tf":
          lowerCAmelCase 						=							stable_softmax(model_outputs.logits      , axis=-1	)[0]
          lowerCAmelCase 						=							tf.math.top_k(_SCREAMING_SNAKE_CASE      , k=_SCREAMING_SNAKE_CASE	)
          lowerCAmelCase						,   lowerCAmelCase 						=							topk.values.numpy(), topk.indices.numpy()
      else:
          raise ValueError(F'Unsupported framework: {self.framework}'	)

      lowerCAmelCase 						=							scores.tolist()
      lowerCAmelCase 						=							ids.tolist()
      return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)]





