






"""simple docstring"""
import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


lowerCamelCase_					=      get_logger(__name__)


lowerCamelCase_					=      r'''\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n'''







class 			UpperCamelCase_       :





	@add_start_docstrings(__UpperCAmelCase						)
	def __call__(      self					: Optional[Any]	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray						)						->			jnp.ndarray:
				raise NotImplementedError(
				    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""						)







class 			UpperCamelCase_       :





	@add_start_docstrings(__UpperCAmelCase						)
	def __call__(      self					: Tuple	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray						)						->			jnp.ndarray:
				raise NotImplementedError(
				    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""						)







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	@add_start_docstrings(__UpperCAmelCase						)
	def __call__(      self					: Tuple	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int	,	**lowerCAmelCase_					: str						)						->			jnp.ndarray:



				for processor in self:
							UpperCAmelCase_     : List[Any]			     =					inspect.signature(processor.__call__						).parameters
							if len(__UpperCAmelCase						) > 3:
										if not all(arg in kwargs for arg in list(function_args.keys()						)[2:]						):
													raise ValueError(
													    f"""Make sure that all the required parameters: {list(function_args.keys()						)} for """
													    f"""{processor.__class__} are passed to the logits processor."""						)
										UpperCAmelCase_     : Union[str, Any]			     =					processor(__UpperCAmelCase	,	__UpperCAmelCase	,	__UpperCAmelCase	,	**__UpperCAmelCase						)
							else:
										UpperCAmelCase_     : List[str]			     =					processor(__UpperCAmelCase	,	__UpperCAmelCase	,	__UpperCAmelCase						)
				return scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: Any	,	lowerCAmelCase_					: float						)						->			Union[str, Any]:



				if not isinstance(__UpperCAmelCase	,	__UpperCAmelCase						) or not (temperature > 0):
							raise ValueError(f"""`temperature` has to be a strictly positive float, but is {temperature}"""						)

				UpperCAmelCase_     : str			     =					temperature





	def __call__(      self					: Union[str, Any]	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int						)						->			jnp.ndarray:
				UpperCAmelCase_     : Dict			     =					scores / self.temperature
				return scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: Any	,	lowerCAmelCase_					: float	,	lowerCAmelCase_					: float = -float("Inf"						)	,	lowerCAmelCase_					: int = 1						)						->			str:



				if not isinstance(__UpperCAmelCase	,	__UpperCAmelCase						) or (top_p < 0 or top_p > 1.0):
							raise ValueError(f"""`top_p` has to be a float > 0 and < 1, but is {top_p}"""						)
				if not isinstance(__UpperCAmelCase	,	__UpperCAmelCase						) or (min_tokens_to_keep < 1):
							raise ValueError(f"""`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}"""						)

				UpperCAmelCase_     : Dict			     =					top_p
				UpperCAmelCase_     : Optional[Any]			     =					filter_value
				UpperCAmelCase_     : Dict			     =					min_tokens_to_keep





	def __call__(      self					: Any	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int						)						->			jnp.ndarray:
				UpperCAmelCase_     ,	UpperCAmelCase_     : str			     =					lax.top_k(__UpperCAmelCase	,	scores.shape[-1]						)

				UpperCAmelCase_     : str			     =					jnp.full_like(__UpperCAmelCase	,	self.filter_value						)
				UpperCAmelCase_     : Optional[int]			     =					jax.nn.softmax(__UpperCAmelCase	,	axis=-1						).cumsum(axis=-1						)
				UpperCAmelCase_     : List[Any]			     =					cumulative_probs < self.top_p

				# include the token that is higher than top_p as well
				UpperCAmelCase_     : List[str]			     =					jnp.roll(__UpperCAmelCase	,	1						)
				score_mask |= score_mask.at[:, 0].set(__UpperCAmelCase						)

				# min tokens to keep
				UpperCAmelCase_     : Union[str, Any]			     =					score_mask.at[:, : self.min_tokens_to_keep].set(__UpperCAmelCase						)

				UpperCAmelCase_     : int			     =					jnp.where(__UpperCAmelCase	,	__UpperCAmelCase	,	__UpperCAmelCase						)
				UpperCAmelCase_     : int			     =					jax.lax.sort_key_val(__UpperCAmelCase	,	__UpperCAmelCase						)[-1]

				return next_scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: List[Any]	,	lowerCAmelCase_					: int	,	lowerCAmelCase_					: float = -float("Inf"						)	,	lowerCAmelCase_					: int = 1						)						->			str:



				if not isinstance(__UpperCAmelCase	,	__UpperCAmelCase						) or top_k <= 0:
							raise ValueError(f"""`top_k` has to be a strictly positive integer, but is {top_k}"""						)

				UpperCAmelCase_     : List[Any]			     =					max(__UpperCAmelCase	,	__UpperCAmelCase						)
				UpperCAmelCase_     : List[Any]			     =					filter_value





	def __call__(      self					: Any	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int						)						->			jnp.ndarray:
				UpperCAmelCase_     ,	UpperCAmelCase_     : Optional[int]			     =					scores.shape
				UpperCAmelCase_     : str			     =					jnp.full(batch_size * vocab_size	,	self.filter_value						)

				UpperCAmelCase_     : str			     =					min(self.top_k	,	scores.shape[-1]						)  # Safety check
				UpperCAmelCase_     ,	UpperCAmelCase_     : Union[str, Any]			     =					lax.top_k(__UpperCAmelCase	,	__UpperCAmelCase						)
				UpperCAmelCase_     : int			     =					jnp.broadcast_to((jnp.arange(__UpperCAmelCase						) * vocab_size)[:, None]	,	(batch_size, topk)						).flatten()
				UpperCAmelCase_     : List[Any]			     =					topk_scores.flatten()
				UpperCAmelCase_     : str			     =					topk_indices.flatten() + shift

				UpperCAmelCase_     : Optional[Any]			     =					next_scores_flat.at[topk_indices_flat].set(__UpperCAmelCase						)
				UpperCAmelCase_     : Optional[int]			     =					next_scores_flat.reshape(__UpperCAmelCase	,	__UpperCAmelCase						)
				return next_scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: Optional[Any]	,	lowerCAmelCase_					: int						)						->			Tuple:
				UpperCAmelCase_     : Tuple			     =					bos_token_id





	def __call__(      self					: Optional[Any]	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int						)						->			jnp.ndarray:
				UpperCAmelCase_     : Union[str, Any]			     =					jnp.full(scores.shape	,	-float("inf"						)						)

				UpperCAmelCase_     : Optional[int]			     =					1 - jnp.bool_(cur_len - 1						)

				UpperCAmelCase_     : Tuple			     =					jnp.where(__UpperCAmelCase	,	new_scores.at[:, self.bos_token_id].set(0						)	,	__UpperCAmelCase						)

				return scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: List[Any]	,	lowerCAmelCase_					: int	,	lowerCAmelCase_					: int						)						->			Union[str, Any]:
				UpperCAmelCase_     : str			     =					max_length
				UpperCAmelCase_     : Tuple			     =					eos_token_id





	def __call__(      self					: Optional[int]	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int						)						->			jnp.ndarray:
				UpperCAmelCase_     : Any			     =					jnp.full(scores.shape	,	-float("inf"						)						)

				UpperCAmelCase_     : int			     =					1 - jnp.bool_(cur_len - self.max_length + 1						)

				UpperCAmelCase_     : List[str]			     =					jnp.where(__UpperCAmelCase	,	new_scores.at[:, self.eos_token_id].set(0						)	,	__UpperCAmelCase						)

				return scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: Optional[int]	,	lowerCAmelCase_					: int	,	lowerCAmelCase_					: int						)						->			Tuple:



				if not isinstance(__UpperCAmelCase	,	__UpperCAmelCase						) or min_length < 0:
							raise ValueError(f"""`min_length` has to be a positive integer, but is {min_length}"""						)

				if not isinstance(__UpperCAmelCase	,	__UpperCAmelCase						) or eos_token_id < 0:
							raise ValueError(f"""`eos_token_id` has to be a positive integer, but is {eos_token_id}"""						)

				UpperCAmelCase_     : int			     =					min_length
				UpperCAmelCase_     : int			     =					eos_token_id





	def __call__(      self					: Optional[int]	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int						)						->			jnp.ndarray:
				UpperCAmelCase_     : Tuple			     =					1 - jnp.clip(cur_len - self.min_length	,	0	,	1						)

				UpperCAmelCase_     : Optional[Any]			     =					jnp.where(__UpperCAmelCase	,	scores.at[:, self.eos_token_id].set(-float("inf"						)						)	,	__UpperCAmelCase						)

				return scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: Union[str, Any]	,	lowerCAmelCase_					: Dict	,	lowerCAmelCase_					: Tuple						)						->			List[str]:
				UpperCAmelCase_     : Optional[int]			     =					list(__UpperCAmelCase						)
				UpperCAmelCase_     : Optional[Any]			     =					begin_index





	def __call__(      self					: Any	,	lowerCAmelCase_					: List[Any]	,	lowerCAmelCase_					: Any	,	lowerCAmelCase_					: int						)						->			str:
				UpperCAmelCase_     : Union[str, Any]			     =					1 - jnp.bool_(cur_len - self.begin_index						)

				UpperCAmelCase_     : List[Any]			     =					jnp.where(__UpperCAmelCase	,	scores.at[:, self.begin_suppress_tokens].set(-float("inf"						)						)	,	__UpperCAmelCase						)

				return scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: List[Any]	,	lowerCAmelCase_					: list						)						->			str:
				UpperCAmelCase_     : List[str]			     =					list(__UpperCAmelCase						)





	def __call__(      self					: List[str]	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int						)						->			jnp.ndarray:
				UpperCAmelCase_     : Optional[int]			     =					scores.at[..., self.suppress_tokens].set(-float("inf"						)						)

				return scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: List[Any]	,	lowerCAmelCase_					: List[str]						)						->			Optional[int]:
				UpperCAmelCase_     : str			     =					dict(__UpperCAmelCase						)
				# Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
				# index of the array corresponds to the index of the token to be forced, for XLA compatibility.
				# Indexes without forced tokens will have a negative value.
				UpperCAmelCase_     : Tuple			     =					jnp.ones((max(force_token_map.keys()						) + 1)	,	dtype=jnp.intaa						) * -1
				for index, token in force_token_map.items():
							if token is not None:
										UpperCAmelCase_     : Union[str, Any]			     =					force_token_array.at[index].set(__UpperCAmelCase						)
				UpperCAmelCase_     : List[str]			     =					jnp.intaa(__UpperCAmelCase						)





	def __call__(      self					: List[str]	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: int						)						->			jnp.ndarray:



				def _force_token(lowerCAmelCase_					: List[Any]						):
							UpperCAmelCase_     : str			     =					scores.shape[0]
							UpperCAmelCase_     : List[Any]			     =					self.force_token_array[generation_idx]

							UpperCAmelCase_     : Any			     =					jnp.ones_like(__UpperCAmelCase	,	dtype=scores.dtype						) * -float("inf"						)
							UpperCAmelCase_     : List[Any]			     =					jnp.zeros((batch_size, 1)	,	dtype=scores.dtype						)
							UpperCAmelCase_     : Union[str, Any]			     =					lax.dynamic_update_slice(__UpperCAmelCase	,	__UpperCAmelCase	,	(0, current_token)						)
							return new_scores

				UpperCAmelCase_     : int			     =					lax.cond(
				    cur_len >= self.force_token_array.shape[0]	,	lambda: scores	,	lambda: lax.cond(
				        self.force_token_array[cur_len] >= 0	,	lambda: _force_token(__UpperCAmelCase						)	,	lambda: scores	,	)	,	)
				return scores







