



import unittest

from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import (
      MODEL_FOR_PRETRAINING_MAPPING,
      AlbertForMaskedLM,
      AlbertForMultipleChoice,
      AlbertForPreTraining,
      AlbertForQuestionAnswering,
      AlbertForSequenceClassification,
      AlbertForTokenClassification,
      AlbertModel,
  )
  from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST







class 						snake_case  :



   '''simple docstring'''






   def __init__(    self							:	int ,						lowerCAmelCase							:	Union[str, Any] ,						lowerCAmelCase							:	Optional[Any]=13 ,						lowerCAmelCase							:	List[str]=7 ,						lowerCAmelCase							:	Optional[Any]=True ,						lowerCAmelCase							:	Dict=True ,						lowerCAmelCase							:	str=True ,						lowerCAmelCase							:	int=True ,						lowerCAmelCase							:	int=99 ,						lowerCAmelCase							:	int=16 ,						lowerCAmelCase							:	int=36 ,						lowerCAmelCase							:	Any=6 ,						lowerCAmelCase							:	int=6 ,						lowerCAmelCase							:	Dict=6 ,						lowerCAmelCase							:	Tuple=37 ,						lowerCAmelCase							:	Union[str, Any]="gelu" ,						lowerCAmelCase							:	Optional[Any]=0.1 ,						lowerCAmelCase							:	List[str]=0.1 ,						lowerCAmelCase							:	str=512 ,						lowerCAmelCase							:	List[Any]=16 ,						lowerCAmelCase							:	Optional[int]=2 ,						lowerCAmelCase							:	List[str]=0.02 ,						lowerCAmelCase							:	Union[str, Any]=3 ,						lowerCAmelCase							:	Union[str, Any]=4 ,						lowerCAmelCase							:	Optional[Any]=None ,						) -> int:

    """simple docstring"""







    _snake_case			:     List[Any] 		=    parent
    _snake_case			:     Optional[int] 		=    batch_size
    _snake_case			:     Optional[Any] 		=    seq_length
    _snake_case			:     Optional[int] 		=    is_training
    _snake_case			:     str 		=    use_input_mask
    _snake_case			:     List[str] 		=    use_token_type_ids
    _snake_case			:     List[str] 		=    use_labels
    _snake_case			:     Union[str, Any] 		=    vocab_size
    _snake_case			:     Optional[Any] 		=    embedding_size
    _snake_case			:     str 		=    hidden_size
    _snake_case			:     Union[str, Any] 		=    num_hidden_layers
    _snake_case			:     Union[str, Any] 		=    num_hidden_groups
    _snake_case			:     Dict 		=    num_attention_heads
    _snake_case			:     int 		=    intermediate_size
    _snake_case			:     List[Any] 		=    hidden_act
    _snake_case			:     Any 		=    hidden_dropout_prob
    _snake_case			:     str 		=    attention_probs_dropout_prob
    _snake_case			:     Optional[int] 		=    max_position_embeddings
    _snake_case			:     Any 		=    type_vocab_size
    _snake_case			:     List[str] 		=    type_sequence_label_size
    _snake_case			:     int 		=    initializer_range
    _snake_case			:     List[Any] 		=    num_labels
    _snake_case			:     List[Any] 		=    num_choices
    _snake_case			:     List[Any] 		=    scope

   def    UpperCamelCase_     (    self							:	int) -> Optional[int]:

    """simple docstring"""







    _snake_case			:     Optional[Any] 		=    ids_tensor([self.batch_size, self.seq_length] ,						self.vocab_size)

    _snake_case			:     Dict 		=    None
    if self.use_input_mask:
     _snake_case			:     Dict 		=    random_attention_mask([self.batch_size, self.seq_length])

    _snake_case			:     Optional[Any] 		=    None
    if self.use_token_type_ids:
     _snake_case			:     List[str] 		=    ids_tensor([self.batch_size, self.seq_length] ,						self.type_vocab_size)

    _snake_case			:     str 		=    None
    _snake_case			:     Union[str, Any] 		=    None
    _snake_case			:     List[str] 		=    None
    if self.use_labels:
     _snake_case			:     List[str] 		=    ids_tensor([self.batch_size] ,						self.type_sequence_label_size)
     _snake_case			:     Optional[Any] 		=    ids_tensor([self.batch_size, self.seq_length] ,						self.num_labels)
     _snake_case			:     int 		=    ids_tensor([self.batch_size] ,						self.num_choices)

    _snake_case			:     str 		=    self.get_config()

    return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

   def    UpperCamelCase_     (    self							:	int) -> Dict:

    """simple docstring"""







    return AlbertConfig(
        vocab_size=self.vocab_size ,						hidden_size=self.hidden_size ,						num_hidden_layers=self.num_hidden_layers ,						num_attention_heads=self.num_attention_heads ,						intermediate_size=self.intermediate_size ,						hidden_act=self.hidden_act ,						hidden_dropout_prob=self.hidden_dropout_prob ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob ,						max_position_embeddings=self.max_position_embeddings ,						type_vocab_size=self.type_vocab_size ,						initializer_range=self.initializer_range ,						num_hidden_groups=self.num_hidden_groups ,						)

   def    UpperCamelCase_     (    self							:	Any ,						lowerCAmelCase							:	int ,						lowerCAmelCase							:	Tuple ,						lowerCAmelCase							:	Tuple ,						lowerCAmelCase							:	Dict ,						lowerCAmelCase							:	List[Any] ,						lowerCAmelCase							:	str ,						lowerCAmelCase							:	str) -> List[Any]:

    """simple docstring"""







    _snake_case			:     Dict 		=    AlbertModel(config=__lowerCamelCase)
    model.to(__lowerCamelCase)
    model.eval()
    _snake_case			:     List[Any] 		=    model(__lowerCamelCase ,						attention_mask=__lowerCamelCase ,						token_type_ids=__lowerCamelCase)
    _snake_case			:     str 		=    model(__lowerCamelCase ,						token_type_ids=__lowerCamelCase)
    _snake_case			:     Dict 		=    model(__lowerCamelCase)
    self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.hidden_size))
    self.parent.assertEqual(result.pooler_output.shape ,						(self.batch_size, self.hidden_size))

   def    UpperCamelCase_     (    self							:	Optional[Any] ,						lowerCAmelCase							:	str ,						lowerCAmelCase							:	List[Any] ,						lowerCAmelCase							:	Tuple ,						lowerCAmelCase							:	Tuple ,						lowerCAmelCase							:	Optional[Any] ,						lowerCAmelCase							:	List[Any] ,						lowerCAmelCase							:	List[str]) -> Tuple:

    """simple docstring"""







    _snake_case			:     Tuple 		=    AlbertForPreTraining(config=__lowerCamelCase)
    model.to(__lowerCamelCase)
    model.eval()
    _snake_case			:     Optional[Any] 		=    model(
        __lowerCamelCase ,						attention_mask=__lowerCamelCase ,						token_type_ids=__lowerCamelCase ,						labels=__lowerCamelCase ,						sentence_order_label=__lowerCamelCase ,						)
    self.parent.assertEqual(result.prediction_logits.shape ,						(self.batch_size, self.seq_length, self.vocab_size))
    self.parent.assertEqual(result.sop_logits.shape ,						(self.batch_size, config.num_labels))

   def    UpperCamelCase_     (    self							:	Optional[Any] ,						lowerCAmelCase							:	List[Any] ,						lowerCAmelCase							:	Optional[int] ,						lowerCAmelCase							:	Union[str, Any] ,						lowerCAmelCase							:	Dict ,						lowerCAmelCase							:	Optional[int] ,						lowerCAmelCase							:	Any ,						lowerCAmelCase							:	int) -> int:

    """simple docstring"""







    _snake_case			:     List[Any] 		=    AlbertForMaskedLM(config=__lowerCamelCase)
    model.to(__lowerCamelCase)
    model.eval()
    _snake_case			:     Any 		=    model(__lowerCamelCase ,						attention_mask=__lowerCamelCase ,						token_type_ids=__lowerCamelCase ,						labels=__lowerCamelCase)
    self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.seq_length, self.vocab_size))

   def    UpperCamelCase_     (    self							:	str ,						lowerCAmelCase							:	Union[str, Any] ,						lowerCAmelCase							:	str ,						lowerCAmelCase							:	Any ,						lowerCAmelCase							:	Tuple ,						lowerCAmelCase							:	List[Any] ,						lowerCAmelCase							:	Optional[Any] ,						lowerCAmelCase							:	str) -> str:

    """simple docstring"""







    _snake_case			:     Optional[Any] 		=    AlbertForQuestionAnswering(config=__lowerCamelCase)
    model.to(__lowerCamelCase)
    model.eval()
    _snake_case			:     List[str] 		=    model(
        __lowerCamelCase ,						attention_mask=__lowerCamelCase ,						token_type_ids=__lowerCamelCase ,						start_positions=__lowerCamelCase ,						end_positions=__lowerCamelCase ,						)
    self.parent.assertEqual(result.start_logits.shape ,						(self.batch_size, self.seq_length))
    self.parent.assertEqual(result.end_logits.shape ,						(self.batch_size, self.seq_length))

   def    UpperCamelCase_     (    self							:	Tuple ,						lowerCAmelCase							:	Any ,						lowerCAmelCase							:	Union[str, Any] ,						lowerCAmelCase							:	Optional[Any] ,						lowerCAmelCase							:	Union[str, Any] ,						lowerCAmelCase							:	int ,						lowerCAmelCase							:	str ,						lowerCAmelCase							:	int) -> Union[str, Any]:

    """simple docstring"""







    _snake_case			:     int 		=    self.num_labels
    _snake_case			:     int 		=    AlbertForSequenceClassification(__lowerCamelCase)
    model.to(__lowerCamelCase)
    model.eval()
    _snake_case			:     Tuple 		=    model(__lowerCamelCase ,						attention_mask=__lowerCamelCase ,						token_type_ids=__lowerCamelCase ,						labels=__lowerCamelCase)
    self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.num_labels))

   def    UpperCamelCase_     (    self							:	int ,						lowerCAmelCase							:	int ,						lowerCAmelCase							:	Union[str, Any] ,						lowerCAmelCase							:	Any ,						lowerCAmelCase							:	List[str] ,						lowerCAmelCase							:	Optional[Any] ,						lowerCAmelCase							:	Tuple ,						lowerCAmelCase							:	Dict) -> Optional[int]:

    """simple docstring"""







    _snake_case			:     Union[str, Any] 		=    self.num_labels
    _snake_case			:     Any 		=    AlbertForTokenClassification(config=__lowerCamelCase)
    model.to(__lowerCamelCase)
    model.eval()
    _snake_case			:     List[str] 		=    model(__lowerCamelCase ,						attention_mask=__lowerCamelCase ,						token_type_ids=__lowerCamelCase ,						labels=__lowerCamelCase)
    self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.seq_length, self.num_labels))

   def    UpperCamelCase_     (    self							:	Optional[int] ,						lowerCAmelCase							:	List[str] ,						lowerCAmelCase							:	List[str] ,						lowerCAmelCase							:	List[str] ,						lowerCAmelCase							:	Optional[int] ,						lowerCAmelCase							:	Union[str, Any] ,						lowerCAmelCase							:	Optional[Any] ,						lowerCAmelCase							:	Tuple) -> str:

    """simple docstring"""







    _snake_case			:     Dict 		=    self.num_choices
    _snake_case			:     List[Any] 		=    AlbertForMultipleChoice(config=__lowerCamelCase)
    model.to(__lowerCamelCase)
    model.eval()
    _snake_case			:     Any 		=    input_ids.unsqueeze(1).expand(-1 ,						self.num_choices ,						-1).contiguous()
    _snake_case			:     Dict 		=    token_type_ids.unsqueeze(1).expand(-1 ,						self.num_choices ,						-1).contiguous()
    _snake_case			:     List[Any] 		=    input_mask.unsqueeze(1).expand(-1 ,						self.num_choices ,						-1).contiguous()
    _snake_case			:     int 		=    model(
        __lowerCamelCase ,						attention_mask=__lowerCamelCase ,						token_type_ids=__lowerCamelCase ,						labels=__lowerCamelCase ,						)
    self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.num_choices))


   def    UpperCamelCase_     (    self							:	int) -> List[Any]:

    """simple docstring"""







    _snake_case			:     Any 		=    self.prepare_config_and_inputs()
    (
        _snake_case      
    )			:     Optional[int] 		=    config_and_inputs
    _snake_case			:     Optional[int] 		=    {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
    return config, inputs_dict







@require_torch
class 						snake_case  (		_a    ,_a    ,unittest.TestCase     ):



   '''simple docstring'''






   snake_case_    :       int								=						(
       (
           AlbertModel,
           AlbertForPreTraining,
           AlbertForMaskedLM,
           AlbertForMultipleChoice,
           AlbertForSequenceClassification,
           AlbertForTokenClassification,
           AlbertForQuestionAnswering,
       )
       if is_torch_available()
       else ()
   )
   snake_case_    :       List[Any]								=						(
       {
           """feature-extraction""": AlbertModel,
           """fill-mask""": AlbertForMaskedLM,
           """question-answering""": AlbertForQuestionAnswering,
           """text-classification""": AlbertForSequenceClassification,
           """token-classification""": AlbertForTokenClassification,
           """zero-shot""": AlbertForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   snake_case_    :       Dict								=						True

   def    UpperCamelCase_     (    self							:	List[Any] ,						lowerCAmelCase							:	List[str] ,						lowerCAmelCase							:	str ,						lowerCAmelCase							:	Dict=False) -> List[str]:

    """simple docstring"""







    _snake_case			:     Tuple 		=    super()._prepare_for_class(__lowerCamelCase ,						__lowerCamelCase ,						return_labels=__lowerCamelCase)

    if return_labels:
     if model_class in get_values(__lowerCamelCase):
      _snake_case			:     Optional[int] 		=    torch.zeros(
          (self.model_tester.batch_size, self.model_tester.seq_length) ,						dtype=torch.long ,						device=__lowerCamelCase)
      _snake_case			:     Optional[int] 		=    torch.zeros(
          self.model_tester.batch_size ,						dtype=torch.long ,						device=__lowerCamelCase)
    return inputs_dict

   def    UpperCamelCase_     (    self							:	Any) -> str:

    """simple docstring"""







    _snake_case			:     Optional[int] 		=    AlbertModelTester(self)
    _snake_case			:     Tuple 		=    ConfigTester(self ,						config_class=__lowerCamelCase ,						hidden_size=37)

   def    UpperCamelCase_     (    self							:	Dict) -> Optional[int]:

    """simple docstring"""







    self.config_tester.run_common_tests()

   def    UpperCamelCase_     (    self							:	Dict) -> Any:

    """simple docstring"""







    _snake_case			:     int 		=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCamelCase)

   def    UpperCamelCase_     (    self							:	Union[str, Any]) -> Optional[int]:

    """simple docstring"""







    _snake_case			:     Dict 		=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_pretraining(*__lowerCamelCase)

   def    UpperCamelCase_     (    self							:	List[Any]) -> Union[str, Any]:

    """simple docstring"""







    _snake_case			:     Union[str, Any] 		=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase)

   def    UpperCamelCase_     (    self							:	Optional[int]) -> str:

    """simple docstring"""







    _snake_case			:     List[Any] 		=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_multiple_choice(*__lowerCamelCase)

   def    UpperCamelCase_     (    self							:	str) -> List[str]:

    """simple docstring"""







    _snake_case			:     Any 		=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase)

   def    UpperCamelCase_     (    self							:	Dict) -> List[Any]:

    """simple docstring"""







    _snake_case			:     Optional[int] 		=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase)

   def    UpperCamelCase_     (    self							:	Any) -> Optional[int]:

    """simple docstring"""







    _snake_case			:     Union[str, Any] 		=    self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
     _snake_case			:     Optional[Any] 		=    type
     self.model_tester.create_and_check_model(*__lowerCamelCase)


   @slow
   def    UpperCamelCase_     (    self							:	Dict) -> List[str]:

    """simple docstring"""







    for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case			:     List[Any] 		=    AlbertModel.from_pretrained(__lowerCamelCase)
     self.assertIsNotNone(__lowerCamelCase)







