



'''simple docstring'''




import unittest

import numpy as np

from transformers import is_flax_available
from transformers.testing_utils import require_flax

from ..test_modeling_flax_common import ids_tensor


if is_flax_available():
       import jax
       import jax.numpy as jnp

       from transformers.generation import (
           FlaxForcedBOSTokenLogitsProcessor,
           FlaxForcedEOSTokenLogitsProcessor,
           FlaxLogitsProcessorList,
           FlaxMinLengthLogitsProcessor,
           FlaxTemperatureLogitsWarper,
           FlaxTopKLogitsWarper,
           FlaxTopPLogitsWarper,
       )

@require_flax
class     UpperCamelCase_				(							unittest.TestCase    ):





 def 				_lowercase(						self	,	A	,	A					)    ->    str:
        UpperCAmelCase  :	Tuple							  =	jnp.ones((batch_size, length)					) / length
        return scores





 def 				_lowercase(						self					)    ->    List[Any]:
        UpperCAmelCase  :	Dict							  =	None
        UpperCAmelCase  :	int							  =	20

        UpperCAmelCase  :	Tuple							  =	self._get_uniform_logits(batch_size=2	,	length=snake_case_					)

        # tweak scores to not be uniform anymore
        UpperCAmelCase  :	Optional[Any]							  =	scores.at[1, 5].set((1 / length) + 0.1					)  # peak, 1st batch
        UpperCAmelCase  :	Tuple							  =	scores.at[1, 10].set((1 / length) - 0.4					)  # valley, 1st batch

        # compute softmax
        UpperCAmelCase  :	Union[str, Any]							  =	jax.nn.softmax(snake_case_	,	axis=-1					)

        UpperCAmelCase  :	Union[str, Any]							  =	FlaxTemperatureLogitsWarper(temperature=0.5					)
        UpperCAmelCase  :	Optional[int]							  =	FlaxTemperatureLogitsWarper(temperature=1.3					)

        UpperCAmelCase  :	Optional[Any]							  =	jax.nn.softmax(temp_dist_warper_sharper(snake_case_	,	scores.copy()	,	cur_len=snake_case_					)	,	axis=-1					)
        UpperCAmelCase  :	Dict							  =	jax.nn.softmax(temp_dist_warper_smoother(snake_case_	,	scores.copy()	,	cur_len=snake_case_					)	,	axis=-1					)

        # uniform distribution stays uniform
        self.assertTrue(jnp.allclose(probs[0, :]	,	warped_prob_sharp[0, :]	,	atol=1e-3					)					)
        self.assertTrue(jnp.allclose(probs[0, :]	,	warped_prob_smooth[0, :]	,	atol=1e-3					)					)

        # sharp peaks get higher, valleys get lower
        self.assertLess(probs[1, :].max()	,	warped_prob_sharp[1, :].max()					)
        self.assertGreater(probs[1, :].min()	,	warped_prob_sharp[1, :].min()					)

        # smooth peaks get lower, valleys get higher
        self.assertGreater(probs[1, :].max()	,	warped_prob_smooth[1, :].max()					)
        self.assertLess(probs[1, :].min()	,	warped_prob_smooth[1, :].min()					)





 def 				_lowercase(						self					)    ->    Optional[int]:
        UpperCAmelCase  :	List[Any]							  =	None
        UpperCAmelCase  :	Tuple							  =	10
        UpperCAmelCase  :	str							  =	2

        # create ramp distribution
        UpperCAmelCase  :	Any							  =	np.broadcast_to(np.arange(snake_case_					)[None, :]	,	(batch_size, vocab_size)					).copy()
        UpperCAmelCase  :	Tuple							  =	ramp_logits[1:, : vocab_size // 2] + vocab_size

        UpperCAmelCase  :	Union[str, Any]							  =	FlaxTopKLogitsWarper(3					)

        UpperCAmelCase  :	Dict							  =	top_k_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)

        # check that correct tokens are filtered
        self.assertListEqual(jnp.isinf(scores[0]					).tolist()	,	7 * [True] + 3 * [False]					)
        self.assertListEqual(jnp.isinf(scores[1]					).tolist()	,	2 * [True] + 3 * [False] + 5 * [True]					)

        # check special case
        UpperCAmelCase  :	Any							  =	5
        UpperCAmelCase  :	Optional[int]							  =	FlaxTopKLogitsWarper(top_k=1	,	filter_value=0.0	,	min_tokens_to_keep=3					)

        UpperCAmelCase  :	List[str]							  =	np.broadcast_to(np.arange(snake_case_					)[None, :]	,	(batch_size, length)					).copy()
        UpperCAmelCase  :	str							  =	top_k_warp_safety_check(snake_case_	,	snake_case_	,	cur_len=snake_case_					)

        # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
        self.assertListEqual((scores == 0.0).sum(axis=-1					).tolist()	,	[2, 2]					)





 def 				_lowercase(						self					)    ->    Dict:
        UpperCAmelCase  :	Any							  =	None
        UpperCAmelCase  :	Any							  =	10
        UpperCAmelCase  :	str							  =	2

        # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
        UpperCAmelCase  :	List[str]							  =	np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.1_5, 0.3, 0.3, 0.2_5]]					)					)

        UpperCAmelCase  :	Tuple							  =	FlaxTopPLogitsWarper(0.8					)
        UpperCAmelCase  :	Tuple							  =	np.exp(top_p_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)					)

        # dist should be filtered to keep min num values so that sum is >= top_p
        # exp (-inf) => 0
        UpperCAmelCase  :	Any							  =	np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.2_5]]					)
        self.assertTrue(np.allclose(snake_case_	,	snake_case_	,	atol=1e-3					)					)

        # check edge cases with negative and extreme logits
        UpperCAmelCase  :	Optional[int]							  =	np.broadcast_to(np.arange(snake_case_					)[None, :]	,	(batch_size, vocab_size)					).copy() - (
            vocab_size // 2
        )

        # make ramp_logits more extreme
        UpperCAmelCase  :	Dict							  =	ramp_logits[1] * 1_0_0.0

        # make sure at least 2 tokens are kept
        UpperCAmelCase  :	Any							  =	FlaxTopPLogitsWarper(0.9	,	min_tokens_to_keep=2	,	filter_value=0.0					)
        UpperCAmelCase  :	int							  =	top_p_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)

        # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
        self.assertListEqual((filtered_dist != 0.0).sum(axis=-1					).tolist()	,	[3, 2]					)





 def 				_lowercase(						self					)    ->    Optional[int]:
        UpperCAmelCase  :	Any							  =	20
        UpperCAmelCase  :	Dict							  =	4
        UpperCAmelCase  :	Union[str, Any]							  =	0

        UpperCAmelCase  :	Tuple							  =	FlaxMinLengthLogitsProcessor(min_length=10	,	eos_token_id=snake_case_					)

        # check that min length is applied at length 5
        UpperCAmelCase  :	Optional[int]							  =	ids_tensor((batch_size, 20)	,	vocab_size=20					)
        UpperCAmelCase  :	int							  =	5
        UpperCAmelCase  :	int							  =	self._get_uniform_logits(snake_case_	,	snake_case_					)
        UpperCAmelCase  :	Any							  =	min_dist_processor(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()	,	4 * [-float("""inf"""					)]					)

        # check that min length is not applied anymore at length 15
        UpperCAmelCase  :	Optional[int]							  =	self._get_uniform_logits(snake_case_	,	snake_case_					)
        UpperCAmelCase  :	Union[str, Any]							  =	15
        UpperCAmelCase  :	Optional[Any]							  =	min_dist_processor(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        self.assertFalse(jnp.isinf(snake_case_					).any()					)





 def 				_lowercase(						self					)    ->    Optional[Any]:
        UpperCAmelCase  :	int							  =	20
        UpperCAmelCase  :	Dict							  =	4
        UpperCAmelCase  :	Optional[int]							  =	0

        UpperCAmelCase  :	str							  =	FlaxForcedBOSTokenLogitsProcessor(bos_token_id=snake_case_					)

        # check that all scores are -inf except the bos_token_id score
        UpperCAmelCase  :	List[str]							  =	ids_tensor((batch_size, 1)	,	vocab_size=20					)
        UpperCAmelCase  :	Union[str, Any]							  =	1
        UpperCAmelCase  :	Any							  =	self._get_uniform_logits(snake_case_	,	snake_case_					)
        UpperCAmelCase  :	List[Any]							  =	logits_processor(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]					).all()					)
        self.assertListEqual(scores[:, bos_token_id].tolist()	,	4 * [0]					)  # score for bos_token_id shold be zero

        # check that bos_token_id is not forced if current length is greater than 1
        UpperCAmelCase  :	Optional[Any]							  =	3
        UpperCAmelCase  :	Dict							  =	self._get_uniform_logits(snake_case_	,	snake_case_					)
        UpperCAmelCase  :	List[str]							  =	logits_processor(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        self.assertFalse(jnp.isinf(snake_case_					).any()					)





 def 				_lowercase(						self					)    ->    Dict:
        UpperCAmelCase  :	List[Any]							  =	20
        UpperCAmelCase  :	List[str]							  =	4
        UpperCAmelCase  :	Union[str, Any]							  =	0
        UpperCAmelCase  :	Dict							  =	5

        UpperCAmelCase  :	Optional[int]							  =	FlaxForcedEOSTokenLogitsProcessor(max_length=snake_case_	,	eos_token_id=snake_case_					)

        # check that all scores are -inf except the eos_token_id when max_length is reached
        UpperCAmelCase  :	List[str]							  =	ids_tensor((batch_size, 4)	,	vocab_size=20					)
        UpperCAmelCase  :	Union[str, Any]							  =	4
        UpperCAmelCase  :	Optional[Any]							  =	self._get_uniform_logits(snake_case_	,	snake_case_					)
        UpperCAmelCase  :	Optional[Any]							  =	logits_processor(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]					).all()					)
        self.assertListEqual(scores[:, eos_token_id].tolist()	,	4 * [0]					)  # score for eos_token_id should be zero

        # check that eos_token_id is not forced if max_length is not reached
        UpperCAmelCase  :	Union[str, Any]							  =	3
        UpperCAmelCase  :	List[Any]							  =	self._get_uniform_logits(snake_case_	,	snake_case_					)
        UpperCAmelCase  :	int							  =	logits_processor(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        self.assertFalse(jnp.isinf(snake_case_					).any()					)





 def 				_lowercase(						self					)    ->    Dict:
        UpperCAmelCase  :	Any							  =	4
        UpperCAmelCase  :	Any							  =	10
        UpperCAmelCase  :	List[Any]							  =	15
        UpperCAmelCase  :	List[Any]							  =	2
        UpperCAmelCase  :	Dict							  =	1
        UpperCAmelCase  :	Optional[Any]							  =	15

        # dummy input_ids and scores
        UpperCAmelCase  :	Any							  =	ids_tensor((batch_size, sequence_length)	,	snake_case_					)
        UpperCAmelCase  :	int							  =	input_ids.copy()

        UpperCAmelCase  :	Optional[int]							  =	self._get_uniform_logits(snake_case_	,	snake_case_					)
        UpperCAmelCase  :	Tuple							  =	scores.copy()

        # instantiate all dist processors
        UpperCAmelCase  :	Optional[Any]							  =	FlaxTemperatureLogitsWarper(temperature=0.5					)
        UpperCAmelCase  :	Dict							  =	FlaxTopKLogitsWarper(3					)
        UpperCAmelCase  :	Dict							  =	FlaxTopPLogitsWarper(0.8					)

        # instantiate all logits processors
        UpperCAmelCase  :	Dict							  =	FlaxMinLengthLogitsProcessor(min_length=10	,	eos_token_id=snake_case_					)
        UpperCAmelCase  :	Any							  =	FlaxForcedBOSTokenLogitsProcessor(bos_token_id=snake_case_					)
        UpperCAmelCase  :	int							  =	FlaxForcedEOSTokenLogitsProcessor(max_length=snake_case_	,	eos_token_id=snake_case_					)

        UpperCAmelCase  :	Any							  =	10

        # no processor list
        UpperCAmelCase  :	List[str]							  =	temp_dist_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        UpperCAmelCase  :	Tuple							  =	top_k_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        UpperCAmelCase  :	int							  =	top_p_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        UpperCAmelCase  :	Optional[int]							  =	min_dist_proc(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        UpperCAmelCase  :	Union[str, Any]							  =	bos_dist_proc(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
        UpperCAmelCase  :	List[str]							  =	eos_dist_proc(snake_case_	,	snake_case_	,	cur_len=snake_case_					)

        # with processor list
        UpperCAmelCase  :	int							  =	FlaxLogitsProcessorList(
            [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]					)
        UpperCAmelCase  :	Any							  =	processor(snake_case_	,	snake_case_	,	cur_len=snake_case_					)

        # scores should be equal
        self.assertTrue(jnp.allclose(snake_case_	,	snake_case_	,	atol=1e-3					)					)

        # input_ids should never be changed
        self.assertListEqual(input_ids.tolist()	,	input_ids_comp.tolist()					)






 def 				_lowercase(						self					)    ->    List[str]:
        UpperCAmelCase  :	List[Any]							  =	4
        UpperCAmelCase  :	Union[str, Any]							  =	10
        UpperCAmelCase  :	Optional[int]							  =	15
        UpperCAmelCase  :	List[Any]							  =	2
        UpperCAmelCase  :	List[Any]							  =	1
        UpperCAmelCase  :	Optional[Any]							  =	15

        # dummy input_ids and scores
        UpperCAmelCase  :	Any							  =	ids_tensor((batch_size, sequence_length)	,	snake_case_					)
        UpperCAmelCase  :	Dict							  =	input_ids.copy()

        UpperCAmelCase  :	Tuple							  =	self._get_uniform_logits(snake_case_	,	snake_case_					)
        UpperCAmelCase  :	int							  =	scores.copy()

        # instantiate all dist processors
        UpperCAmelCase  :	str							  =	FlaxTemperatureLogitsWarper(temperature=0.5					)
        UpperCAmelCase  :	Optional[Any]							  =	FlaxTopKLogitsWarper(3					)
        UpperCAmelCase  :	Any							  =	FlaxTopPLogitsWarper(0.8					)

        # instantiate all logits processors
        UpperCAmelCase  :	str							  =	FlaxMinLengthLogitsProcessor(min_length=10	,	eos_token_id=snake_case_					)
        UpperCAmelCase  :	str							  =	FlaxForcedBOSTokenLogitsProcessor(bos_token_id=snake_case_					)
        UpperCAmelCase  :	Tuple							  =	FlaxForcedEOSTokenLogitsProcessor(max_length=snake_case_	,	eos_token_id=snake_case_					)

        UpperCAmelCase  :	Dict							  =	10

        # no processor list
        def run_no_processor_list(A	,	A	,	A					):
               UpperCAmelCase  :	Optional[int]							  =	temp_dist_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
               UpperCAmelCase  :	str							  =	top_k_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
               UpperCAmelCase  :	int							  =	top_p_warp(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
               UpperCAmelCase  :	Tuple							  =	min_dist_proc(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
               UpperCAmelCase  :	Optional[Any]							  =	bos_dist_proc(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
               UpperCAmelCase  :	Optional[Any]							  =	eos_dist_proc(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
               return scores

        # with processor list
        def run_processor_list(A	,	A	,	A					):
               UpperCAmelCase  :	int							  =	FlaxLogitsProcessorList(
                   [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]					)
               UpperCAmelCase  :	Optional[int]							  =	processor(snake_case_	,	snake_case_	,	cur_len=snake_case_					)
               return scores

        UpperCAmelCase  :	Tuple							  =	jax.jit(snake_case_					)
        UpperCAmelCase  :	List[str]							  =	jax.jit(snake_case_					)

        UpperCAmelCase  :	int							  =	jitted_run_no_processor_list(snake_case_	,	snake_case_	,	snake_case_					)
        UpperCAmelCase  :	int							  =	jitted_run_processor_list(snake_case_	,	snake_case_	,	snake_case_					)

        # scores should be equal
        self.assertTrue(jnp.allclose(snake_case_	,	snake_case_	,	atol=1e-3					)					)

        # input_ids should never be changed
        self.assertListEqual(input_ids.tolist()	,	input_ids_comp.tolist()					)






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





	def __init__(						self	,	A	,	A=13	,	A=7	,	A=True	,	A=True	,	A=False	,	A=True	,	A=99	,	A=32	,	A=5	,	A=4	,	A=37	,	A="gelu"	,	A=0.1	,	A=0.1	,	A=512	,	A=16	,	A=2	,	A=0.0_2	,	A=3	,	A=4	,	A=None	,	)    ->    Any:
								UpperCAmelCase  :	Optional[int]							  =	parent
								UpperCAmelCase  :	List[Any]							  =	batch_size
								UpperCAmelCase  :	Union[str, Any]							  =	seq_length
								UpperCAmelCase  :	Optional[int]							  =	is_training
								UpperCAmelCase  :	str							  =	use_input_mask
								UpperCAmelCase  :	Optional[int]							  =	use_token_type_ids
								UpperCAmelCase  :	Dict							  =	use_labels
								UpperCAmelCase  :	str							  =	vocab_size
								UpperCAmelCase  :	Optional[int]							  =	hidden_size
								UpperCAmelCase  :	str							  =	num_hidden_layers
								UpperCAmelCase  :	Any							  =	num_attention_heads
								UpperCAmelCase  :	Union[str, Any]							  =	intermediate_size
								UpperCAmelCase  :	str							  =	hidden_act
								UpperCAmelCase  :	Any							  =	hidden_dropout_prob
								UpperCAmelCase  :	str							  =	attention_probs_dropout_prob
								UpperCAmelCase  :	Tuple							  =	max_position_embeddings
								UpperCAmelCase  :	Optional[Any]							  =	type_vocab_size
								UpperCAmelCase  :	Optional[Any]							  =	type_sequence_label_size
								UpperCAmelCase  :	str							  =	initializer_range
								UpperCAmelCase  :	List[Any]							  =	num_labels
								UpperCAmelCase  :	Dict							  =	num_choices
								UpperCAmelCase  :	Tuple							  =	scope





	def 				_lowercase(						self					)    ->    Dict:
								UpperCAmelCase  :	Dict							  =	ids_tensor([self.batch_size, self.seq_length]	,	self.vocab_size					)

								UpperCAmelCase  :	Optional[Any]							  =	None
								if self.use_input_mask:
															UpperCAmelCase  :	Optional[int]							  =	random_attention_mask([self.batch_size, self.seq_length]					)

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

								UpperCAmelCase  :	Union[str, Any]							  =	None
								UpperCAmelCase  :	Dict							  =	None
								UpperCAmelCase  :	Union[str, Any]							  =	None
								if self.use_labels:
															UpperCAmelCase  :	Optional[Any]							  =	ids_tensor([self.batch_size]	,	self.type_sequence_label_size					)
															UpperCAmelCase  :	List[Any]							  =	ids_tensor([self.batch_size, self.seq_length]	,	self.num_labels					)
															UpperCAmelCase  :	Optional[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 				_lowercase(						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 				_lowercase(						self	,	A	,	A	,	A	,	A	,	A	,	A	,	A					)    ->    str:
								UpperCAmelCase  :	Union[str, Any]							  =	OpenLlamaModel(config=A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	Dict							  =	model(A	,	attention_mask=A					)
								UpperCAmelCase  :	Optional[int]							  =	model(A					)
								self.parent.assertEqual(result.last_hidden_state.shape	,	(self.batch_size, self.seq_length, self.hidden_size)					)





	def 				_lowercase(						self	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	)    ->    List[Any]:
								UpperCAmelCase  :	Optional[int]							  =	True
								UpperCAmelCase  :	Union[str, Any]							  =	OpenLlamaModel(A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	List[Any]							  =	model(
								    A	,	attention_mask=A	,	encoder_hidden_states=A	,	encoder_attention_mask=A	,	)
								UpperCAmelCase  :	str							  =	model(
								    A	,	attention_mask=A	,	encoder_hidden_states=A	,	)
								UpperCAmelCase  :	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 				_lowercase(						self	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	)    ->    int:
								UpperCAmelCase  :	Optional[int]							  =	OpenLlamaForCausalLM(config=A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	Tuple							  =	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	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	)    ->    int:
								UpperCAmelCase  :	Dict							  =	True
								UpperCAmelCase  :	Tuple							  =	True
								UpperCAmelCase  :	str							  =	OpenLlamaForCausalLM(config=A					)
								model.to(A					)
								model.eval()

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

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

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

								UpperCAmelCase  :	List[Any]							  =	model(
								    A	,	attention_mask=A	,	encoder_hidden_states=A	,	encoder_attention_mask=A	,	output_hidden_states=A	,	)["""hidden_states"""][0]
								UpperCAmelCase  :	Optional[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
								UpperCAmelCase  :	str							  =	ids_tensor((1,)	,	output_from_past.shape[-1]					).item()
								UpperCAmelCase  :	Any							  =	output_from_no_past[:, -3:, random_slice_idx].detach()
								UpperCAmelCase  :	Dict							  =	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]:
								UpperCAmelCase  :	Union[str, Any]							  =	self.prepare_config_and_inputs()
								(
								    (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  
								)  :	Tuple							  =	config_and_inputs
								UpperCAmelCase  :	str							  =	{"""input_ids""": input_ids, """attention_mask""": input_mask}
								return config, inputs_dict




@require_torch
class     UpperCamelCase_				(							__magic_name__   ,  __magic_name__   ,  __magic_name__   ,  unittest.TestCase    ):
	lowercase    =				(
	    (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
	)
	lowercase    =				(OpenLlamaForCausalLM,) if is_torch_available() else ()
	lowercase    =				(
	    {
	        'feature-extraction': OpenLlamaModel,
	        'text-classification': OpenLlamaForSequenceClassification,
	        'text-generation': OpenLlamaForCausalLM,
	        'zero-shot': OpenLlamaForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	lowercase    =				False
	lowercase    =				False





	def 				_lowercase(						self					)    ->    Tuple:
								UpperCAmelCase  :	Dict							  =	OpenLlamaModelTester(self					)
								UpperCAmelCase  :	List[str]							  =	ConfigTester(self	,	config_class=A	,	hidden_size=37					)





	def 				_lowercase(						self					)    ->    Optional[Any]:
								self.config_tester.run_common_tests()





	def 				_lowercase(						self					)    ->    int:
								UpperCAmelCase  :	Tuple							  =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A					)





	def 				_lowercase(						self					)    ->    str:
								UpperCAmelCase  :	Any							  =	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(*A					)





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






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

								set_seed(42					)  # Fixed seed at init time so the two models get the same random weights
								UpperCAmelCase  :	Union[str, Any]							  =	{"""type""": scaling_type, """factor""": 1_0.0}
								UpperCAmelCase  :	str							  =	OpenLlamaModel(A					)
								scaled_model.to(A					)
								scaled_model.eval()
								UpperCAmelCase  :	List[str]							  =	scaled_model(A					).last_hidden_state
								UpperCAmelCase  :	Optional[int]							  =	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					)					)

