


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    (  UpperCamelCase_	):
      UpperCamelCase__				:    int ='gptj'
      UpperCamelCase__				:    Tuple ={
          'max_position_embeddings': 'n_positions',
          'hidden_size': 'n_embd',
          'num_attention_heads': 'n_head',
          'num_hidden_layers': 'n_layer',
      }






      def __init__(   self		:	List[str]     ,  lowercase_		:	int=5_0400     ,  lowercase_		:	Optional[int]=2048     ,  lowercase_		:	str=4096     ,  lowercase_		:	Union[str, Any]=28     ,  lowercase_		:	List[Any]=16     ,  lowercase_		:	List[Any]=64     ,  lowercase_		:	List[str]=None     ,  lowercase_		:	List[Any]="gelu_new"     ,  lowercase_		:	Any=0.0     ,  lowercase_		:	Tuple=0.0     ,  lowercase_		:	Optional[Any]=0.0     ,  lowercase_		:	Optional[Any]=1E-5     ,  lowercase_		:	Any=0.02     ,  lowercase_		:	List[str]=True     ,  lowercase_		:	Union[str, Any]=5_0256     ,  lowercase_		:	List[str]=5_0256     ,  lowercase_		:	List[str]=False     ,  **lowercase_		:	Optional[int]     ,  )   ->		List[Any]:
             """simple docstring"""




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

             _lowerCamelCase			:						List[str]            =bos_token_id
             _lowerCamelCase			:						Dict            =eos_token_id

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




class A    (  UpperCamelCase_	):






      def __init__(   self		:	int     ,  lowercase_		:	PretrainedConfig     ,  lowercase_		:	str = "default"     ,  lowercase_		:	List[PatchingSpec] = None     ,  lowercase_		:	bool = False     ,  )   ->		Optional[int]:
             """simple docstring"""




             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?
                    _lowerCamelCase			:						int            =0






      @property
      def 			lowerCamelCase			(   self		:	List[str]					)   ->		Mapping[str, Mapping[int, str]]:
             """simple docstring"""




             _lowerCamelCase			:						Tuple            =OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}					)
             if self.use_past:
                    self.fill_with_past_key_values_(lowercase_     ,  direction='inputs'					)
                    _lowerCamelCase			:						Union[str, Any]            ={0: 'batch', 1: 'past_sequence + sequence'}
             else:
                    _lowerCamelCase			:						Optional[int]            ={0: 'batch', 1: 'sequence'}

             return common_inputs






      @property
      def 			lowerCamelCase			(   self		:	Tuple					)   ->		int:
             """simple docstring"""




             return self._config.n_layer






      @property
      def 			lowerCamelCase			(   self		:	Tuple					)   ->		int:
             """simple docstring"""




             return self._config.n_head






      def 			lowerCamelCase			(   self		:	str     ,  lowercase_		:	PreTrainedTokenizer     ,  lowercase_		:	int = -1     ,  lowercase_		:	int = -1     ,  lowercase_		:	bool = False     ,  lowercase_		:	Optional[TensorType] = None     ,  )   ->		Mapping[str, Any]:
             """simple docstring"""




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

             _lowerCamelCase			:						List[str]            =common_inputs['attention_mask']
             if self.use_past:
                    _lowerCamelCase			:						int            =ordered_inputs['attention_mask'].dtype
                    _lowerCamelCase			:						Tuple            =torch.cat(
                        [ordered_inputs['attention_mask'], torch.ones(lowercase_     ,  lowercase_     ,  dtype=lowercase_					)]     ,  dim=1					)

             return ordered_inputs






      @property
      def 			lowerCamelCase			(   self		:	Dict					)   ->		int:
             """simple docstring"""




             return 13






# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import platform

import numpy as np
import psutil
import torch

from accelerate import __version__ as version
from accelerate.commands.config import default_config_file, load_config_from_file

from ..utils import is_npu_available, is_xpu_available




def       a_ (       SCREAMING_SNAKE_CASE__   : str=None	):
       '''simple docstring'''





       if subparsers is not None:
              _lowerCamelCase			:						str            =subparsers.add_parser('env'	)
       else:
              _lowerCamelCase			:						List[Any]            =argparse.ArgumentParser('Accelerate env command'	)

       parser.add_argument(
           '--config_file'						,     default=SCREAMING_SNAKE_CASE__						,     help='The config file to use for the default values in the launching script.'	)

       if subparsers is not None:
              parser.set_defaults(func=SCREAMING_SNAKE_CASE__	)
       return parser




def       a_ (       SCREAMING_SNAKE_CASE__   : int	):
       '''simple docstring'''





       _lowerCamelCase			:						int            =torch.__version__
       _lowerCamelCase			:						Optional[Any]            =torch.cuda.is_available()
       _lowerCamelCase			:						int            =is_xpu_available()
       _lowerCamelCase			:						Union[str, Any]            =is_npu_available()

       _lowerCamelCase			:						Optional[int]            ='Not found'
       # Get the default from the config file.
       if args.config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE__	):
              _lowerCamelCase			:						Any            =load_config_from_file(args.config_file	).to_dict()

       _lowerCamelCase			:						List[str]            ={
           '`Accelerate` version': version,
           'Platform': platform.platform(),
           'Python version': platform.python_version(),
           'Numpy version': np.__version__,
           'PyTorch version (GPU?)': F'''{pt_version} ({pt_cuda_available})''',
           'PyTorch XPU available': str(SCREAMING_SNAKE_CASE__	),
           'PyTorch NPU available': str(SCREAMING_SNAKE_CASE__	),
           'System RAM': F'''{psutil.virtual_memory().total / 1_024 ** 3:.2f} GB''',
       }
       if pt_cuda_available:
              _lowerCamelCase			:						List[Any]            =torch.cuda.get_device_name()

       print('\nCopy-and-paste the text below in your GitHub issue\n'	)
       print('\n'.join([F'''- {prop}: {val}''' for prop, val in info.items()]	)	)

       print('- `Accelerate` default config:' if args.config_file is None else '- `Accelerate` config passed:'	)
       _lowerCamelCase			:						Dict            =(
           '\n'.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]	)
           if isinstance(SCREAMING_SNAKE_CASE__						,     SCREAMING_SNAKE_CASE__	)
           else F'''\t{accelerate_config}'''
       )
       print(SCREAMING_SNAKE_CASE__	)

       _lowerCamelCase			:						str            =accelerate_config

       return info




def       a_ (       ):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =env_command_parser()
       _lowerCamelCase			:						Any            =parser.parse_args()
       env_command(SCREAMING_SNAKE_CASE__	)
       return 0


if __name__ == "__main__":
 raise SystemExit(main())