@require_torch
class 						snake_case  (		unittest.TestCase     ):



   '''simple docstring'''






   @slow
   def    UpperCamelCase_     (    self							:	Union[str, Any]) -> Any:

    """simple docstring"""







    _snake_case			:     int 		=    AlbertModel.from_pretrained("""albert-base-v2""")
    _snake_case			:     str 		=    torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
    _snake_case			:     Any 		=    torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
    with torch.no_grad():
     _snake_case			:     List[str] 		=    model(__lowerCamelCase ,						attention_mask=__lowerCamelCase)[0]
    _snake_case			:     Union[str, Any] 		=    torch.Size((1, 11, 768))
    self.assertEqual(output.shape ,						__lowerCamelCase)
    _snake_case			:     Union[str, Any] 		=    torch.tensor(
        [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]])

    self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,						__lowerCamelCase ,						atol=1E-4))








# Copyright 2021 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.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


UpperCAmelCase_ :						Any      =      '''Create a default config file for Accelerate with only a few flags set.'''

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[int]="no"	,			__magic_name__					:  str = default_json_config_file	,			__magic_name__					:  bool = False					)		->			str:






	"""simple docstring"""



	UpperCamelCase     :Any          =	Path(__magic_name__					)
	path.parent.mkdir(parents=__magic_name__	,			exist_ok=__magic_name__					)
	if path.exists():
		print(
		    f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."""					)
		return False
	UpperCamelCase     :Dict          =	mixed_precision.lower()
	if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
		raise ValueError(
		    f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"""					)
	UpperCamelCase     :Optional[Any]          =	{
	    """compute_environment""": """LOCAL_MACHINE""",
	    """mixed_precision""": mixed_precision,
	}
	if torch.cuda.is_available():
		UpperCamelCase     :Union[str, Any]          =	torch.cuda.device_count()
		UpperCamelCase     :List[Any]          =	num_gpus
		UpperCamelCase     :Dict          =	False
		if num_gpus > 1:
			UpperCamelCase     :Any          =	"""MULTI_GPU"""
		else:
			UpperCamelCase     :Any          =	"""NO"""
	elif is_xpu_available() and use_xpu:
		UpperCamelCase     :Optional[Any]          =	torch.xpu.device_count()
		UpperCamelCase     :Optional[int]          =	num_xpus
		UpperCamelCase     :int          =	False
		if num_xpus > 1:
			UpperCamelCase     :Union[str, Any]          =	"""MULTI_XPU"""
		else:
			UpperCamelCase     :Union[str, Any]          =	"""NO"""
	elif is_npu_available():
		UpperCamelCase     :List[Any]          =	torch.npu.device_count()
		UpperCamelCase     :Optional[Any]          =	num_npus
		UpperCamelCase     :Tuple          =	False
		if num_npus > 1:
			UpperCamelCase     :Optional[Any]          =	"""MULTI_NPU"""
		else:
			UpperCamelCase     :List[Any]          =	"""NO"""
	else:
		UpperCamelCase     :Any          =	0
		UpperCamelCase     :Optional[Any]          =	True
		UpperCamelCase     :Optional[Any]          =	1
		UpperCamelCase     :List[str]          =	"""NO"""
	UpperCamelCase     :int          =	ClusterConfig(**__magic_name__					)
	config.to_json_file(__magic_name__					)
	return path

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  Tuple					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Dict          =	parser.add_parser("""default"""	,			parents=__magic_name__	,			help=__magic_name__	,			formatter_class=__magic_name__					)
	parser.add_argument(
	    """--config_file"""	,			default=__magic_name__	,			help=(
	        """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """
	        """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """
	        """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """
	        """with 'huggingface'."""
	    )	,			dest="""save_location"""	,			)

	parser.add_argument(
	    """--mixed_precision"""	,			choices=["""no""", """fp16""", """bf16"""]	,			type=__magic_name__	,			help="""Whether or not to use mixed precision training. """
	    """Choose between FP16 and BF16 (bfloat16) training. """
	    """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later."""	,			default="""no"""	,			)
	parser.set_defaults(func=__magic_name__					)
	return parser

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Optional[Any]          =	write_basic_config(args.mixed_precision	,			args.save_location					)
	if config_file:
		print(f"""accelerate configuration saved at {config_file}"""					)
