
"""simple docstring"""


import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VideoMAEConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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 (
						    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
						    VideoMAEForPreTraining,
						    VideoMAEForVideoClassification,
						    VideoMAEModel,
						)
						from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from transformers import VideoMAEImageProcessor




class  __lowerCamelCase  :




				def __init__(				self							,						UpperCAmelCase							,						UpperCAmelCase=13							,						UpperCAmelCase=10							,						UpperCAmelCase=3							,						UpperCAmelCase=2							,						UpperCAmelCase=2							,						UpperCAmelCase=2							,						UpperCAmelCase=True							,						UpperCAmelCase=True							,						UpperCAmelCase=32							,						UpperCAmelCase=5							,						UpperCAmelCase=4							,						UpperCAmelCase=37							,						UpperCAmelCase="gelu"							,						UpperCAmelCase=0.1							,						UpperCAmelCase=0.1							,						UpperCAmelCase=10							,						UpperCAmelCase=0.0_2							,						UpperCAmelCase=0.9							,						UpperCAmelCase=None							,						):
							lowerCamelCase_					=  parent
							lowerCamelCase_					=  batch_size
							lowerCamelCase_					=  image_size
							lowerCamelCase_					=  num_channels
							lowerCamelCase_					=  patch_size
							lowerCamelCase_					=  tubelet_size
							lowerCamelCase_					=  num_frames
							lowerCamelCase_					=  is_training
							lowerCamelCase_					=  use_labels
							lowerCamelCase_					=  hidden_size
							lowerCamelCase_					=  num_hidden_layers
							lowerCamelCase_					=  num_attention_heads
							lowerCamelCase_					=  intermediate_size
							lowerCamelCase_					=  hidden_act
							lowerCamelCase_					=  hidden_dropout_prob
							lowerCamelCase_					=  attention_probs_dropout_prob
							lowerCamelCase_					=  type_sequence_label_size
							lowerCamelCase_					=  initializer_range
							lowerCamelCase_					=  mask_ratio
							lowerCamelCase_					=  scope

							# in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
							lowerCamelCase_					=  (image_size // patch_size) ** 2
							lowerCamelCase_					=  (num_frames // tubelet_size) * self.num_patches_per_frame

							# use this variable to define bool_masked_pos
							lowerCamelCase_					=  int(mask_ratio * self.seq_length   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  floats_tensor(
							    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]   )

							lowerCamelCase_					=  None
							if self.use_labels:
										lowerCamelCase_					=  ids_tensor([self.batch_size]							,						self.type_sequence_label_size   )

							lowerCamelCase_					=  self.get_config()

							return config, pixel_values, labels




				def        UpperCAmelCase__						(				self   ):
							return VideoMAEConfig(
							    image_size=self.image_size							,						patch_size=self.patch_size							,						num_channels=self.num_channels							,						num_frames=self.num_frames							,						tubelet_size=self.tubelet_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							,						is_decoder=UpperCAmelCase							,						initializer_range=self.initializer_range							,						)




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   ):
							lowerCamelCase_					=  VideoMAEModel(config=UpperCAmelCase   )
							model.to(UpperCAmelCase   )
							model.eval()
							lowerCamelCase_					=  model(UpperCAmelCase   )
							self.parent.assertEqual(result.last_hidden_state.shape							,						(self.batch_size, self.seq_length, self.hidden_size)   )




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   ):
							lowerCamelCase_					=  VideoMAEForPreTraining(UpperCAmelCase   )
							model.to(UpperCAmelCase   )
							model.eval()
							# important: each video needs to have the same number of masked patches
							# hence we define a single mask, which we then repeat for each example in the batch
							lowerCamelCase_					=  torch.ones((self.num_masks,)   )
							lowerCamelCase_					=  torch.cat([mask, torch.zeros(self.seq_length - mask.size(0   )   )]   )
							lowerCamelCase_					=  mask.expand(self.batch_size							,						-1   ).bool()

							lowerCamelCase_					=  model(UpperCAmelCase							,						UpperCAmelCase   )
							# model only returns predictions for masked patches
							lowerCamelCase_					=  mask.sum().item()
							lowerCamelCase_					=  3 * self.tubelet_size * self.patch_size**2
							self.parent.assertEqual(result.logits.shape							,						(self.batch_size, num_masked_patches, decoder_num_labels)   )





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.prepare_config_and_inputs()
							lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_					=  config_and_inputs
							lowerCamelCase_					=  {'''pixel_values''': pixel_values}
							return config, inputs_dict




