






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







		'''simple docstring'''



		def __init__(							self				,		_UpperCamelCase				,		_UpperCamelCase=1_3				,		_UpperCamelCase=7				,		_UpperCamelCase=True				,		_UpperCamelCase=True				,		_UpperCamelCase=False				,		_UpperCamelCase=True				,		_UpperCamelCase=9_9				,		_UpperCamelCase=3_2				,		_UpperCamelCase=5				,		_UpperCamelCase=4				,		_UpperCamelCase=3_7				,		_UpperCamelCase="gelu"				,		_UpperCamelCase=0.1				,		_UpperCamelCase=0.1				,		_UpperCamelCase=5_1_2				,		_UpperCamelCase=1_6				,		_UpperCamelCase=2				,		_UpperCamelCase=0.02				,		_UpperCamelCase=3				,		_UpperCamelCase=4				,		_UpperCamelCase=None				,		)	->							Tuple:
							UpperCAmelCase_    :      Any            =						parent
							UpperCAmelCase_    :      List[str]            =						batch_size
							UpperCAmelCase_    :      Optional[Any]            =						seq_length
							UpperCAmelCase_    :      str            =						is_training
							UpperCAmelCase_    :      Optional[int]            =						use_input_mask
							UpperCAmelCase_    :      int            =						use_token_type_ids
							UpperCAmelCase_    :      List[Any]            =						use_labels
							UpperCAmelCase_    :      Dict            =						vocab_size
							UpperCAmelCase_    :      int            =						hidden_size
							UpperCAmelCase_    :      Dict            =						num_hidden_layers
							UpperCAmelCase_    :      Any            =						num_attention_heads
							UpperCAmelCase_    :      List[str]            =						intermediate_size
							UpperCAmelCase_    :      str            =						hidden_act
							UpperCAmelCase_    :      Any            =						hidden_dropout_prob
							UpperCAmelCase_    :      Tuple            =						attention_probs_dropout_prob
							UpperCAmelCase_    :      Union[str, Any]            =						max_position_embeddings
							UpperCAmelCase_    :      Dict            =						type_vocab_size
							UpperCAmelCase_    :      List[str]            =						type_sequence_label_size
							UpperCAmelCase_    :      int            =						initializer_range
							UpperCAmelCase_    :      Dict            =						num_labels
							UpperCAmelCase_    :      Tuple            =						num_choices
							UpperCAmelCase_    :      int            =						scope



		def 					__UpperCAmelCase			(							self   )	->							Union[str, Any]:
							UpperCAmelCase_    :      int            =						ids_tensor([self.batch_size, self.seq_length]				,		self.vocab_size   )

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

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

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

							UpperCAmelCase_    :      Union[str, Any]            =						self.get_config()

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



		def 					__UpperCAmelCase			(							self   )	->							Optional[int]:
							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=_UpperCamelCase				,		initializer_range=self.initializer_range				,		use_stable_embedding=_UpperCamelCase				,		)



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )	->							Tuple:
							UpperCAmelCase_    :      Dict            =						OpenLlamaModel(config=_UpperCamelCase   )
							model.to(_UpperCamelCase   )
							model.eval()
							UpperCAmelCase_    :      Dict            =						model(_UpperCamelCase				,		attention_mask=_UpperCamelCase   )
							UpperCAmelCase_    :      Dict            =						model(_UpperCamelCase   )
							self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		)	->							List[Any]:
							UpperCAmelCase_    :      Optional[int]            =						True
							UpperCAmelCase_    :      int            =						OpenLlamaModel(_UpperCamelCase   )
							model.to(_UpperCamelCase   )
							model.eval()
							UpperCAmelCase_    :      Dict            =						model(
							    _UpperCamelCase				,		attention_mask=_UpperCamelCase				,		encoder_hidden_states=_UpperCamelCase				,		encoder_attention_mask=_UpperCamelCase				,		)
							UpperCAmelCase_    :      List[Any]            =						model(
							    _UpperCamelCase				,		attention_mask=_UpperCamelCase				,		encoder_hidden_states=_UpperCamelCase				,		)
							UpperCAmelCase_    :      Any            =						model(_UpperCamelCase				,		attention_mask=_UpperCamelCase   )
							self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		)	->							Optional[Any]:
							UpperCAmelCase_    :      Optional[int]            =						OpenLlamaForCausalLM(config=_UpperCamelCase   )
							model.to(_UpperCamelCase   )
							model.eval()
							UpperCAmelCase_    :      List[str]            =						model(_UpperCamelCase				,		attention_mask=_UpperCamelCase				,		labels=_UpperCamelCase   )
							self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.seq_length, self.vocab_size)   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase				,		)	->							str:
							UpperCAmelCase_    :      Tuple            =						True
							UpperCAmelCase_    :      str            =						True
							UpperCAmelCase_    :      List[Any]            =						OpenLlamaForCausalLM(config=_UpperCamelCase   )
							model.to(_UpperCamelCase   )
							model.eval()

							# first forward pass
							UpperCAmelCase_    :      Optional[int]            =						model(
							    _UpperCamelCase				,		attention_mask=_UpperCamelCase				,		encoder_hidden_states=_UpperCamelCase				,		encoder_attention_mask=_UpperCamelCase				,		use_cache=_UpperCamelCase				,		)
							UpperCAmelCase_    :      Tuple            =						outputs.past_key_values

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

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

							UpperCAmelCase_    :      Optional[int]            =						model(
							    _UpperCamelCase				,		attention_mask=_UpperCamelCase				,		encoder_hidden_states=_UpperCamelCase				,		encoder_attention_mask=_UpperCamelCase				,		output_hidden_states=_UpperCamelCase				,		)['hidden_states'][0]
							UpperCAmelCase_    :      str            =						model(
							    _UpperCamelCase				,		attention_mask=_UpperCamelCase				,		encoder_hidden_states=_UpperCamelCase				,		encoder_attention_mask=_UpperCamelCase				,		past_key_values=_UpperCamelCase				,		output_hidden_states=_UpperCamelCase				,		)['hidden_states'][0]

							# select random slice
							UpperCAmelCase_    :      Dict            =						ids_tensor((1,)				,		output_from_past.shape[-1]   ).item()
							UpperCAmelCase_    :      Any            =						output_from_no_past[:, -3:, random_slice_idx].detach()
							UpperCAmelCase_    :      Union[str, 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(_UpperCamelCase				,		_UpperCamelCase				,		atol=1E-3   )   )



		def 					__UpperCAmelCase			(							self   )	->							Tuple:
							UpperCAmelCase_    :      Optional[int]            =						self.prepare_config_and_inputs()
							(
							    (
							    UpperCAmelCase_
							)       ,  (
							    UpperCAmelCase_
							)       ,  (
							    UpperCAmelCase_
							)       ,  (
							    UpperCAmelCase_
							)       ,  (
							    UpperCAmelCase_
							)       ,  (
							    UpperCAmelCase_
							)       ,  (
							    UpperCAmelCase_
							)       ,  
							)    :      Any            =						config_and_inputs
							UpperCAmelCase_    :      Union[str, Any]            =						{'input_ids': input_ids, 'attention_mask': input_mask}
							return config, inputs_dict





