

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
						from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import ViTImageProcessor



class   __lowercase				:




			"""simple docstring"""







			def __init__( self  :     Any   ,						lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     Any=13   ,						lowerCAmelCase__  :     Tuple=30   ,						lowerCAmelCase__  :     List[str]=2   ,						lowerCAmelCase__  :     int=3   ,						lowerCAmelCase__  :     Optional[int]=True   ,						lowerCAmelCase__  :     List[str]=True   ,						lowerCAmelCase__  :     str=32   ,						lowerCAmelCase__  :     Any=5   ,						lowerCAmelCase__  :     str=4   ,						lowerCAmelCase__  :     int=37   ,						lowerCAmelCase__  :     Optional[Any]="gelu"   ,						lowerCAmelCase__  :     Optional[int]=0.1   ,						lowerCAmelCase__  :     Dict=0.1   ,						lowerCAmelCase__  :     Tuple=10   ,						lowerCAmelCase__  :     Optional[Any]=0.02   ,						lowerCAmelCase__  :     List[str]=None   ,						lowerCAmelCase__  :     Union[str, Any]=2   ,						):
									SCREAMING_SNAKE_CASE_: str  		=       parent
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       batch_size
									SCREAMING_SNAKE_CASE_: str  		=       image_size
									SCREAMING_SNAKE_CASE_: Tuple  		=       patch_size
									SCREAMING_SNAKE_CASE_: int  		=       num_channels
									SCREAMING_SNAKE_CASE_: List[str]  		=       is_training
									SCREAMING_SNAKE_CASE_: str  		=       use_labels
									SCREAMING_SNAKE_CASE_: int  		=       hidden_size
									SCREAMING_SNAKE_CASE_: List[Any]  		=       num_hidden_layers
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       num_attention_heads
									SCREAMING_SNAKE_CASE_: Any  		=       intermediate_size
									SCREAMING_SNAKE_CASE_: str  		=       hidden_act
									SCREAMING_SNAKE_CASE_: str  		=       hidden_dropout_prob
									SCREAMING_SNAKE_CASE_: List[str]  		=       attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE_: int  		=       type_sequence_label_size
									SCREAMING_SNAKE_CASE_: Dict  		=       initializer_range
									SCREAMING_SNAKE_CASE_: Dict  		=       scope
									SCREAMING_SNAKE_CASE_: Dict  		=       encoder_stride

									# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       (image_size // patch_size) ** 2
									SCREAMING_SNAKE_CASE_: Dict  		=       num_patches + 1



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

									SCREAMING_SNAKE_CASE_: str  		=       None
									if self.use_labels:
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ids_tensor([self.batch_size]   ,						self.type_sequence_label_size)

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.get_config()

									return config, pixel_values, labels



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									return ViTConfig(
									    image_size=self.image_size   ,						patch_size=self.patch_size   ,						num_channels=self.num_channels   ,						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   ,						is_decoder=lowerCAmelCase__   ,						initializer_range=self.initializer_range   ,						encoder_stride=self.encoder_stride   ,						)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Tuple):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ViTModel(config=lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       model(lowerCAmelCase__)
									self.parent.assertEqual(result.last_hidden_state.shape   ,						(self.batch_size, self.seq_length, self.hidden_size))



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]   ,						lowerCAmelCase__  :     Optional[Any]   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     Dict):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       ViTForMaskedImageModeling(config=lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_: str  		=       model(lowerCAmelCase__)
									self.parent.assertEqual(
									    result.reconstruction.shape   ,						(self.batch_size, self.num_channels, self.image_size, self.image_size))

									# test greyscale images
									SCREAMING_SNAKE_CASE_: Dict  		=       1
									SCREAMING_SNAKE_CASE_: List[str]  		=       ViTForMaskedImageModeling(lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()

									SCREAMING_SNAKE_CASE_: List[str]  		=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
									SCREAMING_SNAKE_CASE_: str  		=       model(lowerCAmelCase__)
									self.parent.assertEqual(result.reconstruction.shape   ,						(self.batch_size, 1, self.image_size, self.image_size))



			def        _SCREAMING_SNAKE_CASE			( self  :     Any   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.type_sequence_label_size
									SCREAMING_SNAKE_CASE_: List[str]  		=       ViTForImageClassification(lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_: Any  		=       model(lowerCAmelCase__   ,						labels=lowerCAmelCase__)
									self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.type_sequence_label_size))

									# test greyscale images
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       1
									SCREAMING_SNAKE_CASE_: List[str]  		=       ViTForImageClassification(lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
									SCREAMING_SNAKE_CASE_: Dict  		=       model(lowerCAmelCase__)
									self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.type_sequence_label_size))




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







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




			"""simple docstring"""







			_UpperCAmelCase   :							List[Any]										=     (
			    (
			        ViTModel,
			        ViTForImageClassification,
			        ViTForMaskedImageModeling,
			    )
			    if is_torch_available()
			    else ()
			)
			_UpperCAmelCase   :							Tuple										=     (
			    {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
			    if is_torch_available()
			    else {}
			)
			_UpperCAmelCase   :							List[str]										=     True

			_UpperCAmelCase   :							List[Any]										=     False
			_UpperCAmelCase   :							Optional[Any]										=     False
			_UpperCAmelCase   :							Tuple										=     False



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: List[str]  		=       ViTModelTester(self)
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ConfigTester(self   ,						config_class=lowerCAmelCase__   ,						has_text_modality=lowerCAmelCase__   ,						hidden_size=37)



			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									self.config_tester.run_common_tests()



			@unittest.skip(reason="ViT does not use inputs_embeds")
			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									pass



			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															SCREAMING_SNAKE_CASE_: Dict  		=       model_class(lowerCAmelCase__)
															self.assertIsInstance(model.get_input_embeddings()   ,						(nn.Module))
															SCREAMING_SNAKE_CASE_: List[Any]  		=       model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowerCAmelCase__   ,						nn.Linear))



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															SCREAMING_SNAKE_CASE_: List[Any]  		=       model_class(lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_: int  		=       inspect.signature(model.forward)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															SCREAMING_SNAKE_CASE_: Optional[Any]  		=       [*signature.parameters.keys()]

															SCREAMING_SNAKE_CASE_: Optional[int]  		=       ["pixel_values"]
															self.assertListEqual(arg_names[:1]   ,						lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									SCREAMING_SNAKE_CASE_: int  		=       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__)




			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ViTModel.from_pretrained(lowerCAmelCase__)
															self.assertIsNotNone(lowerCAmelCase__)







def 			A_      (    ):
						SCREAMING_SNAKE_CASE_: List[Any]  		=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
						return image



@require_torch
@require_vision
class   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			@cached_property
			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224") if is_vision_available() else None



			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: int  		=       ViTForImageClassification.from_pretrained("google/vit-base-patch16-224").to(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.default_image_processor
									SCREAMING_SNAKE_CASE_: str  		=       prepare_img()
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       image_processor(images=lowerCAmelCase__   ,						return_tensors="pt").to(lowerCAmelCase__)

									# forward pass
									with torch.no_grad():
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       model(**lowerCAmelCase__)

									# verify the logits
									SCREAMING_SNAKE_CASE_: Any  		=       torch.Size((1, 1000))
									self.assertEqual(outputs.logits.shape   ,						lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: List[Any]  		=       torch.tensor([-0.2744, 0.8215, -0.0836]).to(lowerCAmelCase__)

									self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,						lowerCAmelCase__   ,						atol=1E-4))



			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									# ViT models have an `interpolate_pos_encoding` argument in their forward method,
									# allowing to interpolate the pre-trained position embeddings in order to use
									# the model on higher resolutions. The DINO model by Facebook AI leverages this
									# to visualize self-attention on higher resolution images.
									SCREAMING_SNAKE_CASE_: str  		=       ViTModel.from_pretrained("facebook/dino-vits8").to(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: List[Any]  		=       ViTImageProcessor.from_pretrained("facebook/dino-vits8"   ,						size=480)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       prepare_img()
									SCREAMING_SNAKE_CASE_: List[Any]  		=       image_processor(images=lowerCAmelCase__   ,						return_tensors="pt")
									SCREAMING_SNAKE_CASE_: int  		=       inputs.pixel_values.to(lowerCAmelCase__)

									# forward pass
									with torch.no_grad():
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       model(lowerCAmelCase__   ,						interpolate_pos_encoding=lowerCAmelCase__)

									# verify the logits
									SCREAMING_SNAKE_CASE_: Tuple  		=       torch.Size((1, 3601, 384))
									self.assertEqual(outputs.last_hidden_state.shape   ,						lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       torch.tensor(
									    [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]).to(lowerCAmelCase__)

									self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]   ,						lowerCAmelCase__   ,						atol=1E-4))




			@slow
			@require_accelerate
			@require_torch_gpu
			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									SCREAMING_SNAKE_CASE_: Dict  		=       ViTModel.from_pretrained("facebook/dino-vits8"   ,						torch_dtype=torch.floataa   ,						device_map="auto")
									SCREAMING_SNAKE_CASE_: int  		=       self.default_image_processor

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       prepare_img()
									SCREAMING_SNAKE_CASE_: Dict  		=       image_processor(images=lowerCAmelCase__   ,						return_tensors="pt")
									SCREAMING_SNAKE_CASE_: str  		=       inputs.pixel_values.to(lowerCAmelCase__)

									# forward pass to make sure inference works in fp16
									with torch.no_grad():
															SCREAMING_SNAKE_CASE_: str  		=       model(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())






