






'''simple docstring'''

import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel






class 							__magic_name__     :







	"""simple docstring"""



	def __init__(							self  ,      _lowercase  ,      _lowercase=13  ,      _lowercase=7  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=False  ,      _lowercase=True  ,      _lowercase=99  ,      _lowercase=32  ,      _lowercase=5  ,      _lowercase=4  ,      _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  ,      )						->  Optional[int]:
							lowercase_      :   str        =			parent
							lowercase_      :   Union[str, Any]        =			batch_size
							lowercase_      :   Tuple        =			seq_length
							lowercase_      :   Optional[Any]        =			is_training
							lowercase_      :   List[Any]        =			use_input_mask
							lowercase_      :   int        =			use_token_type_ids
							lowercase_      :   Optional[Any]        =			use_labels
							lowercase_      :   Optional[int]        =			vocab_size
							lowercase_      :   Tuple        =			hidden_size
							lowercase_      :   Dict        =			num_hidden_layers
							lowercase_      :   Optional[Any]        =			num_attention_heads
							lowercase_      :   Union[str, Any]        =			intermediate_size
							lowercase_      :   Tuple        =			hidden_act
							lowercase_      :   List[str]        =			hidden_dropout_prob
							lowercase_      :   Dict        =			attention_probs_dropout_prob
							lowercase_      :   List[Any]        =			max_position_embeddings
							lowercase_      :   Any        =			type_vocab_size
							lowercase_      :   int        =			type_sequence_label_size
							lowercase_      :   Dict        =			initializer_range
							lowercase_      :   Optional[Any]        =			num_labels
							lowercase_      :   List[str]        =			num_choices
							lowercase_      :   List[Any]        =			scope
	def        lowerCamelCase__		(							self       )						->  List[str]:
							lowercase_      :   Any        =			ids_tensor([self.batch_size, self.seq_length]  ,      self.vocab_size       )

							lowercase_      :   Union[str, Any]        =			None
							if self.use_input_mask:
													lowercase_      :   int        =			random_attention_mask([self.batch_size, self.seq_length]       )

							lowercase_      :   Union[str, Any]        =			None
							if self.use_token_type_ids:
													lowercase_      :   Dict        =			ids_tensor([self.batch_size, self.seq_length]  ,      self.type_vocab_size       )

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

							lowercase_      :   Optional[Any]        =			self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							return OpenLlamaConfig(
							    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  ,      is_decoder=_lowercase  ,      initializer_range=self.initializer_range  ,      use_stable_embedding=_lowercase  ,      )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  List[Any]:
							lowercase_      :   Optional[int]        =			OpenLlamaModel(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   str        =			model(_lowercase  ,      attention_mask=_lowercase       )
							lowercase_      :   Tuple        =			model(_lowercase       )
							self.parent.assertEqual(result.last_hidden_state.shape  ,      (self.batch_size, self.seq_length, self.hidden_size)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      )						->  Optional[Any]:
							lowercase_      :   Optional[Any]        =			True
							lowercase_      :   str        =			OpenLlamaModel(_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   str        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      encoder_hidden_states=_lowercase  ,      encoder_attention_mask=_lowercase  ,      )
							lowercase_      :   Dict        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      encoder_hidden_states=_lowercase  ,      )
							lowercase_      :   Tuple        =			model(_lowercase  ,      attention_mask=_lowercase       )
							self.parent.assertEqual(result.last_hidden_state.shape  ,      (self.batch_size, self.seq_length, self.hidden_size)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      )						->  Optional[int]:
							lowercase_      :   Optional[Any]        =			OpenLlamaForCausalLM(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   List[Any]        =			model(_lowercase  ,      attention_mask=_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  ,      _lowercase  ,      _lowercase  ,      )						->  List[str]:
							lowercase_      :   Any        =			True
							lowercase_      :   Any        =			True
							lowercase_      :   Tuple        =			OpenLlamaForCausalLM(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()

							# first forward pass
							lowercase_      :   int        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      encoder_hidden_states=_lowercase  ,      encoder_attention_mask=_lowercase  ,      use_cache=_lowercase  ,      )
							lowercase_      :   Optional[Any]        =			outputs.past_key_values

							# create hypothetical multiple next token and extent to next_input_ids
							lowercase_      :   Any        =			ids_tensor((self.batch_size, 3)  ,      config.vocab_size       )
							lowercase_      :   Optional[Any]        =			ids_tensor((self.batch_size, 3)  ,      vocab_size=2       )

							# append to next input_ids and
							lowercase_      :   str        =			torch.cat([input_ids, next_tokens]  ,      dim=-1       )
							lowercase_      :   Optional[int]        =			torch.cat([input_mask, next_mask]  ,      dim=-1       )

							lowercase_      :   Optional[Any]        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      encoder_hidden_states=_lowercase  ,      encoder_attention_mask=_lowercase  ,      output_hidden_states=_lowercase  ,      )['hidden_states'][0]
							lowercase_      :   Union[str, Any]        =			model(
							    _lowercase  ,      attention_mask=_lowercase  ,      encoder_hidden_states=_lowercase  ,      encoder_attention_mask=_lowercase  ,      past_key_values=_lowercase  ,      output_hidden_states=_lowercase  ,      )['hidden_states'][0]

							# select random slice
							lowercase_      :   Any        =			ids_tensor((1,)  ,      output_from_past.shape[-1]       ).item()
							lowercase_      :   Optional[int]        =			output_from_no_past[:, -3:, random_slice_idx].detach()
							lowercase_      :   Optional[Any]        =			output_from_past[:, :, random_slice_idx].detach()

							self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]       )

							# test that outputs are equal for slice
							self.parent.assertTrue(torch.allclose(_lowercase  ,      _lowercase  ,      atol=1E-3       )       )







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






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







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      int        =  (
	    (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
	)
	SCREAMING_SNAKE_CASE_					:      Dict        =  (OpenLlamaForCausalLM,) if is_torch_available() else ()
	SCREAMING_SNAKE_CASE_					:      Dict        =  (
	    {
	        'feature-extraction': OpenLlamaModel,
	        'text-classification': OpenLlamaForSequenceClassification,
	        'text-generation': OpenLlamaForCausalLM,
	        'zero-shot': OpenLlamaForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE_					:      Any        =  False
	SCREAMING_SNAKE_CASE_					:      Optional[int]        =  False
	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   str        =			OpenLlamaModelTester(self       )
							lowercase_      :   List[Any]        =			ConfigTester(self  ,      config_class=_lowercase  ,      hidden_size=37       )
	def        lowerCamelCase__		(							self       )						->  List[str]:
							self.config_tester.run_common_tests()
	def        lowerCamelCase__		(							self       )						->  int:
							lowercase_      :   List[str]        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  List[Any]:
							lowercase_      :   List[Any]        =			self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
													lowercase_      :   Union[str, Any]        =			type
													self.model_tester.create_and_check_model(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Union[str, Any]:
							lowercase_  ,      lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs_for_common()
							lowercase_      :   str        =			3
							lowercase_      :   Optional[int]        =			input_dict['input_ids']
							lowercase_      :   str        =			input_ids.ne(1       ).to(_lowercase       )
							lowercase_      :   Tuple        =			ids_tensor([self.model_tester.batch_size]  ,      self.model_tester.type_sequence_label_size       )
							lowercase_      :   Dict        =			OpenLlamaForSequenceClassification(_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Optional[int]        =			model(_lowercase  ,      attention_mask=_lowercase  ,      labels=_lowercase       )
							self.assertEqual(result.logits.shape  ,      (self.model_tester.batch_size, self.model_tester.num_labels)       )
	def        lowerCamelCase__		(							self       )						->  Optional[int]:
							lowercase_  ,      lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs_for_common()
							lowercase_      :   Optional[int]        =			3
							lowercase_      :   Union[str, Any]        =			'single_label_classification'
							lowercase_      :   List[str]        =			input_dict['input_ids']
							lowercase_      :   Union[str, Any]        =			input_ids.ne(1       ).to(_lowercase       )
							lowercase_      :   int        =			ids_tensor([self.model_tester.batch_size]  ,      self.model_tester.type_sequence_label_size       )
							lowercase_      :   List[Any]        =			OpenLlamaForSequenceClassification(_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   List[str]        =			model(_lowercase  ,      attention_mask=_lowercase  ,      labels=_lowercase       )
							self.assertEqual(result.logits.shape  ,      (self.model_tester.batch_size, self.model_tester.num_labels)       )
	def        lowerCamelCase__		(							self       )						->  Tuple:
							lowercase_  ,      lowercase_      :   Dict        =			self.model_tester.prepare_config_and_inputs_for_common()
							lowercase_      :   Optional[Any]        =			3
							lowercase_      :   int        =			'multi_label_classification'
							lowercase_      :   Tuple        =			input_dict['input_ids']
							lowercase_      :   List[str]        =			input_ids.ne(1       ).to(_lowercase       )
							lowercase_      :   Optional[int]        =			ids_tensor(
							    [self.model_tester.batch_size, config.num_labels]  ,      self.model_tester.type_sequence_label_size       ).to(torch.float       )
							lowercase_      :   Dict        =			OpenLlamaForSequenceClassification(_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Tuple        =			model(_lowercase  ,      attention_mask=_lowercase  ,      labels=_lowercase       )
							self.assertEqual(result.logits.shape  ,      (self.model_tester.batch_size, self.model_tester.num_labels)       )
	@unittest.skip('Open-Llama buffers include complex numbers, which breaks this test'       )
	def        lowerCamelCase__		(							self       )						->  int:
							pass







	@parameterized.expand([('linear',), ('dynamic',)]       )
	def        lowerCamelCase__		(							self  ,      _lowercase       )						->  Any:
							lowercase_  ,      lowercase_      :   List[str]        =			self.model_tester.prepare_config_and_inputs_for_common()
							lowercase_      :   Any        =			ids_tensor([1, 10]  ,      config.vocab_size       )
							lowercase_      :   Tuple        =			ids_tensor([1, int(config.max_position_embeddings * 1.5       )]  ,      config.vocab_size       )

							set_seed(42       )  # Fixed seed at init time so the two models get the same random weights
							lowercase_      :   List[str]        =			OpenLlamaModel(_lowercase       )
							original_model.to(_lowercase       )
							original_model.eval()
							lowercase_      :   int        =			original_model(_lowercase       ).last_hidden_state
							lowercase_      :   int        =			original_model(_lowercase       ).last_hidden_state

							set_seed(42       )  # Fixed seed at init time so the two models get the same random weights
							lowercase_      :   Optional[Any]        =			{'type': scaling_type, 'factor': 10.0}
							lowercase_      :   str        =			OpenLlamaModel(_lowercase       )
							scaled_model.to(_lowercase       )
							scaled_model.eval()
							lowercase_      :   int        =			scaled_model(_lowercase       ).last_hidden_state
							lowercase_      :   List[str]        =			scaled_model(_lowercase       ).last_hidden_state

							# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
							# maximum sequence length, so the outputs for the short input should match.
							if scaling_type == "dynamic":
													self.assertTrue(torch.allclose(_lowercase  ,      _lowercase  ,      atol=1E-5       )       )
							else:
													self.assertFalse(torch.allclose(_lowercase  ,      _lowercase  ,      atol=1E-5       )       )

							# The output should be different for long inputs
							self.assertFalse(torch.allclose(_lowercase  ,      _lowercase  ,      atol=1E-5       )       )








'''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							)
