





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_          =		{
    """Salesforce/codegen-350M-nl""": """https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json""",
    """Salesforce/codegen-350M-multi""": """https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json""",
    """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json""",
    """Salesforce/codegen-2B-nl""": """https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json""",
    """Salesforce/codegen-2B-multi""": """https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json""",
    """Salesforce/codegen-2B-mono""": """https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json""",
    """Salesforce/codegen-6B-nl""": """https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json""",
    """Salesforce/codegen-6B-multi""": """https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json""",
    """Salesforce/codegen-6B-mono""": """https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json""",
    """Salesforce/codegen-16B-nl""": """https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json""",
    """Salesforce/codegen-16B-multi""": """https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json""",
    """Salesforce/codegen-16B-mono""": """https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json""",
}
class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):
   _UpperCamelCase   :		Union[str, Any]			 =	'codegen'
   _UpperCamelCase   :		Tuple			 =	{
       'max_position_embeddings': 'n_positions',
       'hidden_size': 'n_embd',
       'num_attention_heads': 'n_head',
       'num_hidden_layers': 'n_layer',
   }


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





     """simple docstring"""







     lowercase__           =  vocab_size
     lowercase__           =  n_ctx
     lowercase__           =  n_positions
     lowercase__           =  n_embd
     lowercase__           =  n_layer
     lowercase__           =  n_head
     lowercase__           =  n_inner
     lowercase__           =  rotary_dim
     lowercase__           =  activation_function
     lowercase__           =  resid_pdrop
     lowercase__           =  embd_pdrop
     lowercase__           =  attn_pdrop
     lowercase__           =  layer_norm_epsilon
     lowercase__           =  initializer_range
     lowercase__           =  use_cache

     lowercase__           =  bos_token_id
     lowercase__           =  eos_token_id

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






class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):


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





     """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?
       lowercase__           =  0


   @property
   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[Any]	)->       Mapping[str, Mapping[int, str]]:





     """simple docstring"""







     lowercase__           =  OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}	)
     if self.use_past:
       self.fill_with_past_key_values_(a      ,					direction='inputs'	)
       lowercase__           =  {0: 'batch', 1: 'past_sequence + sequence'}
     else:
       lowercase__           =  {0: 'batch', 1: 'sequence'}

     return common_inputs


   @property
   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]	)->       int:





     """simple docstring"""







     return self._config.n_layer


   @property
   def 	SCREAMING_SNAKE_CASE_							(   self      :    Tuple	)->       int:





     """simple docstring"""







     return self._config.n_head


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Dict      ,					a      :    PreTrainedTokenizer      ,					a      :    int = -1      ,					a      :    int = -1      ,					a      :    bool = False      ,					a      :    Optional[TensorType] = None      ,					)->       Mapping[str, Any]:





     """simple docstring"""







     lowercase__           =  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()
     lowercase__           =  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

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

     lowercase__           =  common_inputs['attention_mask']
     if self.use_past:
       lowercase__           =  ordered_inputs['attention_mask'].dtype
       lowercase__           =  torch.cat(
           [ordered_inputs['attention_mask'], torch.ones(a      ,					a      ,					dtype=a	)]      ,					dim=1	)

     return ordered_inputs


   @property
   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]	)->       int:





     """simple docstring"""







     return 13









import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
      from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		)    ->       List[str]:
  if is_torch_version('<'		,						'2.0.0'		) or not hasattr(_SCREAMING_SNAKE_CASE		,						'_dynamo'		):
    return False
  return isinstance(_SCREAMING_SNAKE_CASE		,						torch._dynamo.eval_frame.OptimizedModule		)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE = True		)    ->       Dict:
  lowercase__           =  (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

  lowercase__           =  is_compiled_module(_SCREAMING_SNAKE_CASE		)
  if is_compiled:
    lowercase__           =  model
    lowercase__           =  model._orig_mod

  if is_deepspeed_available():
    options += (DeepSpeedEngine,)

  while isinstance(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		):
    lowercase__           =  model.module

  if not keep_fpaa_wrapper:
    lowercase__           =  getattr(_SCREAMING_SNAKE_CASE		,						'forward'		)
    lowercase__           =  model.__dict__.pop('_original_forward'		,						_SCREAMING_SNAKE_CASE		)
    if original_forward is not None:
      while hasattr(_SCREAMING_SNAKE_CASE		,						'__wrapped__'		):
        lowercase__           =  forward.__wrapped__
        if forward == original_forward:
          break
      lowercase__           =  forward
    if getattr(_SCREAMING_SNAKE_CASE		,						'_converted_to_transformer_engine'		,						_SCREAMING_SNAKE_CASE		):
      convert_model(_SCREAMING_SNAKE_CASE		,						to_transformer_engine=_SCREAMING_SNAKE_CASE		)

  if is_compiled:
    lowercase__           =  model
    lowercase__           =  compiled_model

  return model




def       __UpperCamelCase  ()    ->       Tuple:
  PartialState().wait_for_everyone()




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       List[Any]:
  if PartialState().distributed_type == DistributedType.TPU:
    xm.save(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)
  elif PartialState().local_process_index == 0:
    torch.save(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)




@contextmanager
def       __UpperCamelCase  (**_SCREAMING_SNAKE_CASE		)    ->       Optional[Any]:
  for key, value in kwargs.items():
    lowercase__           =  str(_SCREAMING_SNAKE_CASE		)

  yield

  for key in kwargs:
    if key.upper() in os.environ:
      del os.environ[key.upper()]




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		)    ->       List[str]:
  if not hasattr(_SCREAMING_SNAKE_CASE		,						'__qualname__'		) and not hasattr(_SCREAMING_SNAKE_CASE		,						'__name__'		):
    lowercase__           =  getattr(_SCREAMING_SNAKE_CASE		,						'__class__'		,						_SCREAMING_SNAKE_CASE		)
  if hasattr(_SCREAMING_SNAKE_CASE		,						'__qualname__'		):
    return obj.__qualname__
  if hasattr(_SCREAMING_SNAKE_CASE		,						'__name__'		):
    return obj.__name__
  return str(_SCREAMING_SNAKE_CASE		)




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)    ->       Dict:
  for key, value in source.items():
    if isinstance(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		):
      lowercase__           =  destination.setdefault(_SCREAMING_SNAKE_CASE		,						{}		)
      merge_dicts(_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		)
    else:
      lowercase__           =  value

  return destination




def       __UpperCamelCase  (_SCREAMING_SNAKE_CASE = None		)    ->       bool:
  if port is None:
    lowercase__           =  29500
  with socket.socket(socket.AF_INET		,						socket.SOCK_STREAM		) as s:
    return s.connect_ex(('localhost', port)		) == 0


