





"""simple docstring"""





import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


lowerCAmelCase__     			=			logging.get_logger(__name__)


lowerCAmelCase__     			=			r'''
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

'''





class        _lowerCamelCase      (       _lowercase ):


						@add_start_docstrings(__a		)
						def __call__(self   ,							__a   ,							__a   ,							**__a		) ->   bool:
								raise NotImplementedError("StoppingCriteria needs to be subclassed"		)





class        _lowerCamelCase      (       _lowercase ):


						def __init__(self   ,							__a   ,							__a = None		) ->   Any:
								UpperCamelCase   =	max_length
								UpperCamelCase   =	max_position_embeddings




						@add_start_docstrings(__a		)
						def __call__(self   ,							__a   ,							__a   ,							**__a		) ->   bool:
								UpperCamelCase   =	input_ids.shape[-1]
								UpperCamelCase   =	cur_len >= self.max_length
								if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
										logger.warning_once(
										    "This is a friendly reminder - the current text generation call will exceed the model's predefined "
										    F"maximum length ({self.max_position_embeddings}). Depending on the model, you may observe "
										    "exceptions, performance degradation, or nothing at all."		)
								return is_done





class        _lowerCamelCase      (       _lowercase ):


						def __init__(self   ,							__a   ,							__a		) ->   List[Any]:
								warnings.warn(
								    "The class `MaxNewTokensCriteria` is deprecated. "
								    F"Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` "
								    "with `max_length = start_length + max_new_tokens` instead."   ,							__a   ,							)
								UpperCamelCase   =	start_length
								UpperCamelCase   =	max_new_tokens
								UpperCamelCase   =	start_length + max_new_tokens




						@add_start_docstrings(__a		)
						def __call__(self   ,							__a   ,							__a   ,							**__a		) ->   bool:
								return input_ids.shape[-1] >= self.max_length





class        _lowerCamelCase      (       _lowercase ):


						def __init__(self   ,							__a   ,							__a = None		) ->   Optional[Any]:
								UpperCamelCase   =	max_time
								UpperCamelCase   =	time.time() if initial_timestamp is None else initial_timestamp




						@add_start_docstrings(__a		)
						def __call__(self   ,							__a   ,							__a   ,							**__a		) ->   bool:
								return time.time() - self.initial_timestamp > self.max_time





class        _lowerCamelCase      (       _lowercase ):


						@add_start_docstrings(__a		)
						def __call__(self   ,							__a   ,							__a   ,							**__a		) ->   bool:
								return any(criteria(__a   ,							__a		) for criteria in self		)




						@property
						def     snake_case_   (self		) ->   Optional[int]:
								for stopping_criterium in self:
										if isinstance(__a   ,							__a		):
												return stopping_criterium.max_length
										elif isinstance(__a   ,							__a		):
												return stopping_criterium.max_length
								return None



