



import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
def 		UpperCamelCase     (       snake_case__	:   List[str]	,					snake_case__	:   List[str]=False     )     ->					Optional[Any]:
   try:
      UpperCamelCase   :  List[Any]						     =     os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      UpperCamelCase   :  List[Any]						     =     default
   else:
      # KEY is set, convert it to True or False.
      try:
         UpperCamelCase   :  Optional[Any]						     =     strtobool(snake_case__     )
      except ValueError:
         # More values are supported, but let's keep the message simple.
         raise ValueError(F"""If set, {key} must be yes or no."""     )
   return _value


__UpperCAmelCase	       =	parse_flag_from_env('''RUN_SLOW''', default=False)
def 		UpperCamelCase     (       snake_case__	:   int     )     ->					str:
   return unittest.skip('Test was skipped'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   List[Any]     )     ->					Optional[Any]:
   return unittest.skipUnless(_run_slow_tests	,					'test is slow'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   List[Any]     )     ->					Dict:
   return unittest.skipUnless(not torch.cuda.is_available()	,					'test requires only a CPU'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   List[Any]     )     ->					Dict:
   return unittest.skipUnless(torch.cuda.is_available()	,					'test requires a GPU'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Tuple     )     ->					List[Any]:
   return unittest.skipUnless(is_xpu_available()	,					'test requires a XPU'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Optional[Any]     )     ->					List[Any]:
   return unittest.skipUnless(is_mps_available()	,					'test requires a `mps` backend support in `torch`'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   List[str]     )     ->					Tuple:
   return unittest.skipUnless(
       is_transformers_available() and is_datasets_available()	,					'test requires the Hugging Face suite'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Optional[Any]     )     ->					List[Any]:
   return unittest.skipUnless(is_bnb_available()	,					'test requires the bitsandbytes library'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Dict     )     ->					List[str]:
   return unittest.skipUnless(is_tpu_available()	,					'test requires TPU'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Optional[int]     )     ->					Optional[int]:
   return unittest.skipUnless(torch.cuda.device_count() == 1	,					'test requires a GPU'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Optional[int]     )     ->					Dict:
   return unittest.skipUnless(torch.xpu.device_count() == 1	,					'test requires a XPU'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Tuple     )     ->					Any:
   return unittest.skipUnless(torch.cuda.device_count() > 1	,					'test requires multiple GPUs'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Optional[Any]     )     ->					int:
   return unittest.skipUnless(torch.xpu.device_count() > 1	,					'test requires multiple XPUs'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Optional[int]     )     ->					Any:
   return unittest.skipUnless(is_safetensors_available()	,					'test requires safetensors'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Optional[int]     )     ->					Dict:
   return unittest.skipUnless(is_deepspeed_available()	,					'test requires DeepSpeed'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Dict     )     ->					Optional[Any]:
   return unittest.skipUnless(is_torch_version('>='	,					'1.12.0'     )	,					'test requires torch version >= 1.12.0'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Dict=None	,					snake_case__	:   Union[str, Any]=None     )     ->					Optional[Any]:
   if test_case is None:
      return partial(snake_case__	,					version=snake_case__     )
   return unittest.skipUnless(is_torch_version('>='	,					snake_case__     )	,					F"""test requires torch version >= {version}"""     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Dict     )     ->					Optional[Any]:
   return unittest.skipUnless(is_tensorboard_available()	,					'test requires Tensorboard'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   str     )     ->					Tuple:
   return unittest.skipUnless(is_wandb_available()	,					'test requires wandb'     )(snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Any     )     ->					List[Any]:
   return unittest.skipUnless(is_comet_ml_available()	,					'test requires comet_ml'     )(snake_case__     )