class 			UpperCamelCase_       (UpperCAmelCase_     ):





	def __init__(      self					: Any	,	lowerCAmelCase_					: Optional[Any]	,	lowerCAmelCase_					: List[Any]	,	lowerCAmelCase_					: int						)						->			Optional[int]:
				UpperCAmelCase_     : Optional[int]			     =					generate_config.eos_token_id
				UpperCAmelCase_     : Optional[int]			     =					generate_config.no_timestamps_token_id
				UpperCAmelCase_     : List[str]			     =					generate_config.no_timestamps_token_id + 1

				UpperCAmelCase_     : Optional[int]			     =					decoder_input_length + 1

				if generate_config.is_multilingual:
							# room for language token and task token
							self.begin_index += 2
				if hasattr(__UpperCAmelCase	,	"max_initial_timestamp_index"						):
							UpperCAmelCase_     : int			     =					generate_config.max_initial_timestamp_index
				else:
							UpperCAmelCase_     : Optional[int]			     =					model_config.vocab_size
				if self.max_initial_timestamp_index is None:
							UpperCAmelCase_     : Optional[Any]			     =					model_config.vocab_size





	def __call__(      self					: int	,	lowerCAmelCase_					: Any	,	lowerCAmelCase_					: Any	,	lowerCAmelCase_					: str						)						->			Union[str, Any]:
				UpperCAmelCase_     : Dict			     =					scores.at[:, self.no_timestamps_token_id].set(-float("inf"						)						)

				def handle_pairs(lowerCAmelCase_					: Any	,	lowerCAmelCase_					: Optional[int]						):
							UpperCAmelCase_     : Optional[int]			     =					jnp.where((cur_len - self.begin_index) >= 1	,	__UpperCAmelCase	,	__UpperCAmelCase						)
							UpperCAmelCase_     : int			     =					jnp.where(
							    input_ids_k[cur_len - 1] >= self.timestamp_begin	,	True and last_was_timestamp	,	__UpperCAmelCase	,	)

							UpperCAmelCase_     : Tuple			     =					jnp.where((cur_len - self.begin_index) < 2	,	__UpperCAmelCase	,	__UpperCAmelCase						)
							UpperCAmelCase_     : int			     =					jnp.where(
							    input_ids_k[cur_len - 2] >= self.timestamp_begin	,	__UpperCAmelCase	,	__UpperCAmelCase	,	)

							return jnp.where(
							    __UpperCAmelCase	,	jnp.where(
							        penultimate_was_timestamp > 0	,	scores_k.at[self.timestamp_begin :].set(-float("inf"						)						)	,	scores_k.at[: self.eos_token_id].set(-float("inf"						)						)	,	)	,	__UpperCAmelCase	,	)

				UpperCAmelCase_     : Optional[int]			     =					jax.vmap(__UpperCAmelCase						)(__UpperCAmelCase	,	__UpperCAmelCase						)

				UpperCAmelCase_     : List[str]			     =					jnp.where(cur_len == self.begin_index	,	__UpperCAmelCase	,	__UpperCAmelCase						)
				UpperCAmelCase_     : List[Any]			     =					jnp.where(
				    self.max_initial_timestamp_index is not None	,	True and apply_max_initial_timestamp	,	__UpperCAmelCase	,	)

				UpperCAmelCase_     : str			     =					self.timestamp_begin + self.max_initial_timestamp_index

				UpperCAmelCase_     : Dict			     =					jnp.where(
				    __UpperCAmelCase	,	scores.at[:, last_allowed + 1 :].set(-float("inf"						)						)	,	__UpperCAmelCase	,	)

				# if sum of probability over timestamps is above any other token, sample timestamp
				UpperCAmelCase_     : str			     =					jax.nn.log_softmax(__UpperCAmelCase	,	axis=-1						)

				def handle_cumulative_probs(lowerCAmelCase_					: int	,	lowerCAmelCase_					: Any						):
							UpperCAmelCase_     : Dict			     =					jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]	,	axis=-1						)
							UpperCAmelCase_     : Any			     =					jnp.max(logprobs_k[: self.timestamp_begin]						)
							return jnp.where(
							    timestamp_logprob > max_text_token_logprob	,	scores_k.at[: self.timestamp_begin].set(-float("inf"						)						)	,	__UpperCAmelCase	,	)

				UpperCAmelCase_     : Union[str, Any]			     =					jax.vmap(__UpperCAmelCase						)(__UpperCAmelCase	,	__UpperCAmelCase						)

				return scores