@require_torch
class   lowerCamelCase      (_snake_case ,  _snake_case ,  _snake_case ,  unittest.TestCase			):







		'''simple docstring'''



		_snake_case    :    Optional[Any]       						=  (
		    (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
		)
		_snake_case    :    Union[str, Any]       						=  (OpenLlamaForCausalLM,) if is_torch_available() else ()
		_snake_case    :    Union[str, Any]       						=  (
		    {
		        '''feature-extraction''': OpenLlamaModel,
		        '''text-classification''': OpenLlamaForSequenceClassification,
		        '''text-generation''': OpenLlamaForCausalLM,
		        '''zero-shot''': OpenLlamaForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		_snake_case    :    List[str]       						=  False
		_snake_case    :    Any       						=  False



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							UpperCAmelCase_    :      Dict            =						OpenLlamaModelTester(self   )
							UpperCAmelCase_    :      str            =						ConfigTester(self				,		config_class=_UpperCamelCase				,		hidden_size=3_7   )



		def 					__UpperCAmelCase			(							self   )	->							List[str]:
							self.config_tester.run_common_tests()



		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							UpperCAmelCase_    :      str            =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							int:
							UpperCAmelCase_    :      int            =						self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
												UpperCAmelCase_    :      Optional[int]            =						type
												self.model_tester.create_and_check_model(*_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							str:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      Tuple            =						self.model_tester.prepare_config_and_inputs_for_common()
							UpperCAmelCase_    :      str            =						3
							UpperCAmelCase_    :      Union[str, Any]            =						input_dict['input_ids']
							UpperCAmelCase_    :      int            =						input_ids.ne(1   ).to(_UpperCamelCase   )
							UpperCAmelCase_    :      List[Any]            =						ids_tensor([self.model_tester.batch_size]				,		self.model_tester.type_sequence_label_size   )
							UpperCAmelCase_    :      Optional[int]            =						OpenLlamaForSequenceClassification(_UpperCamelCase   )
							model.to(_UpperCamelCase   )
							model.eval()
							UpperCAmelCase_    :      str            =						model(_UpperCamelCase				,		attention_mask=_UpperCamelCase				,		labels=_UpperCamelCase   )
							self.assertEqual(result.logits.shape				,		(self.model_tester.batch_size, self.model_tester.num_labels)   )



		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      int            =						self.model_tester.prepare_config_and_inputs_for_common()
							UpperCAmelCase_    :      Optional[int]            =						3
							UpperCAmelCase_    :      List[Any]            =						'single_label_classification'
							UpperCAmelCase_    :      int            =						input_dict['input_ids']
							UpperCAmelCase_    :      List[str]            =						input_ids.ne(1   ).to(_UpperCamelCase   )
							UpperCAmelCase_    :      Tuple            =						ids_tensor([self.model_tester.batch_size]				,		self.model_tester.type_sequence_label_size   )
							UpperCAmelCase_    :      Optional[Any]            =						OpenLlamaForSequenceClassification(_UpperCamelCase   )
							model.to(_UpperCamelCase   )
							model.eval()
							UpperCAmelCase_    :      str            =						model(_UpperCamelCase				,		attention_mask=_UpperCamelCase				,		labels=_UpperCamelCase   )
							self.assertEqual(result.logits.shape				,		(self.model_tester.batch_size, self.model_tester.num_labels)   )



		def 					__UpperCAmelCase			(							self   )	->							Any:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      str            =						self.model_tester.prepare_config_and_inputs_for_common()
							UpperCAmelCase_    :      List[str]            =						3
							UpperCAmelCase_    :      List[str]            =						'multi_label_classification'
							UpperCAmelCase_    :      Tuple            =						input_dict['input_ids']
							UpperCAmelCase_    :      Tuple            =						input_ids.ne(1   ).to(_UpperCamelCase   )
							UpperCAmelCase_    :      str            =						ids_tensor(
							    [self.model_tester.batch_size, config.num_labels]				,		self.model_tester.type_sequence_label_size   ).to(torch.float   )
							UpperCAmelCase_    :      Optional[int]            =						OpenLlamaForSequenceClassification(_UpperCamelCase   )
							model.to(_UpperCamelCase   )
							model.eval()
							UpperCAmelCase_    :      Union[str, Any]            =						model(_UpperCamelCase				,		attention_mask=_UpperCamelCase				,		labels=_UpperCamelCase   )
							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 					__UpperCAmelCase			(							self   )	->							Dict:
							pass



		@parameterized.expand([('linear',), ('dynamic',)]   )
		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase   )	->							Any:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      List[str]            =						self.model_tester.prepare_config_and_inputs_for_common()
							UpperCAmelCase_    :      Any            =						ids_tensor([1, 1_0]				,		config.vocab_size   )
							UpperCAmelCase_    :      Dict            =						ids_tensor([1, int(config.max_position_embeddings * 1.5   )]				,		config.vocab_size   )

							set_seed(4_2   )  # Fixed seed at init time so the two models get the same random weights
							UpperCAmelCase_    :      str            =						OpenLlamaModel(_UpperCamelCase   )
							original_model.to(_UpperCamelCase   )
							original_model.eval()
							UpperCAmelCase_    :      Any            =						original_model(_UpperCamelCase   ).last_hidden_state
							UpperCAmelCase_    :      Optional[Any]            =						original_model(_UpperCamelCase   ).last_hidden_state

							set_seed(4_2   )  # Fixed seed at init time so the two models get the same random weights
							UpperCAmelCase_    :      Any            =						{'type': scaling_type, 'factor': 10.0}
							UpperCAmelCase_    :      Optional[int]            =						OpenLlamaModel(_UpperCamelCase   )
							scaled_model.to(_UpperCamelCase   )
							scaled_model.eval()
							UpperCAmelCase_    :      Dict            =						scaled_model(_UpperCamelCase   ).last_hidden_state
							UpperCAmelCase_    :      Union[str, Any]            =						scaled_model(_UpperCamelCase   ).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(_UpperCamelCase				,		_UpperCamelCase				,		atol=1E-5   )   )
							else:
												self.assertFalse(torch.allclose(_UpperCamelCase				,		_UpperCamelCase				,		atol=1E-5   )   )

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











from __future__ import annotations

from typing import Any





def      __snake_case	(			_UpperCAmelCase				):
    if not postfix_notation:
        return 0

    __a						       =				{'''+''', '''-''', '''*''', '''/'''}
    __a						       =				[]

    for token in postfix_notation:
        if token in operations:
            __a       ,   __a						       =				stack.pop(), stack.pop()
            if token == "+":
                stack.append(a + b				)
            elif token == "-":
                stack.append(a - b				)
            elif token == "*":
                stack.append(a * b				)
            else:
                if a * b < 0 and a % b != 0:
                    stack.append(a // b + 1				)
                else:
                    stack.append(a // b				)
        else:
            stack.append(int(_UpperCAmelCase				)				)

    return stack.pop()


if __name__ == "__main__":
 import doctest

 doctest.testmod()