def       a__					(					_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	stopping_criteria.max_length
		UpperCamelCase   =	deepcopy(_SCREAMING_SNAKE_CASE    )
		if stopping_max_length is not None and stopping_max_length != max_length:
				warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter"  ,	_SCREAMING_SNAKE_CASE    )
		elif stopping_max_length is None:
				new_stopping_criteria.append(MaxLengthCriteria(max_length=_SCREAMING_SNAKE_CASE    )    )
		return new_stopping_criteria













"""simple docstring"""





import importlib
import os
import sys


# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append('''.''')


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	test_file.split(os.path.sep    )
		if components[0:2] != ["tests", "models"]:
				raise ValueError(
				    "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got "
				    F"{test_file} instead."    )
		UpperCamelCase   =	components[-1]
		if not test_fn.endswith("py"    ):
				raise ValueError(F"`test_file` should be a python file. Got {test_fn} instead."    )
		if not test_fn.startswith("test_modeling_"    ):
				raise ValueError(
				    F"`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead."    )

		UpperCamelCase   =	components[:-1] + [test_fn.replace(".py"  ,	""    )]
		UpperCamelCase   =	".".join(_SCREAMING_SNAKE_CASE    )

		return test_module_path


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	get_module_path(_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   =	importlib.import_module(_SCREAMING_SNAKE_CASE    )

		return test_module


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	[]
		UpperCamelCase   =	get_test_module(_SCREAMING_SNAKE_CASE    )
		for attr in dir(_SCREAMING_SNAKE_CASE    ):
				if attr.endswith("ModelTester"    ):
						tester_classes.append(getattr(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    )    )

    # sort with class names
		return sorted(_SCREAMING_SNAKE_CASE  ,	key=lambda _SCREAMING_SNAKE_CASE    : x.__name__    )


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	[]
		UpperCamelCase   =	get_test_module(_SCREAMING_SNAKE_CASE    )
		for attr in dir(_SCREAMING_SNAKE_CASE    ):
				UpperCamelCase   =	getattr(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    )
				# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
				# `all_model_classes` is not empty (which also excludes other special classes).
				UpperCamelCase   =	getattr(_SCREAMING_SNAKE_CASE  ,	"all_model_classes"  ,	[]    )
				if len(_SCREAMING_SNAKE_CASE    ) > 0:
						test_classes.append(_SCREAMING_SNAKE_CASE    )

    # sort with class names
		return sorted(_SCREAMING_SNAKE_CASE  ,	key=lambda _SCREAMING_SNAKE_CASE    : x.__name__    )


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	get_test_classes(_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   =	set()
		for test_class in test_classes:
				model_classes.update(test_class.all_model_classes    )

		# sort with class names
		return sorted(_SCREAMING_SNAKE_CASE  ,	key=lambda _SCREAMING_SNAKE_CASE    : x.__name__    )


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	test_class()
		if hasattr(_SCREAMING_SNAKE_CASE  ,	"setUp"    ):
				test.setUp()

		UpperCamelCase   =	None
		if hasattr(_SCREAMING_SNAKE_CASE  ,	"model_tester"    ):
				# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
				if test.model_tester is not None:
						UpperCamelCase   =	test.model_tester.__class__

		return model_tester


def       a__					(					_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	get_test_classes(_SCREAMING_SNAKE_CASE    )

		UpperCamelCase   =	[]
		for test_class in test_classes:
				if model_class in test_class.all_model_classes:
						target_test_classes.append(_SCREAMING_SNAKE_CASE    )

    # sort with class names
		return sorted(_SCREAMING_SNAKE_CASE  ,	key=lambda _SCREAMING_SNAKE_CASE    : x.__name__    )


def       a__					(					_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	get_test_classes_for_model(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    )

		UpperCamelCase   =	[]
		for test_class in test_classes:
				UpperCamelCase   =	get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE    )
				if tester_class is not None:
						tester_classes.append(_SCREAMING_SNAKE_CASE    )

    # sort with class names
		return sorted(_SCREAMING_SNAKE_CASE  ,	key=lambda _SCREAMING_SNAKE_CASE    : x.__name__    )


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	get_test_classes(_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   =	{test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE    ) for test_class in test_classes}
		return test_tester_mapping


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	get_model_classes(_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   =	{
		    model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ) for model_class in model_classes
		}
		return model_test_mapping


def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		UpperCamelCase   =	get_model_classes(_SCREAMING_SNAKE_CASE    )
		UpperCamelCase   =	{
		    model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ) for model_class in model_classes
		}
		return model_to_tester_mapping






def       a__					(					_SCREAMING_SNAKE_CASE    ):




		"""simple docstring"""


		if isinstance(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):
				return o
		elif isinstance(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):
				return o.__name__
		elif isinstance(_SCREAMING_SNAKE_CASE  ,	(list, tuple)    ):
				return [to_json(_SCREAMING_SNAKE_CASE    ) for x in o]
		elif isinstance(_SCREAMING_SNAKE_CASE  ,	_SCREAMING_SNAKE_CASE    ):
				return {to_json(_SCREAMING_SNAKE_CASE    ): to_json(_SCREAMING_SNAKE_CASE    ) for k, v in o.items()}
		else:
				return o






