
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
					import jax
					import jaxlib

lowerCamelCase__          =		get_logger()

lowerCamelCase__          =		None







class      A__							(     TensorFormatter[Mapping, 'jax.Array', Mapping]	):






				def __init__(						self					:      List[str]    ,     a					:      Tuple=None    ,     a					:      str=None    ,     **a					:      int   ):






							'''simple docstring'''







							super().__init__(features=a   )
							import jax
							from jaxlib.xla_client import Device

							if isinstance(a    ,     a   ):
										raise ValueError(
										    f'''Expected {device} to be a `str` not {type(a   )}, as `jaxlib.xla_extension.Device` '''
										    'is not serializable neither with `pickle` nor with `dill`. Instead you can surround '
										    'the device with `str()` to get its string identifier that will be internally mapped '
										    'to the actual `jaxlib.xla_extension.Device`.'   )
							lowerCAmelCase__      :      Optional[int]         =		device if isinstance(a    ,     a   ) else str(jax.devices()[0]   )
							# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
							# with `pickle` nor with `dill`, so we need to use a global variable instead
							global DEVICE_MAPPING
							if DEVICE_MAPPING is None:
										lowerCAmelCase__      :      Union[str, Any]         =		self._map_devices_to_str()
							if self.device not in list(DEVICE_MAPPING.keys()   ):
										logger.warning(
										    f'''Device with string identifier {self.device} not listed among the available '''
										    f'''devices: {list(DEVICE_MAPPING.keys()   )}, so falling back to the default '''
										    f'''device: {str(jax.devices()[0]   )}.'''   )
										lowerCAmelCase__      :      Optional[Any]         =		str(jax.devices()[0]   )
							lowerCAmelCase__      :      Tuple         =		jnp_array_kwargs






				@staticmethod
				def 							_lowerCamelCase		(						):






							'''simple docstring'''







							import jax

							return {str(a   ): device for device in jax.devices()}






				def 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      int   ):






							'''simple docstring'''







							import jax
							import jax.numpy as jnp

							if isinstance(a    ,     a   ) and column:
										if all(
										    isinstance(a    ,     jax.Array   ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column   ):
													return jnp.stack(a    ,     axis=0   )
							return column






				def 							_lowerCamelCase		(						self					:      int    ,     a					:      Tuple   ):






							'''simple docstring'''







							import jax
							import jax.numpy as jnp

							if isinstance(a    ,     (str, bytes, type(a   ))   ):
										return value
							elif isinstance(a    ,     (np.character, np.ndarray)   ) and np.issubdtype(value.dtype    ,     np.character   ):
										return value.tolist()

							lowerCAmelCase__      :      int         =		{}

							if isinstance(a    ,     (np.number, np.ndarray)   ) and np.issubdtype(value.dtype    ,     np.integer   ):
										# the default int precision depends on the jax config
										# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
										if jax.config.jax_enable_xaa:
													lowerCAmelCase__      :      Dict         =		{'dtype': jnp.intaa}
										else:
													lowerCAmelCase__      :      Any         =		{'dtype': jnp.intaa}
							elif isinstance(a    ,     (np.number, np.ndarray)   ) and np.issubdtype(value.dtype    ,     np.floating   ):
										lowerCAmelCase__      :      int         =		{'dtype': jnp.floataa}
							elif config.PIL_AVAILABLE and "PIL" in sys.modules:
										import PIL.Image

										if isinstance(a    ,     PIL.Image.Image   ):
													lowerCAmelCase__      :      Tuple         =		np.asarray(a   )

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
							global DEVICE_MAPPING
							if DEVICE_MAPPING is None:
										lowerCAmelCase__      :      Union[str, Any]         =		self._map_devices_to_str()

							with jax.default_device(DEVICE_MAPPING[self.device]   ):
										# calling jnp.array on a np.ndarray does copy the data
										# see https://github.com/google/jax/issues/4486
										return jnp.array(a    ,     **{**default_dtype, **self.jnp_array_kwargs}   )






				def 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      str   ):






							'''simple docstring'''







							import jax

							# support for torch, tf, jax etc.
							if config.TORCH_AVAILABLE and "torch" in sys.modules:
										import torch

										if isinstance(a    ,     torch.Tensor   ):
													return self._tensorize(data_struct.detach().cpu().numpy()[()]   )
							if hasattr(a    ,     '__array__'   ) and not isinstance(a    ,     jax.Array   ):
										lowerCAmelCase__      :      List[str]         =		data_struct.__array__()
							# support for nested types like struct of list of struct
							if isinstance(a    ,     np.ndarray   ):
										if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
													return self._consolidate([self.recursive_tensorize(a   ) for substruct in data_struct]   )
							elif isinstance(a    ,     (list, tuple)   ):
										return self._consolidate([self.recursive_tensorize(a   ) for substruct in data_struct]   )
							return self._tensorize(a   )






				def 							_lowerCamelCase		(						self					:      int    ,     a					:      dict   ):






							'''simple docstring'''







							return map_nested(self._recursive_tensorize    ,     a    ,     map_list=a   )






				def 							_lowerCamelCase		(						self					:      Dict    ,     a					:      pa.Table   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Dict         =		self.numpy_arrow_extractor().extract_row(a   )
							lowerCAmelCase__      :      Union[str, Any]         =		self.python_features_decoder.decode_row(a   )
							return self.recursive_tensorize(a   )






				def 							_lowerCamelCase		(						self					:      int    ,     a					:      pa.Table   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Union[str, Any]         =		self.numpy_arrow_extractor().extract_column(a   )
							lowerCAmelCase__      :      Tuple         =		self.python_features_decoder.decode_column(a    ,     pa_table.column_names[0]   )
							lowerCAmelCase__      :      int         =		self.recursive_tensorize(a   )
							lowerCAmelCase__      :      List[str]         =		self._consolidate(a   )
							return column






				def 							_lowerCamelCase		(						self					:      int    ,     a					:      pa.Table   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Union[str, Any]         =		self.numpy_arrow_extractor().extract_batch(a   )
							lowerCAmelCase__      :      Tuple         =		self.python_features_decoder.decode_batch(a   )
							lowerCAmelCase__      :      Optional[Any]         =		self.recursive_tensorize(a   )
							for column_name in batch:
										lowerCAmelCase__      :      Dict         =		self._consolidate(batch[column_name]   )
							return batch

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


lowerCamelCase__          =		logging.get_logger(__name__)

lowerCamelCase__          =		{
    """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      A__							(     __magic_name__	):
				lowercase			    =  'gptj'
				lowercase			    =  {
				    'max_position_embeddings': 'n_positions',
				    'hidden_size': 'n_embd',
				    'num_attention_heads': 'n_head',
				    'num_hidden_layers': 'n_layer',
				}






				def __init__(						self					:      Optional[Any]    ,     a					:      Dict=50_400    ,     a					:      Union[str, Any]=2_048    ,     a					:      List[str]=4_096    ,     a					:      Any=28    ,     a					:      Optional[Any]=16    ,     a					:      Optional[Any]=64    ,     a					:      int=None    ,     a					:      Any="gelu_new"    ,     a					:      Union[str, Any]=0.0    ,     a					:      List[Any]=0.0    ,     a					:      List[Any]=0.0    ,     a					:      Optional[Any]=1E-5    ,     a					:      Optional[int]=0.0_2    ,     a					:      int=True    ,     a					:      str=50_256    ,     a					:      str=50_256    ,     a					:      Any=False    ,     **a					:      Dict    ,     ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[Any]         =		vocab_size
							lowerCAmelCase__      :      List[Any]         =		n_positions
							lowerCAmelCase__      :      str         =		n_embd
							lowerCAmelCase__      :      str         =		n_layer
							lowerCAmelCase__      :      str         =		n_head
							lowerCAmelCase__      :      Dict         =		n_inner
							lowerCAmelCase__      :      Union[str, Any]         =		rotary_dim
							lowerCAmelCase__      :      Optional[int]         =		activation_function
							lowerCAmelCase__      :      Any         =		resid_pdrop
							lowerCAmelCase__      :      int         =		embd_pdrop
							lowerCAmelCase__      :      int         =		attn_pdrop
							lowerCAmelCase__      :      List[Any]         =		layer_norm_epsilon
							lowerCAmelCase__      :      str         =		initializer_range
							lowerCAmelCase__      :      Dict         =		use_cache

							lowerCAmelCase__      :      str         =		bos_token_id
							lowerCAmelCase__      :      int         =		eos_token_id

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







class      A__							(     __magic_name__	):






				def __init__(						self					:      str    ,     a					:      PretrainedConfig    ,     a					:      str = "default"    ,     a					:      List[PatchingSpec] = None    ,     a					:      bool = False    ,     ):






							'''simple docstring'''







							super().__init__(a    ,     task=a    ,     patching_specs=a    ,     use_past=a   )
							if not getattr(self._config    ,     'pad_token_id'    ,     a   ):
										# TODO: how to do that better?
										lowerCAmelCase__      :      int         =		0






				@property
				def 							_lowerCamelCase		(						self					:      Tuple   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Dict         =		OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}   )
							if self.use_past:
										self.fill_with_past_key_values_(a    ,     direction='inputs'   )
										lowerCAmelCase__      :      Optional[Any]         =		{0: 'batch', 1: 'past_sequence + sequence'}
							else:
										lowerCAmelCase__      :      Tuple         =		{0: 'batch', 1: 'sequence'}

							return common_inputs






				@property
				def 							_lowerCamelCase		(						self					:      Union[str, Any]   ):






							'''simple docstring'''







							return self._config.n_layer






				@property
				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							return self._config.n_head






				def 							_lowerCamelCase		(						self					:      Tuple    ,     a					:      PreTrainedTokenizer    ,     a					:      int = -1    ,     a					:      int = -1    ,     a					:      bool = False    ,     a					:      Optional[TensorType] = None    ,     ):






							'''simple docstring'''







							lowerCAmelCase__      :      Tuple         =		super(a    ,     self   ).generate_dummy_inputs(
							    a    ,     batch_size=a    ,     seq_length=a    ,     is_pair=a    ,     framework=a   )

							# We need to order the input in the way they appears in the forward()
							lowerCAmelCase__      :      Optional[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

													lowerCAmelCase__      ,				lowerCAmelCase__      :      int         =		common_inputs['input_ids'].shape
													# Not using the same length for past_key_values
													lowerCAmelCase__      :      Optional[int]         =		seqlen + 2
													lowerCAmelCase__      :      Tuple         =		(
													    batch,
													    self.num_attention_heads,
													    past_key_values_length,
													    self._config.hidden_size // self.num_attention_heads,
													)
													lowerCAmelCase__      :      Tuple         =		[
													    (torch.zeros(a   ), torch.zeros(a   )) for _ in range(self.num_layers   )
													]

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

							return ordered_inputs






				@property
				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







							return 13