


from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__snake_case   							=						logging.get_logger(__name__)






def 		_A		(		_lowercase )					-> List[int]:


     """simple docstring"""


     if isinstance(_lowercase					,  np.ndarray ):
          return list(tensor.shape )

     __UpperCamelCase =			tf.shape(_lowercase )

     if tensor.shape == tf.TensorShape(_lowercase ):
          return dynamic

     __UpperCamelCase =			tensor.shape.as_list()

     return [dynamic[i] if s is None else s for i, s in enumerate(_lowercase )]






def 		_A		(		_lowercase					,  _lowercase = None					,  _lowercase = None )					-> tf.Tensor:


     """simple docstring"""


     return tf.nn.softmax(logits=logits + 1e-9					,  axis=_lowercase					,  name=_lowercase )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase					,  _lowercase=1e-5					,  _lowercase=-1 )					-> str:


     """simple docstring"""


     if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(_lowercase					,  _lowercase ):
          raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' )

     # Get mean and variance on the axis to be normalized
     __UpperCamelCase,    __UpperCamelCase =			tf.nn.moments(_lowercase					,  axes=[axis]					,  keepdims=_lowercase )

     if axis != -1:
          # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
          # on every dimension except axis
          __UpperCamelCase =			[1] * inputs.shape.rank
          __UpperCamelCase =			shape_list(_lowercase )[axis]
          __UpperCamelCase =			tf.reshape(_lowercase					,  _lowercase )
          __UpperCamelCase =			tf.reshape(_lowercase					,  _lowercase )

     # Compute layer normalization using the batch_normalization
     # function.
     __UpperCamelCase =			tf.nn.batch_normalization(
         _lowercase					,  _lowercase					,  _lowercase					,  offset=_lowercase					,  scale=_lowercase					,  variance_epsilon=_lowercase					,  )
     return outputs






def 		_A		(		_lowercase					,  _lowercase=0					,  _lowercase=-1 )					-> Tuple:


     """simple docstring"""


     if end_dim < 0:
          end_dim += input.shape.rank
     if start_dim < 0:
          start_dim += input.shape.rank

     if start_dim == end_dim:
          return input

     __UpperCamelCase =			tf.shape(_lowercase )
     __UpperCamelCase =			tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] )
     __UpperCamelCase =			tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]					,  axis=0 )
     return tf.reshape(_lowercase					,  _lowercase )






def 		_A		(		_lowercase )					-> tf.Tensor:


     """simple docstring"""


     if not isinstance(_lowercase					,  tf.Tensor ):
          __UpperCamelCase =			tf.convert_to_tensor(_lowercase )  # Catches stray NumPy inputs
     if encoder_attention_mask.shape.rank == 3:
          __UpperCamelCase =			encoder_attention_mask[:, None, :, :]
     if encoder_attention_mask.shape.rank == 2:
          __UpperCamelCase =			encoder_attention_mask[:, None, None, :]
     # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
     # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
     # /transformer/transformer_layers.py#L270
     # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
     # encoder_extended_attention_mask.transpose(-1, -2))
     __UpperCamelCase =			(
         tf.cast(1					,  encoder_attention_mask.dtype ) - encoder_extended_attention_mask
     ) * encoder_extended_attention_mask.dtype.min

     return encoder_extended_attention_mask






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase = "input_ids" )					-> None:


     """simple docstring"""


     tf.debugging.assert_less(
         _lowercase					,  tf.cast(_lowercase					,  dtype=tensor.dtype )					,  message=(
             f'''The maximum value of {tensor_name} ({tf.math.reduce_max(_lowercase )}) must be smaller than the embedding '''
             f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.'''
         )					,  )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase )					-> Optional[int]:


     """simple docstring"""


     __UpperCamelCase =			6_45_12
     # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
     # because in that case even chunking the array would not make the saving
     # possible.
     __UpperCamelCase =			[x for x in data if len(_lowercase ) > HDF5_OBJECT_HEADER_LIMIT]

     # Expecting this to never be true.
     if bad_attributes:
          raise RuntimeError(
              'The following attributes cannot be saved to HDF5 file because '
              f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} '''
              f'''bytes: {bad_attributes}''' )

     __UpperCamelCase =			np.asarray(_lowercase )

     __UpperCamelCase =			1
     __UpperCamelCase =			np.array_split(_lowercase					,  _lowercase )

     # This will never loop forever thanks to the test above.
     while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ):
          num_chunks += 1
          __UpperCamelCase =			np.array_split(_lowercase					,  _lowercase )

     if num_chunks > 1:
          for chunk_id, chunk_data in enumerate(_lowercase ):
               __UpperCamelCase =			chunk_data
     else:
          __UpperCamelCase =			data






