





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







       def 						__lowerCamelCase   (				self					:     Dict		, A					:     int		, A					:     int      )       ->List[Any]:
          lowerCamelCase__       :						Union[str, Any]        =							jnp.ones((batch_size, length)      ) / length
          return scores







       def 						__lowerCamelCase   (				self					:     Optional[Any]      )       ->Dict:
          lowerCamelCase__       :						List[Any]        =							None
          lowerCamelCase__       :						Tuple        =							2_0

          lowerCamelCase__       :						Optional[int]        =							self._get_uniform_logits(batch_size=2		, length=A      )

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

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

          lowerCamelCase__       :						Optional[int]        =							FlaxTemperatureLogitsWarper(temperature=0.5      )
          lowerCamelCase__       :						Optional[Any]        =							FlaxTemperatureLogitsWarper(temperature=1.3      )

          lowerCamelCase__       :						Optional[Any]        =							jax.nn.softmax(temp_dist_warper_sharper(A		, scores.copy()		, cur_len=A      )		, axis=-1      )
          lowerCamelCase__       :						int        =							jax.nn.softmax(temp_dist_warper_smoother(A		, scores.copy()		, cur_len=A      )		, 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 						__lowerCamelCase   (				self					:     str      )       ->Optional[int]:
          lowerCamelCase__       :						Optional[int]        =							None
          lowerCamelCase__       :						Any        =							1_0
          lowerCamelCase__       :						Tuple        =							2

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

          lowerCamelCase__       :						Dict        =							FlaxTopKLogitsWarper(3      )

          lowerCamelCase__       :						Tuple        =							top_k_warp(A		, A		, cur_len=A      )

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

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

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







       def 						__lowerCamelCase   (				self					:     Dict      )       ->Union[str, Any]:
          lowerCamelCase__       :						int        =							None
          lowerCamelCase__       :						Dict        =							1_0
          lowerCamelCase__       :						Any        =							2

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

          lowerCamelCase__       :						str        =							FlaxTopPLogitsWarper(0.8      )
          lowerCamelCase__       :						Optional[Any]        =							np.exp(top_p_warp(A		, A		, cur_len=A      )      )

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

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

          # make ramp_logits more extreme
          lowerCamelCase__       :						Optional[Any]        =							ramp_logits[1] * 1_00.0

          # make sure at least 2 tokens are kept
          lowerCamelCase__       :						Dict        =							FlaxTopPLogitsWarper(0.9		, min_tokens_to_keep=2		, filter_value=0.0      )
          lowerCamelCase__       :						Optional[int]        =							top_p_warp(A		, A		, cur_len=A      )

          # 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 						__lowerCamelCase   (				self					:     Dict      )       ->List[str]:
          lowerCamelCase__       :						Union[str, Any]        =							2_0
          lowerCamelCase__       :						Union[str, Any]        =							4
          lowerCamelCase__       :						Optional[Any]        =							0

          lowerCamelCase__       :						Optional[Any]        =							FlaxMinLengthLogitsProcessor(min_length=1_0		, eos_token_id=A      )

          # check that min length is applied at length 5
          lowerCamelCase__       :						str        =							ids_tensor((batch_size, 2_0)		, vocab_size=2_0      )
          lowerCamelCase__       :						Optional[int]        =							5
          lowerCamelCase__       :						Dict        =							self._get_uniform_logits(A		, A      )
          lowerCamelCase__       :						Optional[Any]        =							min_dist_processor(A		, A		, cur_len=A      )
          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__       :						Any        =							self._get_uniform_logits(A		, A      )
          lowerCamelCase__       :						str        =							1_5
          lowerCamelCase__       :						List[Any]        =							min_dist_processor(A		, A		, cur_len=A      )
          self.assertFalse(jnp.isinf(A      ).any()      )







       def 						__lowerCamelCase   (				self					:     Any      )       ->List[str]:
          lowerCamelCase__       :						Union[str, Any]        =							2_0
          lowerCamelCase__       :						Optional[Any]        =							4
          lowerCamelCase__       :						Optional[Any]        =							0

          lowerCamelCase__       :						Tuple        =							FlaxForcedBOSTokenLogitsProcessor(bos_token_id=A      )

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







       def 						__lowerCamelCase   (				self					:     Optional[int]      )       ->Any:
          lowerCamelCase__       :						Optional[Any]        =							2_0
          lowerCamelCase__       :						List[str]        =							4
          lowerCamelCase__       :						Union[str, Any]        =							0
          lowerCamelCase__       :						Tuple        =							5

          lowerCamelCase__       :						List[str]        =							FlaxForcedEOSTokenLogitsProcessor(max_length=A		, eos_token_id=A      )

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







       def 						__lowerCamelCase   (				self					:     List[str]      )       ->List[Any]:
          lowerCamelCase__       :						List[str]        =							4
          lowerCamelCase__       :						Any        =							1_0
          lowerCamelCase__       :						int        =							1_5
          lowerCamelCase__       :						str        =							2
          lowerCamelCase__       :						List[str]        =							1
          lowerCamelCase__       :						Tuple        =							1_5

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

          lowerCamelCase__       :						List[str]        =							self._get_uniform_logits(A		, A      )
          lowerCamelCase__       :						Tuple        =							scores.copy()

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

          # instantiate all logits processors
          lowerCamelCase__       :						Optional[int]        =							FlaxMinLengthLogitsProcessor(min_length=1_0		, eos_token_id=A      )
          lowerCamelCase__       :						int        =							FlaxForcedBOSTokenLogitsProcessor(bos_token_id=A      )
          lowerCamelCase__       :						List[Any]        =							FlaxForcedEOSTokenLogitsProcessor(max_length=A		, eos_token_id=A      )

          lowerCamelCase__       :						List[str]        =							1_0

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

          # with processor list
          lowerCamelCase__       :						Any        =							FlaxLogitsProcessorList(
              [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]      )
          lowerCamelCase__       :						Optional[Any]        =							processor(A		, A		, cur_len=A      )

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

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







       def 						__lowerCamelCase   (				self					:     Dict      )       ->List[str]:
          lowerCamelCase__       :						Optional[Any]        =							4
          lowerCamelCase__       :						Union[str, Any]        =							1_0
          lowerCamelCase__       :						int        =							1_5
          lowerCamelCase__       :						Tuple        =							2
          lowerCamelCase__       :						str        =							1
          lowerCamelCase__       :						List[Any]        =							1_5

          # dummy input_ids and scores
          lowerCamelCase__       :						int        =							ids_tensor((batch_size, sequence_length)		, A      )
          lowerCamelCase__       :						Optional[Any]        =							input_ids.copy()

          lowerCamelCase__       :						List[Any]        =							self._get_uniform_logits(A		, A      )
          lowerCamelCase__       :						Tuple        =							scores.copy()

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

          # instantiate all logits processors
          lowerCamelCase__       :						Optional[int]        =							FlaxMinLengthLogitsProcessor(min_length=1_0		, eos_token_id=A      )
          lowerCamelCase__       :						Optional[Any]        =							FlaxForcedBOSTokenLogitsProcessor(bos_token_id=A      )
          lowerCamelCase__       :						List[Any]        =							FlaxForcedEOSTokenLogitsProcessor(max_length=A		, eos_token_id=A      )

          lowerCamelCase__       :						int        =							1_0

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

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

          lowerCamelCase__       :						Dict        =							jax.jit(A      )
          lowerCamelCase__       :						Union[str, Any]        =							jax.jit(A      )

          lowerCamelCase__       :						Union[str, Any]        =							jitted_run_no_processor_list(A		, A		, A      )
          lowerCamelCase__       :						List[Any]        =							jitted_run_processor_list(A		, A		, A      )

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

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










from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


_A :   Tuple  			=  logging.get_logger(__name__)

_A :   List[str]  			=  {
    'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json',
    # See all Nat models at https://huggingface.co/models?filter=nat
}


class        __SCREAMING_SNAKE_CASE      (			lowerCAmelCase_					,lowerCAmelCase_ ):
       _UpperCAmelCase				:  Dict			   =   "nat"

       _UpperCAmelCase				:  Tuple			   =   {
           "num_attention_heads": "num_heads",
           "num_hidden_layers": "num_layers",
       }







       def __init__(				self					:     List[Any]		, A					:     Union[str, Any]=4		, A					:     str=3		, A					:     List[Any]=6_4		, A					:     Optional[Any]=[3, 4, 6, 5]		, A					:     int=[2, 4, 8, 1_6]		, A					:     Optional[int]=7		, A					:     List[Any]=3.0		, A					:     str=True		, A					:     str=0.0		, A					:     Any=0.0		, A					:     int=0.1		, A					:     Tuple="gelu"		, A					:     List[Any]=0.02		, A					:     str=1e-5		, A					:     Optional[int]=0.0		, A					:     Optional[Any]=None		, A					:     Dict=None		, **A					:     str		, )       ->Union[str, Any]:
          super().__init__(**A      )

          lowerCamelCase__       :						Any        =							patch_size
          lowerCamelCase__       :						Optional[Any]        =							num_channels
          lowerCamelCase__       :						Any        =							embed_dim
          lowerCamelCase__       :						str        =							depths
          lowerCamelCase__       :						Union[str, Any]        =							len(A      )
          lowerCamelCase__       :						int        =							num_heads
          lowerCamelCase__       :						Optional[int]        =							kernel_size
          lowerCamelCase__       :						Optional[int]        =							mlp_ratio
          lowerCamelCase__       :						List[Any]        =							qkv_bias
          lowerCamelCase__       :						Tuple        =							hidden_dropout_prob
          lowerCamelCase__       :						List[str]        =							attention_probs_dropout_prob
          lowerCamelCase__       :						List[Any]        =							drop_path_rate
          lowerCamelCase__       :						Union[str, Any]        =							hidden_act
          lowerCamelCase__       :						Union[str, Any]        =							layer_norm_eps
          lowerCamelCase__       :						List[Any]        =							initializer_range
          # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel
          # this indicates the channel dimension after the last stage of the model
          lowerCamelCase__       :						str        =							int(embed_dim * 2 ** (len(A      ) - 1)      )
          lowerCamelCase__       :						Dict        =							layer_scale_init_value
          lowerCamelCase__       :						Dict        =							['''stem'''] + [F"stage{idx}" for idx in range(1		, len(A      ) + 1      )]
          lowerCamelCase__       ,							lowerCamelCase__       :						str        =							get_aligned_output_features_output_indices(
              out_features=A		, out_indices=A		, stage_names=self.stage_names      )



