






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

__lowercase										= logging.get_logger(__name__)


@add_end_docstrings(UpperCAmelCase_			)
class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    def __init__(     self			,			*__lowercase			,			**__lowercase)	->     Any:
        super().__init__(*__lowerCAmelCase			,			**__lowerCAmelCase)
        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       UpperCamelCase__       (     self			,			__lowercase=None)	->     Any:
        __UpperCamelCase					:Dict        =		{}
        if top_k is not None:
            __UpperCamelCase					:List[str]        =		top_k
        return {}, {}, postprocess_params







    def __call__(     self			,			__lowercase			,			**__lowercase)	->     Any:
        return super().__call__(__lowerCAmelCase			,			**__lowerCAmelCase)







    def       UpperCamelCase__       (     self			,			__lowercase)	->     Any:
        __UpperCamelCase					:str        =		load_image(__lowerCAmelCase)
        __UpperCamelCase					:List[Any]        =		self.image_processor(images=__lowerCAmelCase			,			return_tensors=self.framework)
        return model_inputs







    def       UpperCamelCase__       (     self			,			__lowercase)	->     int:
        __UpperCamelCase					:Union[str, Any]        =		self.model(**__lowerCAmelCase)
        return model_outputs







    def       UpperCamelCase__       (     self			,			__lowercase			,			__lowercase=5)	->     Optional[Any]:



        if top_k > self.model.config.num_labels:
            __UpperCamelCase					:Dict        =		self.model.config.num_labels

        if self.framework == "pt":
            __UpperCamelCase					:int        =		model_outputs.logits.softmax(-1)[0]
            __UpperCamelCase  ,	__UpperCamelCase					:List[str]        =		probs.topk(__lowerCAmelCase)
        elif self.framework == "tf":
            __UpperCamelCase					:str        =		stable_softmax(model_outputs.logits			,			axis=-1)[0]
            __UpperCamelCase					:Dict        =		tf.math.top_k(__lowerCAmelCase			,			k=__lowerCAmelCase)
            __UpperCamelCase  ,	__UpperCamelCase					:str        =		topk.values.numpy(), topk.indices.numpy()
        else:
            raise ValueError(f"""Unsupported framework: {self.framework}""")

        __UpperCamelCase					:Optional[int]        =		scores.tolist()
        __UpperCamelCase					:List[str]        =		ids.tolist()
        return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(__lowerCAmelCase			,			__lowerCAmelCase)]






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

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


__lowercase										= logging.get_logger(__name__)

__lowercase										= {
    '''EleutherAI/gpt-j-6B''': '''https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json''',
    # See all GPT-J models at https://huggingface.co/models?filter=gpt_j
}


class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    a__     :						Optional[Any]      =				"""gptj"""
    a__     :						Tuple      =				{
        """max_position_embeddings""": """n_positions""",
        """hidden_size""": """n_embd""",
        """num_attention_heads""": """n_head""",
        """num_hidden_layers""": """n_layer""",
    }







    def __init__(     self			,			__lowercase=50_400			,			__lowercase=2_048			,			__lowercase=4_096			,			__lowercase=28			,			__lowercase=16			,			__lowercase=64			,			__lowercase=None			,			__lowercase="gelu_new"			,			__lowercase=0.0			,			__lowercase=0.0			,			__lowercase=0.0			,			__lowercase=1E-5			,			__lowercase=0.02			,			__lowercase=True			,			__lowercase=50_256			,			__lowercase=50_256			,			__lowercase=False			,			**__lowercase			,			)	->     Tuple:
        __UpperCamelCase					:Any        =		vocab_size
        __UpperCamelCase					:Optional[int]        =		n_positions
        __UpperCamelCase					:Tuple        =		n_embd
        __UpperCamelCase					:int        =		n_layer
        __UpperCamelCase					:Any        =		n_head
        __UpperCamelCase					:Any        =		n_inner
        __UpperCamelCase					:Dict        =		rotary_dim
        __UpperCamelCase					:Tuple        =		activation_function
        __UpperCamelCase					:Optional[Any]        =		resid_pdrop
        __UpperCamelCase					:Any        =		embd_pdrop
        __UpperCamelCase					:List[str]        =		attn_pdrop
        __UpperCamelCase					:str        =		layer_norm_epsilon
        __UpperCamelCase					:List[Any]        =		initializer_range
        __UpperCamelCase					:Dict        =		use_cache

        __UpperCamelCase					:List[Any]        =		bos_token_id
        __UpperCamelCase					:Tuple        =		eos_token_id

        super().__init__(
            bos_token_id=__lowercase			,			eos_token_id=__lowercase			,			tie_word_embeddings=__lowercase			,			**__lowercase)


class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase			,			__lowercase = "default"			,			__lowercase = None			,			__lowercase = False			,			)	->     Any:
        super().__init__(__lowercase			,			task=__lowercase			,			patching_specs=__lowercase			,			use_past=__lowercase)
        if not getattr(self._config			,			'''pad_token_id'''			,			__lowercase):
            # TODO: how to do that better?
            __UpperCamelCase					:Tuple        =		0







    @property
    def       UpperCamelCase__       (     self)	->     Mapping[str, Mapping[int, str]]:
        __UpperCamelCase					:Tuple        =		OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}})
        if self.use_past:
            self.fill_with_past_key_values_(__lowercase			,			direction='''inputs''')
            __UpperCamelCase					:str        =		{0: '''batch''', 1: '''past_sequence + sequence'''}
        else:
            __UpperCamelCase					:Any        =		{0: '''batch''', 1: '''sequence'''}

        return common_inputs







    @property
    def       UpperCamelCase__       (     self)	->     int:
        return self._config.n_layer







    @property
    def       UpperCamelCase__       (     self)	->     int:
        return self._config.n_head







    def       UpperCamelCase__       (     self			,			__lowercase			,			__lowercase = -1			,			__lowercase = -1			,			__lowercase = False			,			__lowercase = None			,			)	->     Mapping[str, Any]:
        __UpperCamelCase					:Optional[int]        =		super(__lowercase			,			self).generate_dummy_inputs(
            __lowercase			,			batch_size=__lowercase			,			seq_length=__lowercase			,			is_pair=__lowercase			,			framework=__lowercase)

        # 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					:str        =		common_inputs['''input_ids'''].shape
                # Not using the same length for past_key_values
                __UpperCamelCase					:List[str]        =		seqlen + 2
                __UpperCamelCase					:Union[str, Any]        =		(
                    batch,
                    self.num_attention_heads,
                    past_key_values_length,
                    self._config.hidden_size // self.num_attention_heads,
                )
                __UpperCamelCase					:Tuple        =		[
                    (torch.zeros(__lowercase), torch.zeros(__lowercase)) for _ in range(self.num_layers)
                ]

        __UpperCamelCase					:Tuple        =		common_inputs['''attention_mask''']
        if self.use_past:
            __UpperCamelCase					:Tuple        =		ordered_inputs['''attention_mask'''].dtype
            __UpperCamelCase					:Optional[Any]        =		torch.cat(
                [ordered_inputs['''attention_mask'''], torch.ones(__lowercase			,			__lowercase			,			dtype=__lowercase)]			,			dim=1)

        return ordered_inputs







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





