





import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


_UpperCAmelCase				:       Any	   =				logging.get_logger(__name__)


_UpperCAmelCase				:       int	   =				R"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""

class    lowerCAmelCase							(					__UpperCamelCase			):
 @add_start_docstrings(UpperCAmelCase	)
 def __call__(      self  :      Optional[Any]			,     UpperCAmelCase  :      torch.LongTensor			,     UpperCAmelCase  :      torch.FloatTensor			,     **UpperCAmelCase  :      List[Any]	)			->	bool:
     raise NotImplementedError('StoppingCriteria needs to be subclassed'	)


class    lowerCAmelCase							(					__UpperCamelCase			):
 def __init__(      self  :      List[Any]			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      Optional[int] = None	)			->	Optional[Any]:
     lowerCamelCase__    :      List[str]					 =		max_length
     lowerCamelCase__    :      Optional[Any]					 =		max_position_embeddings







 @add_start_docstrings(UpperCAmelCase	)
 def __call__(      self  :      Optional[Any]			,     UpperCAmelCase  :      torch.LongTensor			,     UpperCAmelCase  :      torch.FloatTensor			,     **UpperCAmelCase  :      Optional[Any]	)			->	bool:
     lowerCamelCase__    :      Optional[int]					 =		input_ids.shape[-1]
     lowerCamelCase__    :      int					 =		cur_len >= self.max_length
     if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
         logger.warning_once(
             'This is a friendly reminder - the current text generation call will exceed the model\'s predefined '
             F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """
             'exceptions, performance degradation, or nothing at all.'	)
     return is_done


class    lowerCAmelCase							(					__UpperCamelCase			):
 def __init__(      self  :      Optional[Any]			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      int	)			->	Dict:
     warnings.warn(
         'The class `MaxNewTokensCriteria` is deprecated. '
         F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """
         'with `max_length = start_length + max_new_tokens` instead.'			,     UpperCAmelCase			,     )
     lowerCamelCase__    :      Dict					 =		start_length
     lowerCamelCase__    :      str					 =		max_new_tokens
     lowerCamelCase__    :      Optional[Any]					 =		start_length + max_new_tokens







 @add_start_docstrings(UpperCAmelCase	)
 def __call__(      self  :      List[Any]			,     UpperCAmelCase  :      torch.LongTensor			,     UpperCAmelCase  :      torch.FloatTensor			,     **UpperCAmelCase  :      Optional[Any]	)			->	bool:
     return input_ids.shape[-1] >= self.max_length


class    lowerCAmelCase							(					__UpperCamelCase			):
 def __init__(      self  :      Union[str, Any]			,     UpperCAmelCase  :      float			,     UpperCAmelCase  :      Optional[float] = None	)			->	List[str]:
     lowerCamelCase__    :      Union[str, Any]					 =		max_time
     lowerCamelCase__    :      int					 =		time.time() if initial_timestamp is None else initial_timestamp







 @add_start_docstrings(UpperCAmelCase	)
 def __call__(      self  :      int			,     UpperCAmelCase  :      torch.LongTensor			,     UpperCAmelCase  :      torch.FloatTensor			,     **UpperCAmelCase  :      str	)			->	bool:
     return time.time() - self.initial_timestamp > self.max_time


class    lowerCAmelCase							(					__UpperCamelCase			):
 @add_start_docstrings(UpperCAmelCase	)
 def __call__(      self  :      Dict			,     UpperCAmelCase  :      torch.LongTensor			,     UpperCAmelCase  :      torch.FloatTensor			,     **UpperCAmelCase  :      int	)			->	bool:
     return any(criteria(UpperCAmelCase			,     UpperCAmelCase	) for criteria in self	)







 @property
 def      A_	(      self  :      str	)			->	Optional[int]:
     for stopping_criterium in self:
         if isinstance(UpperCAmelCase			,     UpperCAmelCase	):
             return stopping_criterium.max_length
         elif isinstance(UpperCAmelCase			,     UpperCAmelCase	):
             return stopping_criterium.max_length
     return None


