import unittest

from parameterized import parameterized

from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, 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 LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer


class 	lowerCamelCase_     :






    '''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 , )       ->	Dict:
        __UpperCamelCase     :Union[str, Any]			  =		parent
        __UpperCamelCase     :List[str]			  =		batch_size
        __UpperCamelCase     :int			  =		seq_length
        __UpperCamelCase     :str			  =		is_training
        __UpperCamelCase     :Optional[Any]			  =		use_input_mask
        __UpperCamelCase     :List[Any]			  =		use_token_type_ids
        __UpperCamelCase     :Optional[Any]			  =		use_labels
        __UpperCamelCase     :List[Any]			  =		vocab_size
        __UpperCamelCase     :Optional[int]			  =		hidden_size
        __UpperCamelCase     :Tuple			  =		num_hidden_layers
        __UpperCamelCase     :Tuple			  =		num_attention_heads
        __UpperCamelCase     :Optional[int]			  =		intermediate_size
        __UpperCamelCase     :Union[str, Any]			  =		hidden_act
        __UpperCamelCase     :int			  =		hidden_dropout_prob
        __UpperCamelCase     :Optional[int]			  =		attention_probs_dropout_prob
        __UpperCamelCase     :Tuple			  =		max_position_embeddings
        __UpperCamelCase     :str			  =		type_vocab_size
        __UpperCamelCase     :List[Any]			  =		type_sequence_label_size
        __UpperCamelCase     :Optional[int]			  =		initializer_range
        __UpperCamelCase     :str			  =		num_labels
        __UpperCamelCase     :Any			  =		num_choices
        __UpperCamelCase     :Any			  =		scope







    def 			UpperCamelCase__   (	self)       ->	List[Any]:
        __UpperCamelCase     :List[str]			  =		ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)

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

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

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

        __UpperCamelCase     :int			  =		self.get_config()

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







    def 			UpperCamelCase__   (	self)       ->	str:
        return LlamaConfig(
            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 , )







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase)       ->	Tuple:
        __UpperCamelCase     :str			  =		LlamaModel(config=__lowercase)
        model.to(__lowercase)
        model.eval()
        __UpperCamelCase     :str			  =		model(__lowercase , attention_mask=__lowercase)
        __UpperCamelCase     :Any			  =		model(__lowercase)
        self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , )       ->	Tuple:
        __UpperCamelCase     :Optional[Any]			  =		True
        __UpperCamelCase     :Dict			  =		LlamaModel(__lowercase)
        model.to(__lowercase)
        model.eval()
        __UpperCamelCase     :int			  =		model(
            __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , )
        __UpperCamelCase     :Any			  =		model(
            __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , )
        __UpperCamelCase     :Tuple			  =		model(__lowercase , attention_mask=__lowercase)
        self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , )       ->	Optional[Any]:
        __UpperCamelCase     :Optional[int]			  =		LlamaForCausalLM(config=__lowercase)
        model.to(__lowercase)
        model.eval()
        __UpperCamelCase     :Any			  =		model(__lowercase , attention_mask=__lowercase , labels=__lowercase)
        self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size))







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , )       ->	List[Any]:
        __UpperCamelCase     :str			  =		True
        __UpperCamelCase     :Tuple			  =		True
        __UpperCamelCase     :List[Any]			  =		LlamaForCausalLM(config=__lowercase)
        model.to(__lowercase)
        model.eval()

        # first forward pass
        __UpperCamelCase     :Union[str, Any]			  =		model(
            __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , use_cache=__lowercase , )
        __UpperCamelCase     :Optional[Any]			  =		outputs.past_key_values

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

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

        __UpperCamelCase     :Union[str, Any]			  =		model(
            __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , output_hidden_states=__lowercase , )['''hidden_states'''][0]
        __UpperCamelCase     :Tuple			  =		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
        __UpperCamelCase     :Any			  =		ids_tensor((1,) , output_from_past.shape[-1]).item()
        __UpperCamelCase     :Optional[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(__lowercase , __lowercase , atol=1E-3))







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


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






    '''simple docstring'''






    a__	:						Union[str, Any]						=      (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
    a__	:						Union[str, Any]						=      (LlamaForCausalLM,) if is_torch_available() else ()
    a__	:						List[Any]						=      (
        {
            """feature-extraction""": LlamaModel,
            """text-classification""": LlamaForSequenceClassification,
            """text-generation""": LlamaForCausalLM,
            """zero-shot""": LlamaForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    a__	:						Tuple						=      False
    a__	:						Any						=      False







    def 			UpperCamelCase__   (	self)       ->	str:
        __UpperCamelCase     :Dict			  =		LlamaModelTester(self)
        __UpperCamelCase     :Union[str, Any]			  =		ConfigTester(self , config_class=__lowercase , hidden_size=37)







    def 			UpperCamelCase__   (	self)       ->	Dict:
        self.config_tester.run_common_tests()







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :int			  =		self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowercase)







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        __UpperCamelCase     :List[str]			  =		self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
            __UpperCamelCase     :Any			  =		type
            self.model_tester.create_and_check_model(*__lowercase)







    def 			UpperCamelCase__   (	self)       ->	List[str]:
        __UpperCamelCase  ,       __UpperCamelCase     :Union[str, Any]			  =		self.model_tester.prepare_config_and_inputs_for_common()
        __UpperCamelCase     :Dict			  =		3
        __UpperCamelCase     :int			  =		input_dict['''input_ids''']
        __UpperCamelCase     :Tuple			  =		input_ids.ne(1).to(__lowercase)
        __UpperCamelCase     :Any			  =		ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size)
        __UpperCamelCase     :str			  =		LlamaForSequenceClassification(__lowercase)
        model.to(__lowercase)
        model.eval()
        __UpperCamelCase     :str			  =		model(__lowercase , attention_mask=__lowercase , labels=__lowercase)
        self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels))







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







    def 			UpperCamelCase__   (	self)       ->	Dict:
        __UpperCamelCase  ,       __UpperCamelCase     :Dict			  =		self.model_tester.prepare_config_and_inputs_for_common()
        __UpperCamelCase     :int			  =		3
        __UpperCamelCase     :Dict			  =		'''multi_label_classification'''
        __UpperCamelCase     :Optional[int]			  =		input_dict['''input_ids''']
        __UpperCamelCase     :int			  =		input_ids.ne(1).to(__lowercase)
        __UpperCamelCase     :Optional[int]			  =		ids_tensor(
            [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size).to(torch.float)
        __UpperCamelCase     :str			  =		LlamaForSequenceClassification(__lowercase)
        model.to(__lowercase)
        model.eval()
        __UpperCamelCase     :Any			  =		model(__lowercase , attention_mask=__lowercase , labels=__lowercase)
        self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels))







    @unittest.skip('''LLaMA buffers include complex numbers, which breaks this test''')
    def 			UpperCamelCase__   (	self)       ->	Optional[Any]:
        pass







    @parameterized.expand([('''linear''',), ('''dynamic''',)])
    def 			UpperCamelCase__   (	self , __lowercase)       ->	Optional[int]:
        __UpperCamelCase  ,       __UpperCamelCase     :List[str]			  =		self.model_tester.prepare_config_and_inputs_for_common()
        __UpperCamelCase     :Union[str, Any]			  =		ids_tensor([1, 10] , config.vocab_size)
        __UpperCamelCase     :List[Any]			  =		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
        __UpperCamelCase     :str			  =		LlamaModel(__lowercase)
        original_model.to(__lowercase)
        original_model.eval()
        __UpperCamelCase     :Optional[Any]			  =		original_model(__lowercase).last_hidden_state
        __UpperCamelCase     :Optional[int]			  =		original_model(__lowercase).last_hidden_state

        set_seed(42)  # Fixed seed at init time so the two models get the same random weights
        __UpperCamelCase     :List[str]			  =		{'''type''': scaling_type, '''factor''': 10.0}
        __UpperCamelCase     :int			  =		LlamaModel(__lowercase)
        scaled_model.to(__lowercase)
        scaled_model.eval()
        __UpperCamelCase     :List[str]			  =		scaled_model(__lowercase).last_hidden_state
        __UpperCamelCase     :List[Any]			  =		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))


@require_torch
class 	lowerCamelCase_     (   unittest.TestCase ):






    '''simple docstring'''






    @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''')
    @slow
    def 			UpperCamelCase__   (	self)       ->	List[str]:
        __UpperCamelCase     :Dict			  =		[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
        __UpperCamelCase     :Optional[Any]			  =		LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-7b-hf''' , device_map='''auto''')
        __UpperCamelCase     :Tuple			  =		model(torch.tensor([input_ids]))
        # Expected mean on dim = -1
        __UpperCamelCase     :Any			  =		torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]])
        torch.testing.assert_close(out.mean(-1) , __lowercase , atol=1E-2 , rtol=1E-2)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        __UpperCamelCase     :Any			  =		torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,])
        # fmt: on
        torch.testing.assert_close(out[0, 0, :30] , __lowercase , atol=1E-5 , rtol=1E-5)







    @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''')
    @slow
    def 			UpperCamelCase__   (	self)       ->	List[Any]:
        __UpperCamelCase     :str			  =		[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
        __UpperCamelCase     :Any			  =		LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-hf''' , device_map='''auto''')
        __UpperCamelCase     :Optional[int]			  =		model(torch.tensor(__lowercase))
        # Expected mean on dim = -1
        __UpperCamelCase     :Any			  =		torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]])
        torch.testing.assert_close(out.mean(-1) , __lowercase , atol=1E-2 , rtol=1E-2)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        __UpperCamelCase     :Union[str, Any]			  =		torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73])
        # fmt: on
        torch.testing.assert_close(out[0, 0, :30] , __lowercase , atol=1E-5 , rtol=1E-5)







    @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''')
    @slow
    def 			UpperCamelCase__   (	self)       ->	int:
        __UpperCamelCase     :Any			  =		[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
        __UpperCamelCase     :Optional[int]			  =		LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' , device_map='''auto''')
        __UpperCamelCase     :str			  =		model(torch.tensor(__lowercase))
        # Expected mean on dim = -1
        __UpperCamelCase     :List[Any]			  =		torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]])
        torch.testing.assert_close(out.mean(-1) , __lowercase , atol=1E-2 , rtol=1E-2)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        __UpperCamelCase     :Union[str, Any]			  =		torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13])
        # fmt: on
        torch.testing.assert_close(out.mean(-1) , __lowercase , atol=1E-2 , rtol=1E-2)







    @unittest.skip(
        '''Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test''')
    @slow
    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :Any			  =		[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
        __UpperCamelCase     :List[Any]			  =		LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-70b-hf''' , device_map='''auto''')
        __UpperCamelCase     :List[str]			  =		model(torch.tensor(__lowercase))

        __UpperCamelCase     :Dict			  =		torch.tensor(
            [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]] , dtype=torch.floataa)
        torch.testing.assert_close(out.mean(-1) , __lowercase , atol=1E-2 , rtol=1E-2)
        # fmt: off
        __UpperCamelCase     :str			  =		torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12])
        # fmt: on
        torch.testing.assert_close(out[0, 0, :30] , __lowercase , atol=1E-5 , rtol=1E-5)







    @unittest.skip('''Model is curently gated''')
    @slow
    def 			UpperCamelCase__   (	self)       ->	str:
        __UpperCamelCase     :List[Any]			  =		'''Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi'''
        __UpperCamelCase     :Optional[int]			  =		'''Simply put, the theory of relativity states that '''
        __UpperCamelCase     :Tuple			  =		LlamaTokenizer.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''')
        __UpperCamelCase     :Dict			  =		tokenizer.encode(__lowercase , return_tensors='''pt''')
        __UpperCamelCase     :Tuple			  =		LlamaForCausalLM.from_pretrained(
            '''meta-llama/Llama-2-13b-chat-hf''' , device_map='''sequential''' , use_safetensors=__lowercase)

        # greedy generation outputs
        __UpperCamelCase     :List[Any]			  =		model.generate(__lowercase , max_new_tokens=64 , top_p=__lowercase , temperature=1 , do_sample=__lowercase)
        __UpperCamelCase     :str			  =		tokenizer.decode(generated_ids[0] , skip_special_tokens=__lowercase)
        self.assertEqual(__lowercase , __lowercase)






import numpy as np



def lowerCamelCase  (   SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE = 1e-12  ,			SCREAMING_SNAKE_CASE = 100  ,			):
    '''simple docstring'''







    assert np.shape(SCREAMING_SNAKE_CASE	)[0] == np.shape(SCREAMING_SNAKE_CASE	)[1]
    # Ensure proper dimensionality.
    assert np.shape(SCREAMING_SNAKE_CASE	)[0] == np.shape(SCREAMING_SNAKE_CASE	)[0]
    # Ensure inputs are either both complex or both real
    assert np.iscomplexobj(SCREAMING_SNAKE_CASE	) == np.iscomplexobj(SCREAMING_SNAKE_CASE	)
    __UpperCamelCase     :List[Any]			  =		np.iscomplexobj(SCREAMING_SNAKE_CASE	)
    if is_complex:
        # Ensure complex input_matrix is Hermitian
        assert np.array_equal(SCREAMING_SNAKE_CASE  ,			input_matrix.conj().T	)

    # Set convergence to False. Will define convergence when we exceed max_iterations
    # or when we have small changes from one iteration to next.

    __UpperCamelCase     :str			  =		False
    __UpperCamelCase     :int			  =		0
    __UpperCamelCase     :Optional[Any]			  =		0
    __UpperCamelCase     :Union[str, Any]			  =		1e12

    while not convergence:
        # Multiple matrix by the vector.
        __UpperCamelCase     :List[str]			  =		np.dot(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)
        # Normalize the resulting output vector.
        __UpperCamelCase     :Tuple			  =		w / np.linalg.norm(SCREAMING_SNAKE_CASE	)
        # Find rayleigh quotient
        # (faster than usual b/c we know vector is normalized already)
        __UpperCamelCase     :int			  =		vector.conj().T if is_complex else vector.T
        __UpperCamelCase     :Optional[int]			  =		np.dot(SCREAMING_SNAKE_CASE  ,			np.dot(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)	)

        # Check convergence.
        __UpperCamelCase     :Optional[Any]			  =		np.abs(lambda_ - lambda_previous	) / lambda_
        iterations += 1

        if error <= error_tol or iterations >= max_iterations:
            __UpperCamelCase     :Dict			  =		True

        __UpperCamelCase     :List[Any]			  =		lambda_

    if is_complex:
        __UpperCamelCase     :Tuple			  =		np.real(lambda_	)

    return lambda_, vector



def lowerCamelCase  (   ):
    '''simple docstring'''







    __UpperCamelCase     :int			  =		np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]	)
    __UpperCamelCase     :Optional[Any]			  =		np.array([41, 4, 20]	)
    __UpperCamelCase     :Any			  =		real_input_matrix.astype(np.complexaaa	)
    __UpperCamelCase     :Dict			  =		np.triu(1j * complex_input_matrix  ,			1	)
    complex_input_matrix += imag_matrix
    complex_input_matrix += -1 * imag_matrix.T
    __UpperCamelCase     :Optional[int]			  =		np.array([41, 4, 20]	).astype(np.complexaaa	)

    for problem_type in ["real", "complex"]:
        if problem_type == "real":
            __UpperCamelCase     :Any			  =		real_input_matrix
            __UpperCamelCase     :int			  =		real_vector
        elif problem_type == "complex":
            __UpperCamelCase     :Tuple			  =		complex_input_matrix
            __UpperCamelCase     :Optional[Any]			  =		complex_vector

        # Our implementation.
        __UpperCamelCase  ,       __UpperCamelCase     :Dict			  =		power_iteration(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)

        # Numpy implementation.

        # Get eigenvalues and eigenvectors using built-in numpy
        # eigh (eigh used for symmetric or hermetian matrices).
        __UpperCamelCase  ,       __UpperCamelCase     :List[Any]			  =		np.linalg.eigh(SCREAMING_SNAKE_CASE	)
        # Last eigenvalue is the maximum one.
        __UpperCamelCase     :List[Any]			  =		eigen_values[-1]
        # Last column in this matrix is eigenvector corresponding to largest eigenvalue.
        __UpperCamelCase     :str			  =		eigen_vectors[:, -1]

        # Check our implementation and numpy gives close answers.
        assert np.abs(eigen_value - eigen_value_max	) <= 1e-6
        # Take absolute values element wise of each eigenvector.
        # as they are only unique to a minus sign.
        assert np.linalg.norm(np.abs(SCREAMING_SNAKE_CASE	) - np.abs(SCREAMING_SNAKE_CASE	)	) <= 1e-6


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    test_power_iteration()





