






"""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:     List[Any]				,		__A:     int				,		__A:     Tuple=13				,		__A:     Union[str, Any]=7				,		__A:     Union[str, Any]=True				,		__A:     Any=True				,		__A:     Dict=False				,		__A:     Optional[int]=True				,		__A:     Dict=99				,		__A:     List[str]=32				,		__A:     Optional[int]=5				,		__A:     str=4				,		__A:     str=37				,		__A:     int="gelu"				,		__A:     Optional[Any]=0.1				,		__A:     Optional[int]=0.1				,		__A:     int=512				,		__A:     str=16				,		__A:     Optional[Any]=2				,		__A:     Union[str, Any]=0.0_2				,		__A:     List[Any]=3				,		__A:     List[str]=4				,		__A:     Any=None				,		):

												'''simple docstring'''

												a__          =  parent
												a__          =  batch_size
												a__          =  seq_length
												a__          =  is_training
												a__          =  use_input_mask
												a__          =  use_token_type_ids
												a__          =  use_labels
												a__          =  vocab_size
												a__          =  hidden_size
												a__          =  num_hidden_layers
												a__          =  num_attention_heads
												a__          =  intermediate_size
												a__          =  hidden_act
												a__          =  hidden_dropout_prob
												a__          =  attention_probs_dropout_prob
												a__          =  max_position_embeddings
												a__          =  type_vocab_size
												a__          =  type_sequence_label_size
												a__          =  initializer_range
												a__          =  num_labels
												a__          =  num_choices
												a__          =  scope




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												a__          =  ids_tensor([self.batch_size, self.seq_length]				,		self.vocab_size    )

												a__          =  None
												if self.use_input_mask:
																	a__          =  random_attention_mask([self.batch_size, self.seq_length]    )

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

												a__          =  None
												a__          =  None
												a__          =  None
												if self.use_labels:
																	a__          =  ids_tensor([self.batch_size]				,		self.type_sequence_label_size    )
																	a__          =  ids_tensor([self.batch_size, self.seq_length]				,		self.num_labels    )
																	a__          =  ids_tensor([self.batch_size]				,		self.num_choices    )

												a__          =  self.get_config()

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




							def  lowercase		(   self:     Dict    ):

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




							def  lowercase		(   self:     List[str]				,		__A:     Tuple				,		__A:     Tuple				,		__A:     List[Any]				,		__A:     str				,		__A:     str				,		__A:     List[Any]				,		__A:     int    ):

												'''simple docstring'''

												a__          =  OpenLlamaModel(config=__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(__A				,		attention_mask=__A    )
												a__          =  model(__A    )
												self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)    )




							def  lowercase		(   self:     Dict				,		__A:     Tuple				,		__A:     str				,		__A:     List[str]				,		__A:     Optional[int]				,		__A:     List[str]				,		__A:     int				,		__A:     List[Any]				,		__A:     Optional[int]				,		__A:     Optional[Any]				,		):

												'''simple docstring'''

												a__          =  True
												a__          =  OpenLlamaModel(__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		encoder_attention_mask=__A				,		)
												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		)
												a__          =  model(__A				,		attention_mask=__A    )
												self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size)    )




							def  lowercase		(   self:     Optional[int]				,		__A:     Any				,		__A:     int				,		__A:     List[Any]				,		__A:     Optional[Any]				,		__A:     Union[str, Any]				,		__A:     Union[str, Any]				,		__A:     Tuple				,		__A:     List[Any]				,		__A:     int				,		):

												'''simple docstring'''

												a__          =  OpenLlamaForCausalLM(config=__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(__A				,		attention_mask=__A				,		labels=__A    )
												self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.seq_length, self.vocab_size)    )




							def  lowercase		(   self:     Optional[int]				,		__A:     str				,		__A:     Tuple				,		__A:     Tuple				,		__A:     List[str]				,		__A:     Any				,		__A:     int				,		__A:     Optional[int]				,		__A:     str				,		__A:     Optional[Any]				,		):

												'''simple docstring'''

												a__          =  True
												a__          =  True
												a__          =  OpenLlamaForCausalLM(config=__A    )
												model.to(__A    )
												model.eval()

												# first forward pass
												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		encoder_attention_mask=__A				,		use_cache=__A				,		)
												a__          =  outputs.past_key_values

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

												# append to next input_ids and
												a__          =  torch.cat([input_ids, next_tokens]				,		dim=-1    )
												a__          =  torch.cat([input_mask, next_mask]				,		dim=-1    )

												a__          =  model(
												    __A				,		attention_mask=__A				,		encoder_hidden_states=__A				,		encoder_attention_mask=__A				,		output_hidden_states=__A				,		)['''hidden_states'''][0]
												a__          =  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__          =  ids_tensor((1,)				,		output_from_past.shape[-1]    ).item()
												a__          =  output_from_no_past[:, -3:, random_slice_idx].detach()
												a__          =  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  lowercase		(   self:     Union[str, Any]    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												(
												    (
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,(
												    a__
												)       ,
												)          =  config_and_inputs
												a__          =  {'''input_ids''': input_ids, '''attention_mask''': input_mask}
												return config, inputs_dict







@require_torch
class        _SCREAMING_SNAKE_CASE						(  __snake_case       , __snake_case       , __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    =(
							    (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
							)
							_SCREAMING_SNAKE_CASE    =(OpenLlamaForCausalLM,) if is_torch_available() else ()
							_SCREAMING_SNAKE_CASE    =(
							    {
							        'feature-extraction': OpenLlamaModel,
							        'text-classification': OpenLlamaForSequenceClassification,
							        'text-generation': OpenLlamaForCausalLM,
							        'zero-shot': OpenLlamaForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							_SCREAMING_SNAKE_CASE    =False
							_SCREAMING_SNAKE_CASE    =False




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  OpenLlamaModelTester(self    )
												a__          =  ConfigTester(self				,		config_class=__A				,		hidden_size=37    )




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												self.config_tester.run_common_tests()




							def  lowercase		(   self:     str    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__A    )




							def  lowercase		(   self:     Union[str, Any]    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												for type in ["absolute", "relative_key", "relative_key_query"]:
																	a__          =  type
																	self.model_tester.create_and_check_model(*__A    )




							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()
												a__          =  3
												a__          =  input_dict['''input_ids''']
												a__          =  input_ids.ne(1    ).to(__A    )
												a__          =  ids_tensor([self.model_tester.batch_size]				,		self.model_tester.type_sequence_label_size    )
												a__          =  OpenLlamaForSequenceClassification(__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(__A				,		attention_mask=__A				,		labels=__A    )
												self.assertEqual(result.logits.shape				,		(self.model_tester.batch_size, self.model_tester.num_labels)    )




							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()
												a__          =  3
												a__          =  '''single_label_classification'''
												a__          =  input_dict['''input_ids''']
												a__          =  input_ids.ne(1    ).to(__A    )
												a__          =  ids_tensor([self.model_tester.batch_size]				,		self.model_tester.type_sequence_label_size    )
												a__          =  OpenLlamaForSequenceClassification(__A    )
												model.to(__A    )
												model.eval()
												a__          =  model(__A				,		attention_mask=__A				,		labels=__A    )
												self.assertEqual(result.logits.shape				,		(self.model_tester.batch_size, self.model_tester.num_labels)    )




							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()
												a__          =  3
												a__          =  '''multi_label_classification'''
												a__          =  input_dict['''input_ids''']
												a__          =  input_ids.ne(1    ).to(__A    )
												a__          =  ids_tensor(
												    [self.model_tester.batch_size, config.num_labels]				,		self.model_tester.type_sequence_label_size    ).to(torch.float    )
												a__          =  OpenLlamaForSequenceClassification(__A    )
												model.to(__A    )
												model.eval()
												a__          =  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  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												pass





							@parameterized.expand([('''linear''',), ('''dynamic''',)]    )
							def  lowercase		(   self:     Any				,		__A:     List[str]    ):

												'''simple docstring'''

												a__       ,a__          =  self.model_tester.prepare_config_and_inputs_for_common()
												a__          =  ids_tensor([1, 10]				,		config.vocab_size    )
												a__          =  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
												a__          =  OpenLlamaModel(__A    )
												original_model.to(__A    )
												original_model.eval()
												a__          =  original_model(__A    ).last_hidden_state
												a__          =  original_model(__A    ).last_hidden_state

												set_seed(42    )  # Fixed seed at init time so the two models get the same random weights
												a__          =  {'''type''': scaling_type, '''factor''': 1_0.0}
												a__          =  OpenLlamaModel(__A    )
												scaled_model.to(__A    )
												scaled_model.eval()
												a__          =  scaled_model(__A    ).last_hidden_state
												a__          =  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    )    )










"""simple docstring"""







from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__a       :	str             = logging.get_logger(__name__)

__a       :	Dict             = {
    'xlm-mlm-en-2048': 'https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json',
    'xlm-mlm-ende-1024': 'https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json',
    'xlm-mlm-enfr-1024': 'https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json',
    'xlm-mlm-enro-1024': 'https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json',
    'xlm-mlm-tlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json',
    'xlm-mlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json',
    'xlm-clm-enfr-1024': 'https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json',
    'xlm-clm-ende-1024': 'https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json',
    'xlm-mlm-17-1280': 'https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json',
    'xlm-mlm-100-1280': 'https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json',
}







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    ='xlm'
							_SCREAMING_SNAKE_CASE    ={
							    'hidden_size': 'emb_dim',
							    'num_attention_heads': 'n_heads',
							    'num_hidden_layers': 'n_layers',
							    'n_words': 'vocab_size',  # For backward compatibility
							}




							def __init__(   self:     Optional[Any]				,		__A:     str=30145				,		__A:     Union[str, Any]=2048				,		__A:     Union[str, Any]=12				,		__A:     List[Any]=16				,		__A:     List[Any]=0.1				,		__A:     int=0.1				,		__A:     str=True				,		__A:     int=False				,		__A:     Optional[int]=False				,		__A:     Union[str, Any]=False				,		__A:     List[Any]=1				,		__A:     Dict=True				,		__A:     List[Any]=512				,		__A:     Optional[int]=2048**-0.5				,		__A:     Tuple=1e-12				,		__A:     Optional[int]=0.0_2				,		__A:     Optional[int]=0				,		__A:     Union[str, Any]=1				,		__A:     List[Any]=2				,		__A:     Union[str, Any]=3				,		__A:     Tuple=5				,		__A:     Tuple=True				,		__A:     Dict="first"				,		__A:     Optional[int]=True				,		__A:     int=None				,		__A:     Optional[Any]=True				,		__A:     Dict=0.1				,		__A:     Tuple=5				,		__A:     Union[str, Any]=5				,		__A:     Tuple=0				,		__A:     List[str]=0				,		__A:     int=2				,		__A:     Optional[int]=0				,		**__A:     Union[str, Any]				,		):

												'''simple docstring'''

												a__          =  vocab_size
												a__          =  emb_dim
												a__          =  n_layers
												a__          =  n_heads
												a__          =  dropout
												a__          =  attention_dropout
												a__          =  gelu_activation
												a__          =  sinusoidal_embeddings
												a__          =  causal
												a__          =  asm
												a__          =  n_langs
												a__          =  use_lang_emb
												a__          =  layer_norm_eps
												a__          =  bos_index
												a__          =  eos_index
												a__          =  pad_index
												a__          =  unk_index
												a__          =  mask_index
												a__          =  is_encoder
												a__          =  max_position_embeddings
												a__          =  embed_init_std
												a__          =  init_std
												a__          =  summary_type
												a__          =  summary_use_proj
												a__          =  summary_activation
												a__          =  summary_proj_to_labels
												a__          =  summary_first_dropout
												a__          =  start_n_top
												a__          =  end_n_top
												a__          =  mask_token_id
												a__          =  lang_id

												if "n_words" in kwargs:
																	a__          =  kwargs['''n_words''']

												super().__init__(pad_token_id=__A				,		bos_token_id=__A				,		**__A    )







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							@property
							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												if self.task == "multiple-choice":
																	a__          =  {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
												else:
																	a__          =  {0: '''batch''', 1: '''sequence'''}
												return OrderedDict(
												    [
												        ('''input_ids''', dynamic_axis),
												        ('''attention_mask''', dynamic_axis),
												        ('''token_type_ids''', dynamic_axis),
												    ]    )


