






'''simple docstring'''

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 							__magic_name__     :







	"""simple docstring"""



	def __init__(							self  ,      _lowercase  ,      _lowercase=13  ,      _lowercase=7  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=99  ,      _lowercase=16  ,      _lowercase=36  ,      _lowercase=6  ,      _lowercase=6  ,      _lowercase=6  ,      _lowercase=37  ,      _lowercase="gelu"  ,      _lowercase=0.1  ,      _lowercase=0.1  ,      _lowercase=512  ,      _lowercase=16  ,      _lowercase=2  ,      _lowercase=0.02  ,      _lowercase=3  ,      _lowercase=4  ,      _lowercase=None  ,      )						->  List[Any]:
							lowercase_      :   List[Any]        =			parent
							lowercase_      :   Union[str, Any]        =			batch_size
							lowercase_      :   Any        =			seq_length
							lowercase_      :   List[Any]        =			is_training
							lowercase_      :   Any        =			use_input_mask
							lowercase_      :   Optional[int]        =			use_token_type_ids
							lowercase_      :   Optional[Any]        =			use_labels
							lowercase_      :   Optional[int]        =			vocab_size
							lowercase_      :   Union[str, Any]        =			embedding_size
							lowercase_      :   Union[str, Any]        =			hidden_size
							lowercase_      :   str        =			num_hidden_layers
							lowercase_      :   str        =			num_hidden_groups
							lowercase_      :   int        =			num_attention_heads
							lowercase_      :   int        =			intermediate_size
							lowercase_      :   str        =			hidden_act
							lowercase_      :   List[Any]        =			hidden_dropout_prob
							lowercase_      :   Union[str, Any]        =			attention_probs_dropout_prob
							lowercase_      :   List[str]        =			max_position_embeddings
							lowercase_      :   Any        =			type_vocab_size
							lowercase_      :   Any        =			type_sequence_label_size
							lowercase_      :   str        =			initializer_range
							lowercase_      :   Optional[Any]        =			num_labels
							lowercase_      :   List[str]        =			num_choices
							lowercase_      :   Tuple        =			scope
	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							lowercase_      :   Tuple        =			ids_tensor([self.batch_size, self.seq_length]  ,      self.vocab_size       )

							lowercase_      :   Tuple        =			None
							if self.use_input_mask:
													lowercase_      :   Tuple        =			random_attention_mask([self.batch_size, self.seq_length]       )

							lowercase_      :   Tuple        =			None
							if self.use_token_type_ids:
													lowercase_      :   Tuple        =			ids_tensor([self.batch_size, self.seq_length]  ,      self.type_vocab_size       )

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

							lowercase_      :   Any        =			self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
	def        lowerCamelCase__		(							self       )						->  Any:
							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        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  List[Any]:
							lowercase_      :   Dict        =			AlbertModel(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Optional[int]        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase       )
							lowercase_      :   Dict        =			model(_lowercase  ,      token_type_ids=_lowercase       )
							lowercase_      :   str        =			model(_lowercase       )
							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        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Dict:
							lowercase_      :   Optional[int]        =			AlbertForPreTraining(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Dict        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase  ,      sentence_order_label=_lowercase  ,      )
							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        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Tuple:
							lowercase_      :   Optional[Any]        =			AlbertForMaskedLM(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Dict        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.seq_length, self.vocab_size)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Optional[int]:
							lowercase_      :   Optional[Any]        =			AlbertForQuestionAnswering(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Tuple        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      start_positions=_lowercase  ,      end_positions=_lowercase  ,      )
							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        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Optional[Any]:
							lowercase_      :   Dict        =			self.num_labels
							lowercase_      :   Union[str, Any]        =			AlbertForSequenceClassification(_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Optional[int]        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_labels)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  str:
							lowercase_      :   List[Any]        =			self.num_labels
							lowercase_      :   Optional[Any]        =			AlbertForTokenClassification(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   List[Any]        =			model(_lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.seq_length, self.num_labels)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Union[str, Any]:
							lowercase_      :   List[Any]        =			self.num_choices
							lowercase_      :   Tuple        =			AlbertForMultipleChoice(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Union[str, Any]        =			input_ids.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   str        =			token_type_ids.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   Tuple        =			input_mask.unsqueeze(1       ).expand(-1  ,      self.num_choices  ,      -1       ).contiguous()
							lowercase_      :   List[Any]        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      token_type_ids=_lowercase  ,      labels=_lowercase  ,      )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_choices)       )







	def        lowerCamelCase__		(							self       )						->  List[str]:
							lowercase_      :   List[Any]        =			self.prepare_config_and_inputs()
							(
							    (
							    lowercase_
							)  ,      (
							    lowercase_
							)  ,      (
							    lowercase_
							)  ,      (
							    lowercase_
							)  ,      (
							    lowercase_
							)  ,      (
							    lowercase_
							)  ,      (
							    lowercase_
							)  ,      
							)      :   int        =			config_and_inputs
							lowercase_      :   Dict        =			{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
							return config, inputs_dict






@require_torch
class 							__magic_name__     (	UpperCAmelCase_,						UpperCAmelCase_,						unittest.TestCase				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      Optional[Any]        =  (
	    (
	        AlbertModel,
	        AlbertForPreTraining,
	        AlbertForMaskedLM,
	        AlbertForMultipleChoice,
	        AlbertForSequenceClassification,
	        AlbertForTokenClassification,
	        AlbertForQuestionAnswering,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE_					:      Union[str, Any]        =  (
	    {
	        'feature-extraction': AlbertModel,
	        'fill-mask': AlbertForMaskedLM,
	        'question-answering': AlbertForQuestionAnswering,
	        'text-classification': AlbertForSequenceClassification,
	        'token-classification': AlbertForTokenClassification,
	        'zero-shot': AlbertForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE_					:      Optional[Any]        =  True
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase=False       )						->  str:
							lowercase_      :   List[Any]        =			super()._prepare_for_class(_lowercase  ,      _lowercase  ,      return_labels=_lowercase       )

							if return_labels:
													if model_class in get_values(_lowercase       ):
																			lowercase_      :   Optional[Any]        =			torch.zeros(
																			    (self.model_tester.batch_size, self.model_tester.seq_length)  ,      dtype=torch.long  ,      device=_lowercase       )
																			lowercase_      :   Dict        =			torch.zeros(
																			    self.model_tester.batch_size  ,      dtype=torch.long  ,      device=_lowercase       )
							return inputs_dict
	def        lowerCamelCase__		(							self       )						->  Dict:
							lowercase_      :   List[str]        =			AlbertModelTester(self       )
							lowercase_      :   str        =			ConfigTester(self  ,      config_class=_lowercase  ,      hidden_size=37       )
	def        lowerCamelCase__		(							self       )						->  Tuple:
							self.config_tester.run_common_tests()
	def        lowerCamelCase__		(							self       )						->  Dict:
							lowercase_      :   Optional[Any]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							lowercase_      :   List[str]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_pretraining(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Any:
							lowercase_      :   Union[str, Any]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Any:
							lowercase_      :   Optional[Any]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Dict:
							lowercase_      :   Tuple        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   List[str]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							lowercase_      :   Any        =			self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
													lowercase_      :   Tuple        =			type
													self.model_tester.create_and_check_model(*_lowercase       )







	@slow
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowercase_      :   Tuple        =			AlbertModel.from_pretrained(_lowercase       )
													self.assertIsNotNone(_lowercase       )






@require_torch
class 							__magic_name__     (	unittest.TestCase				):







	"""simple docstring"""



	@slow
	def        lowerCamelCase__		(							self       )						->  Any:
							lowercase_      :   List[str]        =			AlbertModel.from_pretrained('albert-base-v2'       )
							lowercase_      :   int        =			torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]       )
							lowercase_      :   Optional[Any]        =			torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]       )
							with torch.no_grad():
													lowercase_      :   List[Any]        =			model(_lowercase  ,      attention_mask=_lowercase       )[0]
							lowercase_      :   str        =			torch.Size((1, 11, 768)       )
							self.assertEqual(output.shape  ,      _lowercase       )
							lowercase_      :   Tuple        =			torch.tensor(
							    [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]]       )

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








'''simple docstring'''

import json
import logging
import os
import socket

import git
import numpy as np
import torch


logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d -  %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    level=logging.INFO,
)
A:      Tuple  				=				logging.getLogger(__name__)