__UpperCAmelCase	       =	(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def 		UpperCamelCase     (       snake_case__	:   Optional[Any]     )     ->					Optional[Any]:
   return unittest.skipUnless(
       _atleast_one_tracker_available	,					'test requires at least one tracker to be available and for `comet_ml` to not be installed'	,					)(snake_case__     )



class     lowerCAmelCase_		(  unittest.TestCase							):
       UpperCAmelCase__    : Optional[Any]       					=  True
       @classmethod
       def  snake_case_	(      cls	)					->		Any:
          UpperCamelCase   :  Optional[Any]						     =     tempfile.mkdtemp()
       @classmethod
       def  snake_case_	(      cls	)					->		Tuple:
          if os.path.exists(cls.tmpdir	):
             shutil.rmtree(cls.tmpdir	)






       def  snake_case_	(      self	)					->		str:
          if self.clear_on_setup:
             for path in Path(self.tmpdir	).glob('**/*'	):
                if path.is_file():
                   path.unlink()
                elif path.is_dir():
                   shutil.rmtree(SCREAMING_SNAKE_CASE_	)






class     lowerCAmelCase_		(  unittest.TestCase							):
       def  snake_case_	(      self	)					->		Optional[int]:
          super().tearDown()
          # Reset the state of the AcceleratorState singleton.
          AcceleratorState._reset_state()
          PartialState._reset_state()






class     lowerCAmelCase_		(  unittest.TestCase							):
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_	)					->		Tuple:
          UpperCamelCase   :  Optional[Any]						     =     mocks if isinstance(SCREAMING_SNAKE_CASE_,      (tuple, list)	) else [mocks]
          for m in self.mocks:
             m.start()
             self.addCleanup(m.stop	)






def 		UpperCamelCase     (       snake_case__	:   Tuple     )     ->					Optional[int]:
   UpperCamelCase   :  Tuple						     =     AcceleratorState()
   UpperCamelCase   :  Tuple						     =     tensor[None].clone().to(state.device     )
   UpperCamelCase   :  str						     =     gather(snake_case__     ).cpu()
   UpperCamelCase   :  Union[str, Any]						     =     tensor[0].cpu()
   for i in range(tensors.shape[0]     ):
      if not torch.equal(tensors[i]	,					snake_case__     ):
         return False
   return True



class     lowerCAmelCase_		:
       def __init__(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)					->		int:
          UpperCamelCase   :  List[Any]						     =     returncode
          UpperCamelCase   :  Tuple						     =     stdout
          UpperCamelCase   :  Any						     =     stderr






async def 		UpperCamelCase     (       snake_case__	:   Tuple	,					snake_case__	:   Optional[int]     )     ->					Union[str, Any]:
   while True:
      UpperCamelCase   :  List[str]						     =     await stream.readline()
      if line:
         callback(snake_case__     )
      else:
         break
async def 		UpperCamelCase     (       snake_case__	:   Dict	,					snake_case__	:   int=None	,					snake_case__	:   Dict=None	,					snake_case__	:   Any=None	,					snake_case__	:   Optional[Any]=False	,					snake_case__	:   Union[str, Any]=False     )     ->					_RunOutput:
   if echo:
      print('\nRunning: '	,					' '.join(snake_case__     )     )

   UpperCamelCase   :  Dict						     =     await asyncio.create_subprocess_exec(
       cmd[0]	,					*cmd[1:]	,					stdin=snake_case__	,					stdout=asyncio.subprocess.PIPE	,					stderr=asyncio.subprocess.PIPE	,					env=snake_case__	,					)

   # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
   # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
   #
   # If it starts hanging, will need to switch to the following code. The problem is that no data
   # will be seen until it's done and if it hangs for example there will be no debug info.
   # out, err = await p.communicate()
   # return _RunOutput(p.returncode, out, err)

   UpperCamelCase   :  Tuple						     =     []
   UpperCamelCase   :  int						     =     []

   def tee(snake_case__	:   List[Any]	,					snake_case__	:   Optional[int]	,					snake_case__	:   Optional[int]	,					snake_case__	:   List[Any]=""     ):
      UpperCamelCase   :  Union[str, Any]						     =     line.decode('utf-8'     ).rstrip()
      sink.append(snake_case__     )
      if not quiet:
         print(snake_case__	,					snake_case__	,					file=snake_case__     )

    # XXX: the timeout doesn't seem to make any difference here
   await asyncio.wait(
       [
           asyncio.create_task(_read_stream(p.stdout	,					lambda snake_case__     : tee(snake_case__	,					snake_case__	,					sys.stdout	,					label='stdout:'     )     )     ),
           asyncio.create_task(_read_stream(p.stderr	,					lambda snake_case__     : tee(snake_case__	,					snake_case__	,					sys.stderr	,					label='stderr:'     )     )     ),
       ]	,					timeout=snake_case__	,					)
   return _RunOutput(await p.wait()	,					snake_case__	,					snake_case__     )
