

import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


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

						from transformers.modeling_flax_pytorch_utils import (
						    convert_pytorch_state_dict_to_flax,
						    load_flax_weights_in_pytorch_model,
						)
						from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel

if is_torch_available():
						import torch



class   __lowercase				:




			"""simple docstring"""







			def __init__( self  :     int   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     List[str]=14   ,						lowerCAmelCase__  :     Dict=7   ,						lowerCAmelCase__  :     Dict=True   ,						lowerCAmelCase__  :     Tuple=True   ,						lowerCAmelCase__  :     Optional[int]=False   ,						lowerCAmelCase__  :     List[str]=True   ,						lowerCAmelCase__  :     List[str]=99   ,						lowerCAmelCase__  :     List[str]=32   ,						lowerCAmelCase__  :     List[str]=4   ,						lowerCAmelCase__  :     Optional[int]=4   ,						lowerCAmelCase__  :     Tuple=4   ,						lowerCAmelCase__  :     Union[str, Any]=37   ,						lowerCAmelCase__  :     Union[str, Any]="gelu"   ,						lowerCAmelCase__  :     Any=0.1   ,						lowerCAmelCase__  :     Optional[Any]=0.1   ,						lowerCAmelCase__  :     Union[str, Any]=512   ,						lowerCAmelCase__  :     Tuple=0.02   ,						):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       parent
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       batch_size
									SCREAMING_SNAKE_CASE_: Dict  		=       seq_length
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       is_training
									SCREAMING_SNAKE_CASE_: List[Any]  		=       use_input_mask
									SCREAMING_SNAKE_CASE_: Tuple  		=       use_token_type_ids
									SCREAMING_SNAKE_CASE_: Any  		=       use_labels
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       vocab_size
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       hidden_size
									SCREAMING_SNAKE_CASE_: int  		=       rotary_dim
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       num_hidden_layers
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       num_attention_heads
									SCREAMING_SNAKE_CASE_: List[Any]  		=       intermediate_size
									SCREAMING_SNAKE_CASE_: List[str]  		=       hidden_act
									SCREAMING_SNAKE_CASE_: Any  		=       hidden_dropout_prob
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       max_position_embeddings
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       initializer_range
									SCREAMING_SNAKE_CASE_: List[str]  		=       None
									SCREAMING_SNAKE_CASE_: Tuple  		=       vocab_size - 1
									SCREAMING_SNAKE_CASE_: Any  		=       vocab_size - 1
									SCREAMING_SNAKE_CASE_: Dict  		=       vocab_size - 1



			def        _SCREAMING_SNAKE_CASE			( self  :     Dict):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ids_tensor([self.batch_size, self.seq_length]   ,						self.vocab_size)

									SCREAMING_SNAKE_CASE_: Any  		=       None
									if self.use_input_mask:
															SCREAMING_SNAKE_CASE_: Tuple  		=       random_attention_mask([self.batch_size, self.seq_length])

									SCREAMING_SNAKE_CASE_: List[Any]  		=       GPTJConfig(
									    vocab_size=self.vocab_size   ,						n_embd=self.hidden_size   ,						n_layer=self.num_hidden_layers   ,						n_head=self.num_attention_heads   ,						n_positions=self.max_position_embeddings   ,						use_cache=lowerCAmelCase__   ,						bos_token_id=self.bos_token_id   ,						eos_token_id=self.eos_token_id   ,						pad_token_id=self.pad_token_id   ,						rotary_dim=self.rotary_dim   ,						)

									return (config, input_ids, input_mask)



			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Any  		=       config_and_inputs
									SCREAMING_SNAKE_CASE_: List[Any]  		=       {"input_ids": input_ids, "attention_mask": attention_mask}
									return config, inputs_dict



			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]   ,						lowerCAmelCase__  :     Optional[int]   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Dict):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       20
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       model_class_name(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       model.init_cache(input_ids.shape[0]   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       jnp.ones((input_ids.shape[0], max_decoder_length)   ,						dtype="i4")

									SCREAMING_SNAKE_CASE_: Optional[int]  		=       jnp.broadcast_to(
									    jnp.arange(input_ids.shape[-1] - 1)[None, :]   ,						(input_ids.shape[0], input_ids.shape[-1] - 1))
									SCREAMING_SNAKE_CASE_: int  		=       model(
									    input_ids[:, :-1]   ,						attention_mask=lowerCAmelCase__   ,						past_key_values=lowerCAmelCase__   ,						position_ids=lowerCAmelCase__   ,						)

									SCREAMING_SNAKE_CASE_: int  		=       jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]   ,						dtype="i4")
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       model(
									    input_ids[:, -1:]   ,						attention_mask=lowerCAmelCase__   ,						past_key_values=outputs_cache.past_key_values   ,						position_ids=lowerCAmelCase__   ,						)

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       model(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: int  		=       np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
									self.parent.assertTrue(diff < 1E-3   ,						msg=F"Max diff is {diff}")




			def        _SCREAMING_SNAKE_CASE			( self  :     str   ,						lowerCAmelCase__  :     Optional[Any]   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     Any   ,						lowerCAmelCase__  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       20
									SCREAMING_SNAKE_CASE_: List[Any]  		=       model_class_name(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: List[Any]  		=       jnp.concatenate(
									    [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))]   ,						axis=-1   ,						)

									SCREAMING_SNAKE_CASE_: Optional[int]  		=       model.init_cache(input_ids.shape[0]   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       jnp.broadcast_to(
									    jnp.arange(input_ids.shape[-1] - 1)[None, :]   ,						(input_ids.shape[0], input_ids.shape[-1] - 1))

									SCREAMING_SNAKE_CASE_: Dict  		=       model(
									    input_ids[:, :-1]   ,						attention_mask=lowerCAmelCase__   ,						past_key_values=lowerCAmelCase__   ,						position_ids=lowerCAmelCase__   ,						)
									SCREAMING_SNAKE_CASE_: List[str]  		=       jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]   ,						dtype="i4")
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       model(
									    input_ids[:, -1:]   ,						past_key_values=outputs_cache.past_key_values   ,						attention_mask=lowerCAmelCase__   ,						position_ids=lowerCAmelCase__   ,						)

									SCREAMING_SNAKE_CASE_: int  		=       model(lowerCAmelCase__   ,						attention_mask=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
									self.parent.assertTrue(diff < 1E-3   ,						msg=F"Max diff is {diff}")







@require_flax
class   __lowercase				( UpperCAmelCase_		,       UpperCAmelCase_		,       unittest.TestCase	):




			"""simple docstring"""







			_UpperCAmelCase   :							int										=     (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else ()
			_UpperCAmelCase   :							Optional[Any]										=     (FlaxGPTJForCausalLM,) if is_flax_available() else ()



			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									SCREAMING_SNAKE_CASE_: Dict  		=       FlaxGPTJModelTester(self)



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									for model_class_name in self.all_model_classes:
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.model_tester.prepare_config_and_inputs()
															self.model_tester.check_use_cache_forward(lowerCAmelCase__   ,						lowerCAmelCase__   ,						lowerCAmelCase__   ,						lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									for model_class_name in self.all_model_classes:
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: int  		=       self.model_tester.prepare_config_and_inputs()
															self.model_tester.check_use_cache_forward_with_attn_mask(
															    lowerCAmelCase__   ,						lowerCAmelCase__   ,						lowerCAmelCase__   ,						lowerCAmelCase__)



			@tooslow
			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									SCREAMING_SNAKE_CASE_: Any  		=       GPTaTokenizer.from_pretrained("gpt2"   ,						pad_token="<|endoftext|>"   ,						padding_side="left")
									SCREAMING_SNAKE_CASE_: Any  		=       tokenizer(["Hello this is a long string", "Hey"]   ,						return_tensors="np"   ,						padding=lowerCAmelCase__   ,						truncation=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Tuple  		=       FlaxGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B")
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       False
									SCREAMING_SNAKE_CASE_: int  		=       model.config.eos_token_id

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       jax.jit(model.generate)

									SCREAMING_SNAKE_CASE_: int  		=       jit_generate(
									    inputs["input_ids"]   ,						attention_mask=inputs["attention_mask"]   ,						pad_token_id=tokenizer.pad_token_id).sequences

									SCREAMING_SNAKE_CASE_: str  		=       tokenizer.batch_decode(lowerCAmelCase__   ,						skip_special_tokens=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       [
									    "Hello this is a long string of text.\n\nI'm trying to get the text of the",
									    "Hey, I'm a little late to the party. I'm going to",
									]

									self.assertListEqual(lowerCAmelCase__   ,						lowerCAmelCase__)



			@is_pt_flax_cross_test
			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[str]  		=       self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															with self.subTest(model_class.__name__):
																					# prepare inputs
																					SCREAMING_SNAKE_CASE_: int  		=       self._prepare_for_class(lowerCAmelCase__   ,						lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_: Any  		=       {k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()}

																					# load corresponding PyTorch class
																					SCREAMING_SNAKE_CASE_: Tuple  		=       model_class.__name__[4:]  # Skip the "Flax" at the beginning
																					SCREAMING_SNAKE_CASE_: Tuple  		=       getattr(lowerCAmelCase__   ,						lowerCAmelCase__)

																					SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: str  		=       pt_inputs["input_ids"].shape
																					SCREAMING_SNAKE_CASE_: Optional[int]  		=       np.random.randint(0   ,						seq_length - 1   ,						size=(batch_size,))
																					for batch_idx, start_index in enumerate(lowerCAmelCase__):
																											SCREAMING_SNAKE_CASE_: Dict  		=       0
																											SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       1
																											SCREAMING_SNAKE_CASE_: Optional[int]  		=       0
																											SCREAMING_SNAKE_CASE_: Optional[int]  		=       1
																					SCREAMING_SNAKE_CASE_: Any  		=       pt_model_class(lowerCAmelCase__).eval()
																					SCREAMING_SNAKE_CASE_: Any  		=       model_class(lowerCAmelCase__   ,						dtype=jnp.floataa)

																					SCREAMING_SNAKE_CASE_: List[Any]  		=       convert_pytorch_state_dict_to_flax(pt_model.state_dict()   ,						lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_: int  		=       fx_state

																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       pt_model(**lowerCAmelCase__).to_tuple()

																					SCREAMING_SNAKE_CASE_: List[Any]  		=       fx_model(**lowerCAmelCase__).to_tuple()
																					self.assertEqual(len(lowerCAmelCase__)   ,						len(lowerCAmelCase__)   ,						"Output lengths differ between Flax and PyTorch")
																					for fx_output, pt_output in zip(lowerCAmelCase__   ,						lowerCAmelCase__):
																											self.assert_almost_equals(fx_output[:, -1]   ,						pt_output[:, -1].numpy()   ,						4E-2)

																					with tempfile.TemporaryDirectory() as tmpdirname:
																											pt_model.save_pretrained(lowerCAmelCase__)
																											SCREAMING_SNAKE_CASE_: List[str]  		=       model_class.from_pretrained(lowerCAmelCase__   ,						from_pt=lowerCAmelCase__)

																					SCREAMING_SNAKE_CASE_: Tuple  		=       fx_model_loaded(**lowerCAmelCase__).to_tuple()
																					self.assertEqual(
																					    len(lowerCAmelCase__)   ,						len(lowerCAmelCase__)   ,						"Output lengths differ between Flax and PyTorch")
																					for fx_output_loaded, pt_output in zip(lowerCAmelCase__   ,						lowerCAmelCase__):
																											self.assert_almost_equals(fx_output_loaded[:, -1]   ,						pt_output[:, -1].numpy()   ,						4E-2)



			@is_pt_flax_cross_test
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Tuple  		=       self.model_tester.prepare_config_and_inputs_for_common()
									for model_class in self.all_model_classes:
															with self.subTest(model_class.__name__):
																					# prepare inputs
																					SCREAMING_SNAKE_CASE_: Any  		=       self._prepare_for_class(lowerCAmelCase__   ,						lowerCAmelCase__)
																					SCREAMING_SNAKE_CASE_: Dict  		=       {k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()}

																					# load corresponding PyTorch class
																					SCREAMING_SNAKE_CASE_: int  		=       model_class.__name__[4:]  # Skip the "Flax" at the beginning
																					SCREAMING_SNAKE_CASE_: Optional[int]  		=       getattr(lowerCAmelCase__   ,						lowerCAmelCase__)

																					SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       pt_model_class(lowerCAmelCase__).eval()
																					SCREAMING_SNAKE_CASE_: Dict  		=       model_class(lowerCAmelCase__   ,						dtype=jnp.floataa)

																					SCREAMING_SNAKE_CASE_: List[str]  		=       load_flax_weights_in_pytorch_model(lowerCAmelCase__   ,						fx_model.params)
																					SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[str]  		=       pt_inputs["input_ids"].shape
																					SCREAMING_SNAKE_CASE_: List[str]  		=       np.random.randint(0   ,						seq_length - 1   ,						size=(batch_size,))
																					for batch_idx, start_index in enumerate(lowerCAmelCase__):
																											SCREAMING_SNAKE_CASE_: Optional[Any]  		=       0
																											SCREAMING_SNAKE_CASE_: List[str]  		=       1
																											SCREAMING_SNAKE_CASE_: Any  		=       0
																											SCREAMING_SNAKE_CASE_: List[str]  		=       1

																					# make sure weights are tied in PyTorch
																					pt_model.tie_weights()

																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_: List[str]  		=       pt_model(**lowerCAmelCase__).to_tuple()

																					SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       fx_model(**lowerCAmelCase__).to_tuple()
																					self.assertEqual(len(lowerCAmelCase__)   ,						len(lowerCAmelCase__)   ,						"Output lengths differ between Flax and PyTorch")
																					for fx_output, pt_output in zip(lowerCAmelCase__   ,						lowerCAmelCase__):
																											self.assert_almost_equals(fx_output[:, -1]   ,						pt_output[:, -1].numpy()   ,						4E-2)

																					with tempfile.TemporaryDirectory() as tmpdirname:
																											fx_model.save_pretrained(lowerCAmelCase__)
																											SCREAMING_SNAKE_CASE_: int  		=       pt_model_class.from_pretrained(lowerCAmelCase__   ,						from_flax=lowerCAmelCase__)

																					with torch.no_grad():
																											SCREAMING_SNAKE_CASE_: Optional[Any]  		=       pt_model_loaded(**lowerCAmelCase__).to_tuple()

																					self.assertEqual(
																					    len(lowerCAmelCase__)   ,						len(lowerCAmelCase__)   ,						"Output lengths differ between Flax and PyTorch")
																					for fx_output, pt_output in zip(lowerCAmelCase__   ,						lowerCAmelCase__):
																											self.assert_almost_equals(fx_output[:, -1]   ,						pt_output[:, -1].numpy()   ,						4E-2)




			@tooslow
			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									for model_class_name in self.all_model_classes:
															SCREAMING_SNAKE_CASE_: Dict  		=       model_class_name.from_pretrained("EleutherAI/gpt-j-6B")
															SCREAMING_SNAKE_CASE_: List[Any]  		=       model(np.ones((1, 1)))
															self.assertIsNotNone(lowerCAmelCase__)









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   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: str  		=       jnp.ones((batch_size, length)) / length
									return scores



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Dict  		=       None
									SCREAMING_SNAKE_CASE_: str  		=       20

									SCREAMING_SNAKE_CASE_: List[Any]  		=       self._get_uniform_logits(batch_size=2   ,						length=lowerCAmelCase__)

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

									# compute softmax
									SCREAMING_SNAKE_CASE_: Dict  		=       jax.nn.softmax(lowerCAmelCase__   ,						axis=-1)

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       FlaxTemperatureLogitsWarper(temperature=0.5)
									SCREAMING_SNAKE_CASE_: List[str]  		=       FlaxTemperatureLogitsWarper(temperature=1.3)

									SCREAMING_SNAKE_CASE_: str  		=       jax.nn.softmax(temp_dist_warper_sharper(lowerCAmelCase__   ,						scores.copy()   ,						cur_len=lowerCAmelCase__)   ,						axis=-1)
									SCREAMING_SNAKE_CASE_: int  		=       jax.nn.softmax(temp_dist_warper_smoother(lowerCAmelCase__   ,						scores.copy()   ,						cur_len=lowerCAmelCase__)   ,						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        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: List[str]  		=       None
									SCREAMING_SNAKE_CASE_: str  		=       10
									SCREAMING_SNAKE_CASE_: Tuple  		=       2

									# create ramp distribution
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       np.broadcast_to(np.arange(lowerCAmelCase__)[None, :]   ,						(batch_size, vocab_size)).copy()
									SCREAMING_SNAKE_CASE_: Dict  		=       ramp_logits[1:, : vocab_size // 2] + vocab_size

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

									SCREAMING_SNAKE_CASE_: Dict  		=       top_k_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)

									# 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
									SCREAMING_SNAKE_CASE_: Any  		=       5
									SCREAMING_SNAKE_CASE_: str  		=       FlaxTopKLogitsWarper(top_k=1   ,						filter_value=0.0   ,						min_tokens_to_keep=3)

									SCREAMING_SNAKE_CASE_: Any  		=       np.broadcast_to(np.arange(lowerCAmelCase__)[None, :]   ,						(batch_size, length)).copy()
									SCREAMING_SNAKE_CASE_: Any  		=       top_k_warp_safety_check(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)

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



			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									SCREAMING_SNAKE_CASE_: Tuple  		=       None
									SCREAMING_SNAKE_CASE_: Dict  		=       10
									SCREAMING_SNAKE_CASE_: Dict  		=       2

									# create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
									SCREAMING_SNAKE_CASE_: Tuple  		=       np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]]))

									SCREAMING_SNAKE_CASE_: int  		=       FlaxTopPLogitsWarper(0.8)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       np.exp(top_p_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__))

									# dist should be filtered to keep min num values so that sum is >= top_p
									# exp (-inf) => 0
									SCREAMING_SNAKE_CASE_: Dict  		=       np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]])
									self.assertTrue(np.allclose(lowerCAmelCase__   ,						lowerCAmelCase__   ,						atol=1E-3))

									# check edge cases with negative and extreme logits
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       np.broadcast_to(np.arange(lowerCAmelCase__)[None, :]   ,						(batch_size, vocab_size)).copy() - (
									    vocab_size // 2
									)

									# make ramp_logits more extreme
									SCREAMING_SNAKE_CASE_: Dict  		=       ramp_logits[1] * 100.0

									# make sure at least 2 tokens are kept
									SCREAMING_SNAKE_CASE_: str  		=       FlaxTopPLogitsWarper(0.9   ,						min_tokens_to_keep=2   ,						filter_value=0.0)
									SCREAMING_SNAKE_CASE_: Any  		=       top_p_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)

									# 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        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									SCREAMING_SNAKE_CASE_: Tuple  		=       20
									SCREAMING_SNAKE_CASE_: List[str]  		=       4
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       0

									SCREAMING_SNAKE_CASE_: str  		=       FlaxMinLengthLogitsProcessor(min_length=10   ,						eos_token_id=lowerCAmelCase__)

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

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



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: int  		=       20
									SCREAMING_SNAKE_CASE_: str  		=       4
									SCREAMING_SNAKE_CASE_: List[Any]  		=       0

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__)

									# check that all scores are -inf except the bos_token_id score
									SCREAMING_SNAKE_CASE_: int  		=       ids_tensor((batch_size, 1)   ,						vocab_size=20)
									SCREAMING_SNAKE_CASE_: List[str]  		=       1
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self._get_uniform_logits(lowerCAmelCase__   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: int  		=       logits_processor(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									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
									SCREAMING_SNAKE_CASE_: List[Any]  		=       3
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self._get_uniform_logits(lowerCAmelCase__   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: int  		=       logits_processor(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									self.assertFalse(jnp.isinf(lowerCAmelCase__).any())



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									SCREAMING_SNAKE_CASE_: Any  		=       20
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       4
									SCREAMING_SNAKE_CASE_: Dict  		=       0
									SCREAMING_SNAKE_CASE_: List[Any]  		=       5

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__   ,						eos_token_id=lowerCAmelCase__)

									# check that all scores are -inf except the eos_token_id when max_length is reached
									SCREAMING_SNAKE_CASE_: List[Any]  		=       ids_tensor((batch_size, 4)   ,						vocab_size=20)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       4
									SCREAMING_SNAKE_CASE_: Dict  		=       self._get_uniform_logits(lowerCAmelCase__   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       logits_processor(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									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
									SCREAMING_SNAKE_CASE_: List[str]  		=       3
									SCREAMING_SNAKE_CASE_: str  		=       self._get_uniform_logits(lowerCAmelCase__   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: int  		=       logits_processor(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									self.assertFalse(jnp.isinf(lowerCAmelCase__).any())



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: int  		=       4
									SCREAMING_SNAKE_CASE_: List[Any]  		=       10
									SCREAMING_SNAKE_CASE_: int  		=       15
									SCREAMING_SNAKE_CASE_: Dict  		=       2
									SCREAMING_SNAKE_CASE_: int  		=       1
									SCREAMING_SNAKE_CASE_: List[Any]  		=       15

									# dummy input_ids and scores
									SCREAMING_SNAKE_CASE_: int  		=       ids_tensor((batch_size, sequence_length)   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: str  		=       input_ids.copy()

									SCREAMING_SNAKE_CASE_: List[Any]  		=       self._get_uniform_logits(lowerCAmelCase__   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       scores.copy()

									# instantiate all dist processors
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       FlaxTemperatureLogitsWarper(temperature=0.5)
									SCREAMING_SNAKE_CASE_: Tuple  		=       FlaxTopKLogitsWarper(3)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       FlaxTopPLogitsWarper(0.8)

									# instantiate all logits processors
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       FlaxMinLengthLogitsProcessor(min_length=10   ,						eos_token_id=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Dict  		=       FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__   ,						eos_token_id=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       10

									# no processor list
									SCREAMING_SNAKE_CASE_: Dict  		=       temp_dist_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Tuple  		=       top_k_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Any  		=       top_p_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: int  		=       min_dist_proc(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       bos_dist_proc(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Tuple  		=       eos_dist_proc(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)

									# with processor list
									SCREAMING_SNAKE_CASE_: str  		=       FlaxLogitsProcessorList(
									    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc])
									SCREAMING_SNAKE_CASE_: Tuple  		=       processor(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)

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

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




			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       4
									SCREAMING_SNAKE_CASE_: int  		=       10
									SCREAMING_SNAKE_CASE_: List[str]  		=       15
									SCREAMING_SNAKE_CASE_: List[Any]  		=       2
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       1
									SCREAMING_SNAKE_CASE_: str  		=       15

									# dummy input_ids and scores
									SCREAMING_SNAKE_CASE_: Tuple  		=       ids_tensor((batch_size, sequence_length)   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       input_ids.copy()

									SCREAMING_SNAKE_CASE_: List[Any]  		=       self._get_uniform_logits(lowerCAmelCase__   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       scores.copy()

									# instantiate all dist processors
									SCREAMING_SNAKE_CASE_: Dict  		=       FlaxTemperatureLogitsWarper(temperature=0.5)
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       FlaxTopKLogitsWarper(3)
									SCREAMING_SNAKE_CASE_: Dict  		=       FlaxTopPLogitsWarper(0.8)

									# instantiate all logits processors
									SCREAMING_SNAKE_CASE_: int  		=       FlaxMinLengthLogitsProcessor(min_length=10   ,						eos_token_id=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__   ,						eos_token_id=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: str  		=       10

									# no processor list
									def run_no_processor_list(lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     Dict):
															SCREAMING_SNAKE_CASE_: Any  		=       temp_dist_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       top_k_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       top_p_warp(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_: List[Any]  		=       min_dist_proc(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       bos_dist_proc(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       eos_dist_proc(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
															return scores

									# with processor list
									def run_processor_list(lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     Union[str, Any]):
															SCREAMING_SNAKE_CASE_: List[str]  		=       FlaxLogitsProcessorList(
															    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc])
															SCREAMING_SNAKE_CASE_: Dict  		=       processor(lowerCAmelCase__   ,						lowerCAmelCase__   ,						cur_len=lowerCAmelCase__)
															return scores

									SCREAMING_SNAKE_CASE_: str  		=       jax.jit(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       jax.jit(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Dict  		=       jitted_run_no_processor_list(lowerCAmelCase__   ,						lowerCAmelCase__   ,						lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       jitted_run_processor_list(lowerCAmelCase__   ,						lowerCAmelCase__   ,						lowerCAmelCase__)

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

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