def 	_UpperCAmelCase    (  a		:	str							)			->			List[Any]:





						"""simple docstring"""
						lowercase_      :   List[str]        =			git.Repo(search_parent_directories=a							)
						lowercase_      :   Union[str, Any]        =			{
						    'repo_id': str(a							),
						    'repo_sha': str(repo.head.object.hexsha							),
						    'repo_branch': str(repo.active_branch							),
						}

						with open(os.path.join(a						,			'git_log.json'							)						,			'w'							) as f:
												json.dump(a						,			a						,			indent=4							)






def 	_UpperCAmelCase    (  a		:	str							)			->			Union[str, Any]:





						"""simple docstring"""
						if params.n_gpu <= 0:
												lowercase_      :   int        =			0
												lowercase_      :   Union[str, Any]        =			-1
												lowercase_      :   List[str]        =			True
												lowercase_      :   Optional[Any]        =			False
												return

						assert torch.cuda.is_available()

						logger.info('Initializing GPUs'							)
						if params.n_gpu > 1:
												assert params.local_rank != -1

												lowercase_      :   Dict        =			int(os.environ['WORLD_SIZE']							)
												lowercase_      :   Union[str, Any]        =			int(os.environ['N_GPU_NODE']							)
												lowercase_      :   Optional[int]        =			int(os.environ['RANK']							)

												# number of nodes / node ID
												lowercase_      :   int        =			params.world_size // params.n_gpu_per_node
												lowercase_      :   str        =			params.global_rank // params.n_gpu_per_node
												lowercase_      :   Dict        =			True

												assert params.n_nodes == int(os.environ['N_NODES']							)
												assert params.node_id == int(os.environ['NODE_RANK']							)

						# local job (single GPU)
						else:
												assert params.local_rank == -1

												lowercase_      :   str        =			1
												lowercase_      :   Dict        =			0
												lowercase_      :   Tuple        =			0
												lowercase_      :   List[Any]        =			0
												lowercase_      :   int        =			1
												lowercase_      :   Tuple        =			1
												lowercase_      :   str        =			False

						# sanity checks
						assert params.n_nodes >= 1
						assert 0 <= params.node_id < params.n_nodes
						assert 0 <= params.local_rank <= params.global_rank < params.world_size
						assert params.world_size == params.n_nodes * params.n_gpu_per_node

						# define whether this is the master process / if we are in multi-node distributed mode
						lowercase_      :   List[str]        =			params.node_id == 0 and params.local_rank == 0
						lowercase_      :   Optional[Any]        =			params.n_nodes > 1

						# summary
						lowercase_      :   int        =			f"--- Global rank: {params.global_rank} - "
						logger.info(PREFIX + 'Number of nodes: %i' % params.n_nodes							)
						logger.info(PREFIX + 'Node ID        : %i' % params.node_id							)
						logger.info(PREFIX + 'Local rank     : %i' % params.local_rank							)
						logger.info(PREFIX + 'World size     : %i' % params.world_size							)
						logger.info(PREFIX + 'GPUs per node  : %i' % params.n_gpu_per_node							)
						logger.info(PREFIX + 'Master         : %s' % str(params.is_master							)							)
						logger.info(PREFIX + 'Multi-node     : %s' % str(params.multi_node							)							)
						logger.info(PREFIX + 'Multi-GPU      : %s' % str(params.multi_gpu							)							)
						logger.info(PREFIX + 'Hostname       : %s' % socket.gethostname()							)

						# set GPU device
						torch.cuda.set_device(params.local_rank							)

						# initialize multi-GPU
						if params.multi_gpu:
												logger.info('Initializing PyTorch distributed'							)
												torch.distributed.init_process_group(
												    init_method='env://'						,			backend='nccl'						,			)






def 	_UpperCAmelCase    (  a		:	Dict							)			->			Optional[int]:





						"""simple docstring"""
						np.random.seed(args.seed							)
						torch.manual_seed(args.seed							)
						if args.n_gpu > 0:
												torch.cuda.manual_seed_all(args.seed							)
