'''simple docstring'''


import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


snake_case__					:      Tuple				      =  logging.getLogger(__name__)


snake_case__					:      Optional[Any]				      =  list(MODEL_WITH_LM_HEAD_MAPPING.keys())
snake_case__					:      int				      =  tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class 					__SCREAMING_SNAKE_CASE						:







  '''simple docstring'''






  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={
          '''help''': (
              '''The model checkpoint for weights initialization. Leave None if you want to train a model from'''
              ''' scratch.'''
          )
      }						,     )
  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(lowerCamelCase_	)}						,     )
  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}	)
  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}	)
  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}						,     )







@dataclass
class 					__SCREAMING_SNAKE_CASE						:







  '''simple docstring'''






  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''The input training data file (a text file).'''}	)
  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={
          '''help''': (
              '''The input training data files (multiple files in glob format). '''
              '''Very often splitting large files to smaller files can prevent tokenizer going out of memory'''
          )
      }						,     )
  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}						,     )
  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''}						,     )
  lowerCamelCase_		:Optional[str]						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''}						,     )
  lowerCamelCase_		:bool						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''}						,     )

  lowerCamelCase_		:bool						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''}	)
  lowerCamelCase_		:bool						   =		field(default=lowerCamelCase_						,     metadata={'''help''': '''Whether ot not to use whole word mask.'''}	)
  lowerCamelCase_		:float						   =		field(
      default=0.15						,     metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''}	)
  lowerCamelCase_		:float						   =		field(
      default=1 / 6						,     metadata={
          '''help''': (
              '''Ratio of length of a span of masked tokens to surrounding context length for permutation language'''
              ''' modeling.'''
          )
      }						,     )
  lowerCamelCase_		:int						   =		field(
      default=5						,     metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''}	)

  lowerCamelCase_		:int						   =		field(
      default=-1						,     metadata={
          '''help''': (
              '''Optional input sequence length after tokenization.'''
              '''The training dataset will be truncated in block of this size for training.'''
              '''Default to the model max input length for single sentence inputs (take into account special tokens).'''
          )
      }						,     )
  lowerCamelCase_		:bool						   =		field(
      default=lowerCamelCase_						,     metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}	)







def  _lowerCamelCase   (				lowerCamelCase_ :							DataTrainingArguments     ,					lowerCamelCase_ :							PreTrainedTokenizer     ,					lowerCamelCase_ :							bool = False     ,					lowerCamelCase_ :							Optional[str] = None     ,					):



     """simple docstring"""





     def _dataset(lowerCamelCase_ :							Any     ,					lowerCamelCase_ :							Union[str, Any]=None       ):
          if args.line_by_line:
               if ref_path is not None:
                    if not args.whole_word_mask or not args.mlm:
                         raise ValueError('You need to set world whole masking and mlm to True for Chinese Whole Word Mask'       )
                    return LineByLineWithRefDataset(
                        tokenizer=lowerCamelCase_     ,					file_path=lowerCamelCase_     ,					block_size=args.block_size     ,					ref_path=lowerCamelCase_     ,					)

               return LineByLineTextDataset(tokenizer=lowerCamelCase_     ,					file_path=lowerCamelCase_     ,					block_size=args.block_size       )
          else:
               return TextDataset(
                   tokenizer=lowerCamelCase_     ,					file_path=lowerCamelCase_     ,					block_size=args.block_size     ,					overwrite_cache=args.overwrite_cache     ,					cache_dir=lowerCamelCase_     ,					)

     if evaluate:
          return _dataset(args.eval_data_file     ,					args.eval_ref_file       )
     elif args.train_data_files:
          return ConcatDataset([_dataset(lowerCamelCase_       ) for f in glob(args.train_data_files       )]       )
     else:
          return _dataset(args.train_data_file     ,					args.train_ref_file       )


def  _lowerCamelCase   (				):



     """simple docstring"""





     UpperCAmelCase_							:       Union[str, Any]       =				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
     UpperCAmelCase_       ,      UpperCAmelCase_       ,      UpperCAmelCase_							:       int       =				parser.parse_args_into_dataclasses()

     if data_args.eval_data_file is None and training_args.do_eval:
          raise ValueError(
              'Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '
              'or remove the --do_eval argument.'       )
     if (
         os.path.exists(training_args.output_dir       )
         and os.listdir(training_args.output_dir       )
         and training_args.do_train
         and not training_args.overwrite_output_dir
     ):
          raise ValueError(
              F'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
              ' --overwrite_output_dir to overcome.'       )

     # Setup logging
     logging.basicConfig(
         format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'     ,					datefmt='%m/%d/%Y %H:%M:%S'     ,					level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN     ,					)
     logger.warning(
         'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'     ,					training_args.local_rank     ,					training_args.device     ,					training_args.n_gpu     ,					bool(training_args.local_rank != -1       )     ,					training_args.fpaa     ,					)
     # Set the verbosity to info of the Transformers logger (on main process only):
     if is_main_process(training_args.local_rank       ):
          transformers.utils.logging.set_verbosity_info()
          transformers.utils.logging.enable_default_handler()
          transformers.utils.logging.enable_explicit_format()
     logger.info('Training/evaluation parameters %s'     ,					lowerCamelCase_       )

     # Set seed
     set_seed(training_args.seed       )

     # Load pretrained model and tokenizer
     #
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.

     if model_args.config_name:
          UpperCAmelCase_							:       int       =				AutoConfig.from_pretrained(model_args.config_name     ,					cache_dir=model_args.cache_dir       )
     elif model_args.model_name_or_path:
          UpperCAmelCase_							:       int       =				AutoConfig.from_pretrained(model_args.model_name_or_path     ,					cache_dir=model_args.cache_dir       )
     else:
          UpperCAmelCase_							:       int       =				CONFIG_MAPPING[model_args.model_type]()
          logger.warning('You are instantiating a new config instance from scratch.'       )

     if model_args.tokenizer_name:
          UpperCAmelCase_							:       str       =				AutoTokenizer.from_pretrained(model_args.tokenizer_name     ,					cache_dir=model_args.cache_dir       )
     elif model_args.model_name_or_path:
          UpperCAmelCase_							:       Dict       =				AutoTokenizer.from_pretrained(model_args.model_name_or_path     ,					cache_dir=model_args.cache_dir       )
     else:
          raise ValueError(
              'You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'
              ' script, save it,and load it from here, using --tokenizer_name'       )

     if model_args.model_name_or_path:
          UpperCAmelCase_							:       Dict       =				AutoModelWithLMHead.from_pretrained(
              model_args.model_name_or_path     ,					from_tf=bool('.ckpt' in model_args.model_name_or_path       )     ,					config=lowerCamelCase_     ,					cache_dir=model_args.cache_dir     ,					)
     else:
          logger.info('Training new model from scratch'       )
          UpperCAmelCase_							:       Optional[int]       =				AutoModelWithLMHead.from_config(lowerCamelCase_       )

     model.resize_token_embeddings(len(lowerCamelCase_       )       )

     if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
          raise ValueError(
              'BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'
              '--mlm flag (masked language modeling).'       )

     if data_args.block_size <= 0:
          UpperCAmelCase_							:       Optional[int]       =				tokenizer.max_len
          # Our input block size will be the max possible for the model
     else:
          UpperCAmelCase_							:       int       =				min(data_args.block_size     ,					tokenizer.max_len       )

     # Get datasets

     UpperCAmelCase_							:       Optional[Any]       =				(
         get_dataset(lowerCamelCase_     ,					tokenizer=lowerCamelCase_     ,					cache_dir=model_args.cache_dir       ) if training_args.do_train else None
     )
     UpperCAmelCase_							:       List[str]       =				(
         get_dataset(lowerCamelCase_     ,					tokenizer=lowerCamelCase_     ,					evaluate=lowerCamelCase_     ,					cache_dir=model_args.cache_dir       )
         if training_args.do_eval
         else None
     )
     if config.model_type == "xlnet":
          UpperCAmelCase_							:       int       =				DataCollatorForPermutationLanguageModeling(
              tokenizer=lowerCamelCase_     ,					plm_probability=data_args.plm_probability     ,					max_span_length=data_args.max_span_length     ,					)
     else:
          if data_args.mlm and data_args.whole_word_mask:
               UpperCAmelCase_							:       Union[str, Any]       =				DataCollatorForWholeWordMask(
                   tokenizer=lowerCamelCase_     ,					mlm_probability=data_args.mlm_probability       )
          else:
               UpperCAmelCase_							:       Dict       =				DataCollatorForLanguageModeling(
                   tokenizer=lowerCamelCase_     ,					mlm=data_args.mlm     ,					mlm_probability=data_args.mlm_probability       )

    # Initialize our Trainer
     UpperCAmelCase_							:       str       =				Trainer(
         model=lowerCamelCase_     ,					args=lowerCamelCase_     ,					data_collator=lowerCamelCase_     ,					train_dataset=lowerCamelCase_     ,					eval_dataset=lowerCamelCase_     ,					prediction_loss_only=lowerCamelCase_     ,					)

     # Training
     if training_args.do_train:
          UpperCAmelCase_							:       Optional[Any]       =				(
              model_args.model_name_or_path
              if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path       )
              else None
          )
          trainer.train(model_path=lowerCamelCase_       )
          trainer.save_model()
          # For convenience, we also re-save the tokenizer to the same directory,
          # so that you can share your model easily on huggingface.co/models =)
          if trainer.is_world_master():
               tokenizer.save_pretrained(training_args.output_dir       )

    # Evaluation
     UpperCAmelCase_							:       Dict       =				{}
     if training_args.do_eval:
          logger.info('*** Evaluate ***'       )

          UpperCAmelCase_							:       str       =				trainer.evaluate()

          UpperCAmelCase_							:       Dict       =				math.exp(eval_output['eval_loss']       )
          UpperCAmelCase_							:       str       =				{'perplexity': perplexity}

          UpperCAmelCase_							:       Tuple       =				os.path.join(training_args.output_dir     ,					'eval_results_lm.txt'       )
          if trainer.is_world_master():
               with open(lowerCamelCase_     ,					'w'       ) as writer:
                    logger.info('***** Eval results *****'       )
                    for key in sorted(result.keys()       ):
                         logger.info('  %s = %s'     ,					lowerCamelCase_     ,					str(result[key]       )       )
                         writer.write('%s = %s\n' % (key, str(result[key]       ))       )

          results.update(lowerCamelCase_       )

     return results


def  _lowerCamelCase   (				lowerCamelCase_ :							Dict       ):



     """simple docstring"""





     main()


if __name__ == "__main__":
 main()







'''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 					__SCREAMING_SNAKE_CASE						:







  '''simple docstring'''






  def __init__(			self				,		snake_case_				,		snake_case_=1_3				,		snake_case_=7				,		snake_case_=True				,		snake_case_=True				,		snake_case_=False				,		snake_case_=True				,		snake_case_=9_9				,		snake_case_=3_2				,		snake_case_=5				,		snake_case_=4				,		snake_case_=3_7				,		snake_case_="gelu"				,		snake_case_=0.1				,		snake_case_=0.1				,		snake_case_=5_1_2				,		snake_case_=1_6				,		snake_case_=2				,		snake_case_=0.02				,		snake_case_=3				,		snake_case_=4				,		snake_case_=None				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       Union[str, Any]       =				parent
       UpperCAmelCase_							:       List[str]       =				batch_size
       UpperCAmelCase_							:       Dict       =				seq_length
       UpperCAmelCase_							:       Any       =				is_training
       UpperCAmelCase_							:       List[Any]       =				use_input_mask
       UpperCAmelCase_							:       Tuple       =				use_token_type_ids
       UpperCAmelCase_							:       Tuple       =				use_labels
       UpperCAmelCase_							:       Dict       =				vocab_size
       UpperCAmelCase_							:       Union[str, Any]       =				hidden_size
       UpperCAmelCase_							:       Optional[Any]       =				num_hidden_layers
       UpperCAmelCase_							:       Union[str, Any]       =				num_attention_heads
       UpperCAmelCase_							:       Optional[int]       =				intermediate_size
       UpperCAmelCase_							:       Dict       =				hidden_act
       UpperCAmelCase_							:       Any       =				hidden_dropout_prob
       UpperCAmelCase_							:       Optional[Any]       =				attention_probs_dropout_prob
       UpperCAmelCase_							:       Optional[int]       =				max_position_embeddings
       UpperCAmelCase_							:       List[Any]       =				type_vocab_size
       UpperCAmelCase_							:       Optional[Any]       =				type_sequence_label_size
       UpperCAmelCase_							:       List[Any]       =				initializer_range
       UpperCAmelCase_							:       List[Any]       =				num_labels
       UpperCAmelCase_							:       Any       =				num_choices
       UpperCAmelCase_							:       List[str]       =				scope


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       List[str]       =				ids_tensor([self.batch_size, self.seq_length]				,		self.vocab_size						)

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

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

       UpperCAmelCase_							:       Tuple       =				None
       UpperCAmelCase_							:       Any       =				None
       UpperCAmelCase_							:       str       =				None
       if self.use_labels:
            UpperCAmelCase_							:       str       =				ids_tensor([self.batch_size]				,		self.type_sequence_label_size						)
            UpperCAmelCase_							:       Optional[int]       =				ids_tensor([self.batch_size, self.seq_length]				,		self.num_labels						)
            UpperCAmelCase_							:       Any       =				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						):




       '''simple docstring'''

       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=snake_case_				,		initializer_range=self.initializer_range				,		use_stable_embedding=snake_case_				,		)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       str       =				OpenLlamaModel(config=snake_case_						)
       model.to(snake_case_						)
       model.eval()
       UpperCAmelCase_							:       str       =				model(snake_case_				,		attention_mask=snake_case_						)
       UpperCAmelCase_							:       Dict       =				model(snake_case_						)
       self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)						)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       Optional[Any]       =				OpenLlamaForCausalLM(config=snake_case_						)
       model.to(snake_case_						)
       model.eval()
       UpperCAmelCase_							:       Union[str, Any]       =				model(snake_case_				,		attention_mask=snake_case_				,		labels=snake_case_						)
       self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.seq_length, self.vocab_size)						)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		snake_case_				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       Optional[Any]       =				True
       UpperCAmelCase_							:       List[Any]       =				True
       UpperCAmelCase_							:       Tuple       =				OpenLlamaForCausalLM(config=snake_case_						)
       model.to(snake_case_						)
       model.eval()

       # first forward pass
       UpperCAmelCase_							:       Tuple       =				model(
           snake_case_				,		attention_mask=snake_case_				,		encoder_hidden_states=snake_case_				,		encoder_attention_mask=snake_case_				,		use_cache=snake_case_				,		)
       UpperCAmelCase_							:       int       =				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_							:       Optional[int]       =				ids_tensor((self.batch_size, 3)				,		vocab_size=2						)

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

       UpperCAmelCase_							:       List[Any]       =				model(
           snake_case_				,		attention_mask=snake_case_				,		encoder_hidden_states=snake_case_				,		encoder_attention_mask=snake_case_				,		output_hidden_states=snake_case_				,		)['hidden_states'][0]
       UpperCAmelCase_							:       List[str]       =				model(
           snake_case_				,		attention_mask=snake_case_				,		encoder_hidden_states=snake_case_				,		encoder_attention_mask=snake_case_				,		past_key_values=snake_case_				,		output_hidden_states=snake_case_				,		)['hidden_states'][0]

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






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       int       =				self.prepare_config_and_inputs()
       (
           (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      (
           UpperCAmelCase_
       )       ,      
       )							:       Tuple       =				config_and_inputs
       UpperCAmelCase_							:       List[Any]       =				{'input_ids': input_ids, 'attention_mask': input_mask}
       return config, inputs_dict







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







  '''simple docstring'''






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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       List[str]       =				OpenLlamaModelTester(self						)
       UpperCAmelCase_							:       List[Any]       =				ConfigTester(self				,		config_class=snake_case_				,		hidden_size=3_7						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       self.config_tester.run_common_tests()


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       Any       =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*snake_case_						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       Optional[int]       =				self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
            UpperCAmelCase_							:       int       =				type
            self.model_tester.create_and_check_model(*snake_case_						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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




       '''simple docstring'''

       pass






  @parameterized.expand([('linear',), ('dynamic',)]						)
  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_       ,      UpperCAmelCase_							:       Optional[Any]       =				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase_							:       int       =				ids_tensor([1, 1_0]				,		config.vocab_size						)
       UpperCAmelCase_							:       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
       UpperCAmelCase_							:       Tuple       =				OpenLlamaModel(snake_case_						)
       original_model.to(snake_case_						)
       original_model.eval()
       UpperCAmelCase_							:       List[str]       =				original_model(snake_case_						).last_hidden_state
       UpperCAmelCase_							:       Any       =				original_model(snake_case_						).last_hidden_state

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

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