import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
      from sagemaker import Session, TrainingJobAnalytics
      from sagemaker.huggingface import HuggingFace





@pytest.mark.skipif(
    literal_eval(os.getenv('TEST_SAGEMAKER'		,				'False'     )     ) is not True		,				reason='Skipping test because should only be run when releasing minor transformers version'		,				)
@pytest.mark.usefixtures('sm_env'     )
@parameterized_class(
    [
        {
            'framework': 'pytorch',
            'script': 'run_glue.py',
            'model_name_or_path': 'distilbert-base-cased',
            'instance_type': 'ml.g4dn.xlarge',
            'results': {'train_runtime': 6_50, 'eval_accuracy': 0.6, 'eval_loss': 0.9},
        },
        {
            'framework': 'tensorflow',
            'script': 'run_tf.py',
            'model_name_or_path': 'distilbert-base-cased',
            'instance_type': 'ml.g4dn.xlarge',
            'results': {'train_runtime': 6_00, 'eval_accuracy': 0.3, 'eval_loss': 0.9},
        },
    ]     )
class      A							(				unittest.TestCase     ):


   def 			lowercase_      (self     :						int		)						->				Optional[Any]:
         """simple docstring"""



         if self.framework == "pytorch":
               subprocess.run(
                   f"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split()       ,  encoding="utf-8"       ,  check=__UpperCAmelCase       ,  )
         assert hasattr(self       ,  "env"		)


   def 			lowercase_      (self     :						List[Any]       ,  __UpperCAmelCase     :						Optional[int]=1		)						->				Dict:
         """simple docstring"""



         return HuggingFace(
             entry_point=self.script       ,  source_dir=self.env.test_path       ,  role=self.env.role       ,  image_uri=self.env.image_uri       ,  base_job_name=f"""{self.env.base_job_name}-single"""       ,  instance_count=__UpperCAmelCase       ,  instance_type=self.instance_type       ,  debugger_hook_config=__UpperCAmelCase       ,  hyperparameters={**self.env.hyperparameters, "model_name_or_path": self.model_name_or_path}       ,  metric_definitions=self.env.metric_definitions       ,  py_version="py36"       ,  )


   def 			lowercase_      (self     :						Optional[Any]       ,  __UpperCAmelCase     :						Tuple		)						->				Optional[int]:
         """simple docstring"""



         TrainingJobAnalytics(__UpperCAmelCase		).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv"""		)





   def 			lowercase_      (self     :						Any		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.create_estimator()

         # run training
         estimator.fit()

         # result dataframe
         UpperCAmelCase__								=  TrainingJobAnalytics(estimator.latest_training_job.name		).dataframe()

         # extract kpis
         UpperCAmelCase__								=  list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]		)
         UpperCAmelCase__								=  list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]		)
         # get train time from SageMaker job, this includes starting, preprocessing, stopping
         UpperCAmelCase__								=  (
             Session().describe_training_job(estimator.latest_training_job.name		).get("TrainingTimeInSeconds"       ,  9_9_9_9_9_9		)
         )

         # assert kpis
         assert train_runtime <= self.results["train_runtime"]
         assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy		)
         assert all(t <= self.results["eval_loss"] for t in eval_loss		)

         # dump tests result into json file to share in PR
         with open(f"""{estimator.latest_training_job.name}.json"""       ,  "w"		) as outfile:
               json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}       ,  __UpperCAmelCase		)