def 		UpperCamelCase     (       snake_case__	:   Dict	,					snake_case__	:   Any=None	,					snake_case__	:   Tuple=None	,					snake_case__	:   Any=180	,					snake_case__	:   Any=False	,					snake_case__	:   Optional[int]=True     )     ->					_RunOutput:
   UpperCamelCase   :  int						     =     asyncio.get_event_loop()
   UpperCamelCase   :  Tuple						     =     loop.run_until_complete(
       _stream_subprocess(snake_case__	,					env=snake_case__	,					stdin=snake_case__	,					timeout=snake_case__	,					quiet=snake_case__	,					echo=snake_case__     )     )

   UpperCamelCase   :  str						     =     ' '.join(snake_case__     )
   if result.returncode > 0:
      UpperCamelCase   :  Union[str, Any]						     =     '\n'.join(result.stderr     )
      raise RuntimeError(
          F"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
          F"""The combined stderr from workers follows:\n{stderr}"""     )

   return result



class     lowerCAmelCase_		(  a__							):
       pass






def 		UpperCamelCase     (       snake_case__	:   List[str]	,					snake_case__	:   str=False     )     ->					int:
   try:
      UpperCamelCase   :  Union[str, Any]						     =     subprocess.check_output(snake_case__	,					stderr=subprocess.STDOUT     )
      if return_stdout:
         if hasattr(snake_case__	,					'decode'     ):
            UpperCamelCase   :  Optional[int]						     =     output.decode('utf-8'     )
         return output
   except subprocess.CalledProcessError as e:
      raise SubprocessCallException(
          F"""Command `{" ".join(snake_case__     )}` failed with the following error:\n\n{e.output.decode()}"""     ) from e








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  snake_case_	(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)					->		Union[str, Any]:
          UpperCamelCase   :  List[str]						     =     jnp.ones((batch_size, length)	) / length
          return scores
       def  snake_case_	(      self	)					->		Optional[Any]:
          UpperCamelCase   :  Optional[Any]						     =     None
          UpperCamelCase   :  Optional[int]						     =     20

          UpperCamelCase   :  Optional[Any]						     =     self._get_uniform_logits(batch_size=2,      length=SCREAMING_SNAKE_CASE_	)

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

          # compute softmax
          UpperCamelCase   :  List[str]						     =     jax.nn.softmax(SCREAMING_SNAKE_CASE_,      axis=-1	)

          UpperCamelCase   :  List[Any]						     =     FlaxTemperatureLogitsWarper(temperature=0.5	)
          UpperCamelCase   :  int						     =     FlaxTemperatureLogitsWarper(temperature=1.3	)

          UpperCamelCase   :  Tuple						     =     jax.nn.softmax(temp_dist_warper_sharper(SCREAMING_SNAKE_CASE_,      scores.copy(),      cur_len=SCREAMING_SNAKE_CASE_	),      axis=-1	)
          UpperCamelCase   :  Any						     =     jax.nn.softmax(temp_dist_warper_smoother(SCREAMING_SNAKE_CASE_,      scores.copy(),      cur_len=SCREAMING_SNAKE_CASE_	),      axis=-1	)

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

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

          # smooth peaks get lower, valleys get higher
          self.assertGreater(probs[1, :].max(),      warped_prob_smooth[1, :].max()	)
          self.assertLess(probs[1, :].min(),      warped_prob_smooth[1, :].min()	)
       def  snake_case_	(      self	)					->		Optional[Any]:
          UpperCamelCase   :  Dict						     =     None
          UpperCamelCase   :  Any						     =     10
          UpperCamelCase   :  Any						     =     2

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

          UpperCamelCase   :  Dict						     =     FlaxTopKLogitsWarper(3	)

          UpperCamelCase   :  Tuple						     =     top_k_warp(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)

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

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

          UpperCamelCase   :  Union[str, Any]						     =     np.broadcast_to(np.arange(SCREAMING_SNAKE_CASE_	)[None, :],      (batch_size, length)	).copy()
          UpperCamelCase   :  List[str]						     =     top_k_warp_safety_check(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)

          # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
          self.assertListEqual((scores == 0.0).sum(axis=-1	).tolist(),      [2, 2]	)
       def  snake_case_	(      self	)					->		Union[str, Any]:
          UpperCamelCase   :  int						     =     None
          UpperCamelCase   :  List[str]						     =     10
          UpperCamelCase   :  Optional[Any]						     =     2

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

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

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

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

          # make ramp_logits more extreme
          UpperCamelCase   :  Tuple						     =     ramp_logits[1] * 1_00.0

          # make sure at least 2 tokens are kept
          UpperCamelCase   :  int						     =     FlaxTopPLogitsWarper(0.9,      min_tokens_to_keep=2,      filter_value=0.0	)
          UpperCamelCase   :  List[str]						     =     top_p_warp(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)

          # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
          self.assertListEqual((filtered_dist != 0.0).sum(axis=-1	).tolist(),      [3, 2]	)
       def  snake_case_	(      self	)					->		List[Any]:
          UpperCamelCase   :  Union[str, Any]						     =     20
          UpperCamelCase   :  Union[str, Any]						     =     4
          UpperCamelCase   :  Optional[int]						     =     0

          UpperCamelCase   :  Dict						     =     FlaxMinLengthLogitsProcessor(min_length=10,      eos_token_id=SCREAMING_SNAKE_CASE_	)

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

          # check that min length is not applied anymore at length 15
          UpperCamelCase   :  Any						     =     self._get_uniform_logits(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Union[str, Any]						     =     15
          UpperCamelCase   :  str						     =     min_dist_processor(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)
          self.assertFalse(jnp.isinf(SCREAMING_SNAKE_CASE_	).any()	)
       def  snake_case_	(      self	)					->		Dict:
          UpperCamelCase   :  str						     =     20
          UpperCamelCase   :  List[Any]						     =     4
          UpperCamelCase   :  List[str]						     =     0

          UpperCamelCase   :  int						     =     FlaxForcedBOSTokenLogitsProcessor(bos_token_id=SCREAMING_SNAKE_CASE_	)

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

          # check that bos_token_id is not forced if current length is greater than 1
          UpperCamelCase   :  Dict						     =     3
          UpperCamelCase   :  str						     =     self._get_uniform_logits(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  int						     =     logits_processor(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)
          self.assertFalse(jnp.isinf(SCREAMING_SNAKE_CASE_	).any()	)
       def  snake_case_	(      self	)					->		List[str]:
          UpperCamelCase   :  Union[str, Any]						     =     20
          UpperCamelCase   :  Optional[Any]						     =     4
          UpperCamelCase   :  List[Any]						     =     0
          UpperCamelCase   :  int						     =     5

          UpperCamelCase   :  Tuple						     =     FlaxForcedEOSTokenLogitsProcessor(max_length=SCREAMING_SNAKE_CASE_,      eos_token_id=SCREAMING_SNAKE_CASE_	)

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

          # check that eos_token_id is not forced if max_length is not reached
          UpperCamelCase   :  str						     =     3
          UpperCamelCase   :  List[Any]						     =     self._get_uniform_logits(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Union[str, Any]						     =     logits_processor(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)
          self.assertFalse(jnp.isinf(SCREAMING_SNAKE_CASE_	).any()	)
       def  snake_case_	(      self	)					->		int:
          UpperCamelCase   :  int						     =     4
          UpperCamelCase   :  Tuple						     =     10
          UpperCamelCase   :  str						     =     15
          UpperCamelCase   :  List[str]						     =     2
          UpperCamelCase   :  Any						     =     1
          UpperCamelCase   :  List[str]						     =     15

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

          UpperCamelCase   :  Any						     =     self._get_uniform_logits(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Any						     =     scores.copy()

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

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

          UpperCamelCase   :  List[str]						     =     10

          # no processor list
          UpperCamelCase   :  Any						     =     temp_dist_warp(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Dict						     =     top_k_warp(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Dict						     =     top_p_warp(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Dict						     =     min_dist_proc(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Union[str, Any]						     =     bos_dist_proc(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  List[str]						     =     eos_dist_proc(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)

          # with processor list
          UpperCamelCase   :  List[str]						     =     FlaxLogitsProcessorList(
              [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]	)
          UpperCamelCase   :  Optional[Any]						     =     processor(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      cur_len=SCREAMING_SNAKE_CASE_	)

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

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






       def  snake_case_	(      self	)					->		int:
          UpperCamelCase   :  Optional[Any]						     =     4
          UpperCamelCase   :  Tuple						     =     10
          UpperCamelCase   :  Union[str, Any]						     =     15
          UpperCamelCase   :  Union[str, Any]						     =     2
          UpperCamelCase   :  Optional[Any]						     =     1
          UpperCamelCase   :  int						     =     15

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

          UpperCamelCase   :  Optional[int]						     =     self._get_uniform_logits(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Union[str, Any]						     =     scores.copy()

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

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

          UpperCamelCase   :  Any						     =     10

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

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

          UpperCamelCase   :  Dict						     =     jax.jit(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  List[str]						     =     jax.jit(SCREAMING_SNAKE_CASE_	)

          UpperCamelCase   :  int						     =     jitted_run_no_processor_list(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  int						     =     jitted_run_processor_list(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)

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

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