def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase						,	_UpperCAmelCase )			->     StoppingCriteriaList:
    lowerCamelCase__    :      Union[str, Any]					 =		stopping_criteria.max_length
    lowerCamelCase__    :      List[str]					 =		deepcopy(_UpperCAmelCase )
    if stopping_max_length is not None and stopping_max_length != max_length:
        warnings.warn('You set different `max_length` for stopping criteria and `max_length` parameter'						,	_UpperCAmelCase )
    elif stopping_max_length is None:
        new_stopping_criteria.append(MaxLengthCriteria(max_length=_UpperCAmelCase ) )
    return new_stopping_criteria








import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


a__				=		logging.get_logger(__name__)



def    __UpperCAmelCase (	__a      :			Dict	)			->     Tuple:

					"""simple docstring"""

					_a	:    Any         =		R'''\w+[.]\d+'''
					_a	:    Union[str, Any]         =		re.findall(__a		,__a	)
					for pat in pats:
										_a	:    int         =		key.replace(__a		,'''_'''.join(pat.split('''.'''	)	)	)
					return key



def    __UpperCAmelCase (	__a      :			List[str]		,__a      :			Union[str, Any]		,__a      :			Optional[int]	)			->     Tuple:

					"""simple docstring"""

					_a	:    Dict         =		pt_tuple_key[:-1] + ('''scale''',)
					if (
					    any('''norm''' in str_ for str_ in pt_tuple_key	)
					    and (pt_tuple_key[-1] == "bias")
					    and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
					    and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
					):
										_a	:    Dict         =		pt_tuple_key[:-1] + ('''scale''',)
										return renamed_pt_tuple_key, pt_tensor
					elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
										_a	:    Optional[int]         =		pt_tuple_key[:-1] + ('''scale''',)
										return renamed_pt_tuple_key, pt_tensor

					# embedding
					if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
										_a	:    Union[str, Any]         =		pt_tuple_key[:-1] + ('''embedding''',)
										return renamed_pt_tuple_key, pt_tensor

					# conv layer
					_a	:    Tuple         =		pt_tuple_key[:-1] + ('''kernel''',)
					if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
										_a	:    List[str]         =		pt_tensor.transpose(2		,3		,1		,0	)
										return renamed_pt_tuple_key, pt_tensor

					# linear layer
					_a	:    Dict         =		pt_tuple_key[:-1] + ('''kernel''',)
					if pt_tuple_key[-1] == "weight":
										_a	:    Union[str, Any]         =		pt_tensor.T
										return renamed_pt_tuple_key, pt_tensor

					# old PyTorch layer norm weight
					_a	:    Dict         =		pt_tuple_key[:-1] + ('''weight''',)
					if pt_tuple_key[-1] == "gamma":
										return renamed_pt_tuple_key, pt_tensor

					# old PyTorch layer norm bias
					_a	:    Union[str, Any]         =		pt_tuple_key[:-1] + ('''bias''',)
					if pt_tuple_key[-1] == "beta":
										return renamed_pt_tuple_key, pt_tensor

					return pt_tuple_key, pt_tensor







def    __UpperCAmelCase (	__a      :			Dict		,__a      :			str		,__a      :			str=42	)			->     Optional[int]:

					"""simple docstring"""

					_a	:    Tuple         =		{k: v.numpy() for k, v in pt_state_dict.items()}

					# Step 2: Since the model is stateless, get random Flax params
					_a	:    List[Any]         =		flax_model.init_weights(PRNGKey(__a	)	)

					_a	:    Optional[int]         =		flatten_dict(__a	)
					_a	:    Tuple         =		{}

					# Need to change some parameters name to match Flax names
					for pt_key, pt_tensor in pt_state_dict.items():
										_a	:    List[str]         =		rename_key(__a	)
										_a	:    Optional[Any]         =		tuple(renamed_pt_key.split('''.'''	)	)

										# Correctly rename weight parameters
										_a      ,					_a	:    List[str]         =		rename_key_and_reshape_tensor(__a		,__a		,__a	)

										if flax_key in random_flax_state_dict:
															if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
																				raise ValueError(
																				    F"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """
																				    F"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."""	)

        # also add unexpected weight so that warning is thrown
										_a	:    Dict         =		jnp.asarray(__a	)

					return unflatten_dict(__a	)



