


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

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

       def 						UpperCAmelCase(   self      :     Any    ):
            a_    :     int										=    ids_tensor([self.batch_size, self.seq_length]      ,							self.vocab_size    )

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

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

            a_    :     Optional[int]										=    None
            a_    :     Optional[int]										=    None
            a_    :     Tuple										=    None
            if self.use_labels:
                 a_    :     Dict										=    ids_tensor([self.batch_size]      ,							self.type_sequence_label_size    )
                 a_    :     Optional[int]										=    ids_tensor([self.batch_size, self.seq_length]      ,							self.num_labels    )
                 a_    :     Dict										=    ids_tensor([self.batch_size]      ,							self.num_choices    )

            a_    :     Optional[int]										=    self.get_config()

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

       def 						UpperCAmelCase(   self      :     Dict    ):
            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=__a      ,							initializer_range=self.initializer_range      ,							use_stable_embedding=__a      ,							)

       def 						UpperCAmelCase(   self      :     Any      ,							lowerCamelCase_      :     Tuple      ,							lowerCamelCase_      :     List[str]      ,							lowerCamelCase_      :     List[str]      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     Optional[Any]      ,							lowerCamelCase_      :     Any    ):
            a_    :     List[Any]										=    OpenLlamaModel(config=__a    )
            model.to(__a    )
            model.eval()
            a_    :     Dict										=    model(__a      ,							attention_mask=__a    )
            a_    :     Tuple										=    model(__a    )
            self.parent.assertEqual(result.last_hidden_state.shape      ,							(self.batch_size, self.seq_length, self.hidden_size)    )

       def 						UpperCAmelCase(   self      :     Any      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     List[str]      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     Optional[int]      ,							lowerCamelCase_      :     Any      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Optional[Any]      ,							lowerCamelCase_      :     str      ,							):
            a_    :     Optional[Any]										=    True
            a_    :     Dict										=    OpenLlamaModel(__a    )
            model.to(__a    )
            model.eval()
            a_    :     Dict										=    model(
                __a      ,							attention_mask=__a      ,							encoder_hidden_states=__a      ,							encoder_attention_mask=__a      ,							)
            a_    :     List[Any]										=    model(
                __a      ,							attention_mask=__a      ,							encoder_hidden_states=__a      ,							)
            a_    :     List[Any]										=    model(__a      ,							attention_mask=__a    )
            self.parent.assertEqual(result.last_hidden_state.shape      ,							(self.batch_size, self.seq_length, self.hidden_size)    )

       def 						UpperCAmelCase(   self      :     Optional[int]      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     List[Any]      ,							lowerCamelCase_      :     List[str]      ,							lowerCamelCase_      :     Union[str, Any]      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     Dict      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     List[Any]      ,							lowerCamelCase_      :     Optional[int]      ,							):
            a_    :     List[str]										=    OpenLlamaForCausalLM(config=__a    )
            model.to(__a    )
            model.eval()
            a_    :     Any										=    model(__a      ,							attention_mask=__a      ,							labels=__a    )
            self.parent.assertEqual(result.logits.shape      ,							(self.batch_size, self.seq_length, self.vocab_size)    )

       def 						UpperCAmelCase(   self      :     Tuple      ,							lowerCamelCase_      :     Dict      ,							lowerCamelCase_      :     Optional[int]      ,							lowerCamelCase_      :     Any      ,							lowerCamelCase_      :     Optional[Any]      ,							lowerCamelCase_      :     Optional[Any]      ,							lowerCamelCase_      :     Optional[int]      ,							lowerCamelCase_      :     List[str]      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     int      ,							):
            a_    :     str										=    True
            a_    :     int										=    True
            a_    :     Optional[Any]										=    OpenLlamaForCausalLM(config=__a    )
            model.to(__a    )
            model.eval()

            # first forward pass
            a_    :     Dict										=    model(
                __a      ,							attention_mask=__a      ,							encoder_hidden_states=__a      ,							encoder_attention_mask=__a      ,							use_cache=__a      ,							)
            a_    :     List[Any]										=    outputs.past_key_values

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

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

            a_    :     Tuple										=    model(
                __a      ,							attention_mask=__a      ,							encoder_hidden_states=__a      ,							encoder_attention_mask=__a      ,							output_hidden_states=__a      ,							)["hidden_states"][0]
            a_    :     List[Any]										=    model(
                __a      ,							attention_mask=__a      ,							encoder_hidden_states=__a      ,							encoder_attention_mask=__a      ,							past_key_values=__a      ,							output_hidden_states=__a      ,							)["hidden_states"][0]

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

       def 						UpperCAmelCase(   self      :     Union[str, Any]    ):
            a_    :     Dict										=    self.prepare_config_and_inputs()
            (
                a_  
            )    :     List[Any]										=    config_and_inputs
            a_    :     Optional[int]										=    {"input_ids": input_ids, "attention_mask": input_mask}
            return config, inputs_dict