@require_torch
class  __lowerCamelCase  ( lowerCAmelCase						,	lowerCAmelCase						,	unittest.TestCase			):
				a__:      Optional[Any]          =    (
				    (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
				)
				a__:      List[Any]          =    (
				    {'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification}
				    if is_torch_available()
				    else {}
				)

				a__:      Tuple          =    False
				a__:      List[str]          =    False
				a__:      Optional[Any]          =    False
				a__:      List[str]          =    False




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  VideoMAEModelTester(self   )
							lowerCamelCase_					=  ConfigTester(self							,						config_class=UpperCAmelCase							,						has_text_modality=UpperCAmelCase							,						hidden_size=37   )




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase=False   ):
							lowerCamelCase_					=  copy.deepcopy(UpperCAmelCase   )

							if model_class == VideoMAEForPreTraining:
										# important: each video needs to have the same number of masked patches
										# hence we define a single mask, which we then repeat for each example in the batch
										lowerCamelCase_					=  torch.ones((self.model_tester.num_masks,)   )
										lowerCamelCase_					=  torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0   )   )]   )
										lowerCamelCase_					=  mask.expand(self.model_tester.batch_size							,						-1   ).bool()
										lowerCamelCase_					=  bool_masked_pos.to(UpperCAmelCase   )

							if return_labels:
										if model_class in [
										    *get_values(UpperCAmelCase   ),
										]:
													lowerCamelCase_					=  torch.zeros(
													    self.model_tester.batch_size							,						dtype=torch.long							,						device=UpperCAmelCase   )

							return inputs_dict




				def        UpperCAmelCase__						(				self   ):
							self.config_tester.run_common_tests()




				@unittest.skip(reason='''VideoMAE does not use inputs_embeds'''   )
				def        UpperCAmelCase__						(				self   ):
							pass




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_		, lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										lowerCamelCase_					=  model_class(UpperCAmelCase   )
										self.assertIsInstance(model.get_input_embeddings()							,						(nn.Module)   )
										lowerCamelCase_					=  model.get_output_embeddings()
										self.assertTrue(x is None or isinstance(UpperCAmelCase							,						nn.Linear   )   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_		, lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										lowerCamelCase_					=  model_class(UpperCAmelCase   )
										lowerCamelCase_					=  inspect.signature(model.forward   )
										# signature.parameters is an OrderedDict => so arg_names order is deterministic
										lowerCamelCase_					=  [*signature.parameters.keys()]

										lowerCamelCase_					=  ['''pixel_values''']
										self.assertListEqual(arg_names[:1]							,						UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase   )




				@slow
				def        UpperCAmelCase__						(				self   ):
							for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowerCamelCase_					=  VideoMAEModel.from_pretrained(UpperCAmelCase   )
										self.assertIsNotNone(UpperCAmelCase   )




				def        UpperCAmelCase__						(				self   ):
							if not self.has_attentions:
										pass

							else:
										lowerCamelCase_		, lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()
										lowerCamelCase_					=  True

										for model_class in self.all_model_classes:
													lowerCamelCase_					=  self.model_tester.seq_length - self.model_tester.num_masks
													lowerCamelCase_					=  (
													    num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
													)

													lowerCamelCase_					=  True
													lowerCamelCase_					=  False
													lowerCamelCase_					=  True
													lowerCamelCase_					=  model_class(UpperCAmelCase   )
													model.to(UpperCAmelCase   )
													model.eval()
													with torch.no_grad():
																lowerCamelCase_					=  model(**self._prepare_for_class(UpperCAmelCase							,						UpperCAmelCase   )   )
													lowerCamelCase_					=  outputs.attentions
													self.assertEqual(len(UpperCAmelCase   )							,						self.model_tester.num_hidden_layers   )

													# check that output_attentions also work using config
													del inputs_dict["output_attentions"]
													lowerCamelCase_					=  True
													lowerCamelCase_					=  model_class(UpperCAmelCase   )
													model.to(UpperCAmelCase   )
													model.eval()
													with torch.no_grad():
																lowerCamelCase_					=  model(**self._prepare_for_class(UpperCAmelCase							,						UpperCAmelCase   )   )
													lowerCamelCase_					=  outputs.attentions
													self.assertEqual(len(UpperCAmelCase   )							,						self.model_tester.num_hidden_layers   )

													self.assertListEqual(
													    list(attentions[0].shape[-3:]   )							,						[self.model_tester.num_attention_heads, seq_len, seq_len]							,						)
													lowerCamelCase_					=  len(UpperCAmelCase   )

													# Check attention is always last and order is fine
													lowerCamelCase_					=  True
													lowerCamelCase_					=  True
													lowerCamelCase_					=  model_class(UpperCAmelCase   )
													model.to(UpperCAmelCase   )
													model.eval()
													with torch.no_grad():
																lowerCamelCase_					=  model(**self._prepare_for_class(UpperCAmelCase							,						UpperCAmelCase   )   )

													self.assertEqual(out_len + 1							,						len(UpperCAmelCase   )   )

													lowerCamelCase_					=  outputs.attentions

													self.assertEqual(len(UpperCAmelCase   )							,						self.model_tester.num_hidden_layers   )
													self.assertListEqual(
													    list(self_attentions[0].shape[-3:]   )							,						[self.model_tester.num_attention_heads, seq_len, seq_len]							,						)




				def        UpperCAmelCase__						(				self   ):
							def check_hidden_states_output(UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   ):
										lowerCamelCase_					=  model_class(UpperCAmelCase   )
										model.to(UpperCAmelCase   )
										model.eval()

										with torch.no_grad():
													lowerCamelCase_					=  model(**self._prepare_for_class(UpperCAmelCase							,						UpperCAmelCase   )   )

										lowerCamelCase_					=  outputs.hidden_states
										lowerCamelCase_					=  self.model_tester.num_hidden_layers + 1
										self.assertEqual(len(UpperCAmelCase   )							,						UpperCAmelCase   )

										lowerCamelCase_					=  self.model_tester.seq_length - self.model_tester.num_masks
										lowerCamelCase_					=  num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

										self.assertListEqual(
										    list(hidden_states[0].shape[-2:]   )							,						[seq_length, self.model_tester.hidden_size]							,						)

							lowerCamelCase_		, lowerCamelCase_					=  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										lowerCamelCase_					=  True
										check_hidden_states_output(UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   )

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										lowerCamelCase_					=  True

										check_hidden_states_output(UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   )





				@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
				def        UpperCAmelCase__						(				self   ):
							pass






def  lowercase						(	):
			lowerCamelCase_					=  hf_hub_download(
			    repo_id='''hf-internal-testing/spaghetti-video'''	,filename='''eating_spaghetti.npy'''	,repo_type='''dataset'''						)
			lowerCamelCase_					=  np.load(lowerCAmelCase__						)
			return list(lowerCAmelCase__						)




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




				@cached_property
				def        UpperCAmelCase__						(				self   ):
							# logits were tested with a different mean and std, so we use the same here
							return (
							    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]							,						image_std=[0.5, 0.5, 0.5]   )
							    if is_vision_available()
							    else None
							)




				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  VideoMAEForVideoClassification.from_pretrained('''MCG-NJU/videomae-base-finetuned-kinetics'''   ).to(
							    UpperCAmelCase   )

							lowerCamelCase_					=  self.default_image_processor
							lowerCamelCase_					=  prepare_video()
							lowerCamelCase_					=  image_processor(UpperCAmelCase							,						return_tensors='''pt'''   ).to(UpperCAmelCase   )

							# forward pass
							with torch.no_grad():
										lowerCamelCase_					=  model(**UpperCAmelCase   )

							# verify the logits
							lowerCamelCase_					=  torch.Size((1, 400)   )
							self.assertEqual(outputs.logits.shape							,						UpperCAmelCase   )

							lowerCamelCase_					=  torch.tensor([0.3_6_6_9, -0.0_6_8_8, -0.2_4_2_1]   ).to(UpperCAmelCase   )

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





				@slow
				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short'''   ).to(UpperCAmelCase   )

							lowerCamelCase_					=  self.default_image_processor
							lowerCamelCase_					=  prepare_video()
							lowerCamelCase_					=  image_processor(UpperCAmelCase							,						return_tensors='''pt'''   ).to(UpperCAmelCase   )

							# add boolean mask, indicating which patches to mask
							lowerCamelCase_					=  hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos'''							,						filename='''bool_masked_pos.pt'''   )
							lowerCamelCase_					=  torch.load(UpperCAmelCase   )

							# forward pass
							with torch.no_grad():
										lowerCamelCase_					=  model(**UpperCAmelCase   )

							# verify the logits
							lowerCamelCase_					=  torch.Size([1, 1408, 1536]   )
							lowerCamelCase_					=  torch.tensor(
							    [[0.7_9_9_4, 0.9_6_1_2, 0.8_5_0_8], [0.7_4_0_1, 0.8_9_5_8, 0.8_3_0_2], [0.5_8_6_2, 0.7_4_6_8, 0.7_3_2_5]]							,						device=UpperCAmelCase   )
							self.assertEqual(outputs.logits.shape							,						UpperCAmelCase   )
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]							,						UpperCAmelCase							,						atol=1e-4   )   )

							# verify the loss (`config.norm_pix_loss` = `True`)
							lowerCamelCase_					=  torch.tensor([0.5_1_4_2]							,						device=UpperCAmelCase   )
							self.assertTrue(torch.allclose(outputs.loss							,						UpperCAmelCase							,						atol=1e-4   )   )

							# verify the loss (`config.norm_pix_loss` = `False`)
							lowerCamelCase_					=  VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short'''							,						norm_pix_loss=UpperCAmelCase   ).to(
							    UpperCAmelCase   )

							with torch.no_grad():
										lowerCamelCase_					=  model(**UpperCAmelCase   )

							lowerCamelCase_					=  torch.tensor(torch.tensor([0.6_4_6_9]   )							,						device=UpperCAmelCase   )
							self.assertTrue(torch.allclose(outputs.loss							,						UpperCAmelCase							,						atol=1e-4   )   )





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




				def        UpperCAmelCase__						(				self							,						UpperCAmelCase							,						UpperCAmelCase   ):
							lowerCamelCase_					=  jnp.ones((batch_size, length)   ) / length
							return scores




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  None
							lowerCamelCase_					=  20

							lowerCamelCase_					=  self._get_uniform_logits(batch_size=2							,						length=UpperCAmelCase   )

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

							# compute softmax
							lowerCamelCase_					=  jax.nn.softmax(UpperCAmelCase							,						axis=-1   )

							lowerCamelCase_					=  FlaxTemperatureLogitsWarper(temperature=0.5   )
							lowerCamelCase_					=  FlaxTemperatureLogitsWarper(temperature=1.3   )

							lowerCamelCase_					=  jax.nn.softmax(temp_dist_warper_sharper(UpperCAmelCase							,						scores.copy()							,						cur_len=UpperCAmelCase   )							,						axis=-1   )
							lowerCamelCase_					=  jax.nn.softmax(temp_dist_warper_smoother(UpperCAmelCase							,						scores.copy()							,						cur_len=UpperCAmelCase   )							,						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        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  None
							lowerCamelCase_					=  10
							lowerCamelCase_					=  2

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

							lowerCamelCase_					=  FlaxTopKLogitsWarper(3   )

							lowerCamelCase_					=  top_k_warp(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )

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

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

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




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  None
							lowerCamelCase_					=  10
							lowerCamelCase_					=  2

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

							lowerCamelCase_					=  FlaxTopPLogitsWarper(0.8   )
							lowerCamelCase_					=  np.exp(top_p_warp(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )   )

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

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

							# make ramp_logits more extreme
							lowerCamelCase_					=  ramp_logits[1] * 1_0_0.0

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

							# 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        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  20
							lowerCamelCase_					=  4
							lowerCamelCase_					=  0

							lowerCamelCase_					=  FlaxMinLengthLogitsProcessor(min_length=10							,						eos_token_id=UpperCAmelCase   )

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

							# check that min length is not applied anymore at length 15
							lowerCamelCase_					=  self._get_uniform_logits(UpperCAmelCase							,						UpperCAmelCase   )
							lowerCamelCase_					=  15
							lowerCamelCase_					=  min_dist_processor(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							self.assertFalse(jnp.isinf(UpperCAmelCase   ).any()   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  20
							lowerCamelCase_					=  4
							lowerCamelCase_					=  0

							lowerCamelCase_					=  FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase   )

							# check that all scores are -inf except the bos_token_id score
							lowerCamelCase_					=  ids_tensor((batch_size, 1)							,						vocab_size=20   )
							lowerCamelCase_					=  1
							lowerCamelCase_					=  self._get_uniform_logits(UpperCAmelCase							,						UpperCAmelCase   )
							lowerCamelCase_					=  logits_processor(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							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
							lowerCamelCase_					=  3
							lowerCamelCase_					=  self._get_uniform_logits(UpperCAmelCase							,						UpperCAmelCase   )
							lowerCamelCase_					=  logits_processor(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							self.assertFalse(jnp.isinf(UpperCAmelCase   ).any()   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  20
							lowerCamelCase_					=  4
							lowerCamelCase_					=  0
							lowerCamelCase_					=  5

							lowerCamelCase_					=  FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase							,						eos_token_id=UpperCAmelCase   )

							# check that all scores are -inf except the eos_token_id when max_length is reached
							lowerCamelCase_					=  ids_tensor((batch_size, 4)							,						vocab_size=20   )
							lowerCamelCase_					=  4
							lowerCamelCase_					=  self._get_uniform_logits(UpperCAmelCase							,						UpperCAmelCase   )
							lowerCamelCase_					=  logits_processor(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							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
							lowerCamelCase_					=  3
							lowerCamelCase_					=  self._get_uniform_logits(UpperCAmelCase							,						UpperCAmelCase   )
							lowerCamelCase_					=  logits_processor(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							self.assertFalse(jnp.isinf(UpperCAmelCase   ).any()   )




				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  4
							lowerCamelCase_					=  10
							lowerCamelCase_					=  15
							lowerCamelCase_					=  2
							lowerCamelCase_					=  1
							lowerCamelCase_					=  15

							# dummy input_ids and scores
							lowerCamelCase_					=  ids_tensor((batch_size, sequence_length)							,						UpperCAmelCase   )
							lowerCamelCase_					=  input_ids.copy()

							lowerCamelCase_					=  self._get_uniform_logits(UpperCAmelCase							,						UpperCAmelCase   )
							lowerCamelCase_					=  scores.copy()

							# instantiate all dist processors
							lowerCamelCase_					=  FlaxTemperatureLogitsWarper(temperature=0.5   )
							lowerCamelCase_					=  FlaxTopKLogitsWarper(3   )
							lowerCamelCase_					=  FlaxTopPLogitsWarper(0.8   )

							# instantiate all logits processors
							lowerCamelCase_					=  FlaxMinLengthLogitsProcessor(min_length=10							,						eos_token_id=UpperCAmelCase   )
							lowerCamelCase_					=  FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase   )
							lowerCamelCase_					=  FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase							,						eos_token_id=UpperCAmelCase   )

							lowerCamelCase_					=  10

							# no processor list
							lowerCamelCase_					=  temp_dist_warp(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							lowerCamelCase_					=  top_k_warp(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							lowerCamelCase_					=  top_p_warp(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							lowerCamelCase_					=  min_dist_proc(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							lowerCamelCase_					=  bos_dist_proc(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
							lowerCamelCase_					=  eos_dist_proc(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )

							# with processor list
							lowerCamelCase_					=  FlaxLogitsProcessorList(
							    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]   )
							lowerCamelCase_					=  processor(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )

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

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





				def        UpperCAmelCase__						(				self   ):
							lowerCamelCase_					=  4
							lowerCamelCase_					=  10
							lowerCamelCase_					=  15
							lowerCamelCase_					=  2
							lowerCamelCase_					=  1
							lowerCamelCase_					=  15

							# dummy input_ids and scores
							lowerCamelCase_					=  ids_tensor((batch_size, sequence_length)							,						UpperCAmelCase   )
							lowerCamelCase_					=  input_ids.copy()

							lowerCamelCase_					=  self._get_uniform_logits(UpperCAmelCase							,						UpperCAmelCase   )
							lowerCamelCase_					=  scores.copy()

							# instantiate all dist processors
							lowerCamelCase_					=  FlaxTemperatureLogitsWarper(temperature=0.5   )
							lowerCamelCase_					=  FlaxTopKLogitsWarper(3   )
							lowerCamelCase_					=  FlaxTopPLogitsWarper(0.8   )

							# instantiate all logits processors
							lowerCamelCase_					=  FlaxMinLengthLogitsProcessor(min_length=10							,						eos_token_id=UpperCAmelCase   )
							lowerCamelCase_					=  FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase   )
							lowerCamelCase_					=  FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase							,						eos_token_id=UpperCAmelCase   )

							lowerCamelCase_					=  10

							# no processor list
							def run_no_processor_list(UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   ):
										lowerCamelCase_					=  temp_dist_warp(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
										lowerCamelCase_					=  top_k_warp(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
										lowerCamelCase_					=  top_p_warp(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
										lowerCamelCase_					=  min_dist_proc(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
										lowerCamelCase_					=  bos_dist_proc(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
										lowerCamelCase_					=  eos_dist_proc(UpperCAmelCase							,						UpperCAmelCase							,						cur_len=UpperCAmelCase   )
										return scores

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

							lowerCamelCase_					=  jax.jit(UpperCAmelCase   )
							lowerCamelCase_					=  jax.jit(UpperCAmelCase   )

							lowerCamelCase_					=  jitted_run_no_processor_list(UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   )
							lowerCamelCase_					=  jitted_run_processor_list(UpperCAmelCase							,						UpperCAmelCase							,						UpperCAmelCase   )

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

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