def 		_A		(		_lowercase					,  _lowercase )					-> Tuple:


     """simple docstring"""


     if name in group.attrs:
          __UpperCamelCase =			[n.decode('utf8' ) if hasattr(_lowercase					,  'decode' ) else n for n in group.attrs[name]]
     else:
          __UpperCamelCase =			[]
          __UpperCamelCase =			0
          while "%s%d" % (name, chunk_id) in group.attrs:
               data.extend(
                   [n.decode('utf8' ) if hasattr(_lowercase					,  'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] )
               chunk_id += 1
     return data






def 		_A		(		_lowercase )					-> Tuple:


     """simple docstring"""


     def _expand_single_ad_tensor(_lowercase ):
          if isinstance(_lowercase					,  tf.Tensor ) and t.shape.rank == 1:
               return tf.expand_dims(_lowercase					,  axis=-1 )
          return t

     return tf.nest.map_structure(_expand_single_ad_tensor					,  _lowercase )









from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_           =	logging.get_logger(__name__)

UpperCAmelCase_           =	{
    "RWKV/rwkv-4-169m-pile": "https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json",
    "RWKV/rwkv-4-430m-pile": "https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json",
    "RWKV/rwkv-4-1b5-pile": "https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json",
    "RWKV/rwkv-4-3b-pile": "https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json",
    "RWKV/rwkv-4-7b-pile": "https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json",
    "RWKV/rwkv-4-14b-pile": "https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json",
    "RWKV/rwkv-raven-1b5": "https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json",
    "RWKV/rwkv-raven-3b": "https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json",
    "RWKV/rwkv-raven-7b": "https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json",
    "RWKV/rwkv-raven-14b": "https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json",
}




class 			__UpperCamelCase    (							A__    ):
     __A	:  Tuple							  =   """rwkv"""
     __A	:  Any							  =   {"""max_position_embeddings""": """context_length"""}





     def __init__(     self				,							_UpperCamelCase=50277				,							_UpperCamelCase=1024				,							_UpperCamelCase=4096				,							_UpperCamelCase=32				,							_UpperCamelCase=None				,							_UpperCamelCase=None				,							_UpperCamelCase=1e-5				,							_UpperCamelCase=0				,							_UpperCamelCase=0				,							_UpperCamelCase=6				,							_UpperCamelCase=False				,							_UpperCamelCase=True				,							**_UpperCamelCase				,							):
        _UpperCAmelCase           =   vocab_size
        _UpperCAmelCase           =   context_length
        _UpperCAmelCase           =   hidden_size
        _UpperCAmelCase           =   num_hidden_layers
        _UpperCAmelCase           =   attention_hidden_size if attention_hidden_size is not None else hidden_size
        _UpperCAmelCase           =   intermediate_size if intermediate_size is not None else 4 * hidden_size
        _UpperCAmelCase           =   layer_norm_epsilon
        _UpperCAmelCase           =   rescale_every
        _UpperCAmelCase           =   use_cache

        _UpperCAmelCase           =   bos_token_id
        _UpperCAmelCase           =   eos_token_id

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