@require_torch
class   a__	(						_UpperCamelCase						,       _UpperCamelCase						,       _UpperCamelCase						,       unittest.TestCase    ):
       lowerCamelCase__:     List[str]							    =     (
           (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
       )
       lowerCamelCase__:     Dict							    =     (OpenLlamaForCausalLM,) if is_torch_available() else ()
       lowerCamelCase__:     int							    =     (
           {
               "feature-extraction": OpenLlamaModel,
               "text-classification": OpenLlamaForSequenceClassification,
               "text-generation": OpenLlamaForCausalLM,
               "zero-shot": OpenLlamaForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       lowerCamelCase__:     Dict							    =     False
       lowerCamelCase__:     List[str]							    =     False

       def 						UpperCAmelCase(   self      :     Any    ):
            a_    :     List[Any]										=    OpenLlamaModelTester(self    )
            a_    :     Optional[Any]										=    ConfigTester(self      ,							config_class=__a      ,							hidden_size=3_7    )

       def 						UpperCAmelCase(   self      :     List[Any]    ):
            self.config_tester.run_common_tests()

       def 						UpperCAmelCase(   self      :     Union[str, Any]    ):
            a_    :     Union[str, Any]										=    self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__a    )

       def 						UpperCAmelCase(   self      :     List[Any]    ):
            a_    :     List[str]										=    self.model_tester.prepare_config_and_inputs()
            for type in ["absolute", "relative_key", "relative_key_query"]:
                 a_    :     Any										=    type
                 self.model_tester.create_and_check_model(*__a    )

       def 						UpperCAmelCase(   self      :     Dict    ):
            a_    :     List[str]										=    self.model_tester.prepare_config_and_inputs_for_common()
            a_    :     Optional[int]										=    3
            a_    :     Any										=    input_dict["input_ids"]
            a_    :     Dict										=    input_ids.ne(1    ).to(__a    )
            a_    :     Tuple										=    ids_tensor([self.model_tester.batch_size]      ,							self.model_tester.type_sequence_label_size    )
            a_    :     List[str]										=    OpenLlamaForSequenceClassification(__a    )
            model.to(__a    )
            model.eval()
            a_    :     List[str]										=    model(__a      ,							attention_mask=__a      ,							labels=__a    )
            self.assertEqual(result.logits.shape      ,							(self.model_tester.batch_size, self.model_tester.num_labels)    )

       def 						UpperCAmelCase(   self      :     Union[str, Any]    ):
            a_    :     str										=    self.model_tester.prepare_config_and_inputs_for_common()
            a_    :     Optional[Any]										=    3
            a_    :     Optional[Any]										=    "single_label_classification"
            a_    :     Any										=    input_dict["input_ids"]
            a_    :     List[str]										=    input_ids.ne(1    ).to(__a    )
            a_    :     Any										=    ids_tensor([self.model_tester.batch_size]      ,							self.model_tester.type_sequence_label_size    )
            a_    :     Dict										=    OpenLlamaForSequenceClassification(__a    )
            model.to(__a    )
            model.eval()
            a_    :     int										=    model(__a      ,							attention_mask=__a      ,							labels=__a    )
            self.assertEqual(result.logits.shape      ,							(self.model_tester.batch_size, self.model_tester.num_labels)    )

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

       @parameterized.expand([("""linear""",), ("""dynamic""",)]    )
       def 						UpperCAmelCase(   self      :     Tuple      ,							lowerCamelCase_      :     List[Any]    ):
            a_    :     List[str]										=    self.model_tester.prepare_config_and_inputs_for_common()
            a_    :     Optional[int]										=    ids_tensor([1, 1_0]      ,							config.vocab_size    )
            a_    :     Tuple										=    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
            a_    :     List[Any]										=    OpenLlamaModel(__a    )
            original_model.to(__a    )
            original_model.eval()
            a_    :     List[Any]										=    original_model(__a    ).last_hidden_state
            a_    :     Dict										=    original_model(__a    ).last_hidden_state

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

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







from datetime import datetime as dt
import os

from github import Github


__lowerCamelCase        =     [
    '''good first issue''',
    '''good second issue''',
    '''good difficult issue''',
    '''feature request''',
    '''new model''',
    '''wip''',
]



def  _a			(						):
     a_    :     List[str]										=    Github(os.environ["""GITHUB_TOKEN"""] )
     a_    :     str										=    g.get_repo("""huggingface/transformers""" )
     a_    :     List[str]										=    repo.get_issues(state="""open""" )

     for issue in open_issues:
          a_    :     Optional[Any]										=    sorted([comment for comment in issue.get_comments()]  ,  key=lambda __UpperCamelCase : i.created_at  ,  reverse=__UpperCamelCase )
          a_    :     List[Any]										=    comments[0] if len(__UpperCamelCase ) > 0 else None
          if (
              last_comment is not None
              and last_comment.user.login == "github-actions[bot]"
              and (dt.utcnow() - issue.updated_at).days > 7
              and (dt.utcnow() - issue.created_at).days >= 3_0
              and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
          ):
               # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
               issue.edit(state="""closed""" )
          elif (
              (dt.utcnow() - issue.updated_at).days > 2_3
              and (dt.utcnow() - issue.created_at).days >= 3_0
              and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
          ):
               # print(f"Would add stale comment to {issue.number}")
               issue.create_comment(
                   """This issue has been automatically marked as stale because it has not had """
                   """recent activity. If you think this still needs to be addressed """
                   """please comment on this thread.\n\nPlease note that issues that do not follow the """
                   """[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) """
                   """are likely to be ignored.""" )


if __name__ == "__main__":
       main()



