



"""simple docstring"""







import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
     import tensorflow as tf
     from tensorflow.python.framework.errors_impl import ResourceExhaustedError

     from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
     import pyanvml.pyanvml as nvml

lowercase__		:    str				   =     logging.get_logger(__name__)

def     UpperCamelCase_   (   lowerCAmelCase__				:    bool   ,       lowerCAmelCase__				:    bool						)						->       List[Any]:

  """simple docstring"""




  def run_func(lowerCAmelCase__				:    int						):
    @wraps(lowerCAmelCase__						)
    def run_in_eager_mode(*lowerCAmelCase__				:    List[Any]   ,       **lowerCAmelCase__				:    int						):
      return func(*lowerCAmelCase__   ,       **lowerCAmelCase__						)

    @wraps(lowerCAmelCase__						)
    @tf.function(experimental_compile=lowerCAmelCase__						)
    def run_in_graph_mode(*lowerCAmelCase__				:    Dict   ,       **lowerCAmelCase__				:    Any						):
      return func(*lowerCAmelCase__   ,       **lowerCAmelCase__						)

    if do_eager_mode is True:
      if use_xla is not False:
        raise ValueError(
            'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.'						)
      return run_in_eager_mode
    else:
      return run_in_graph_mode

  return run_func

def     UpperCamelCase_   (   lowerCAmelCase__				:    int   ,       lowerCAmelCase__				:    int   ,       lowerCAmelCase__				:    int						)						->       ["tf.Tensor"]:

  """simple docstring"""




  lowerCAmelCase_       :    Dict								=			random.Random()
  lowerCAmelCase_       :    List[str]								=			[rng.randint(0   ,       vocab_size - 1						) for i in range(batch_size * sequence_length						)]
  return tf.constant(lowerCAmelCase__   ,       shape=(batch_size, sequence_length)   ,       dtype=tf.intaa						)







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					42
      _SCREAMING_SNAKE_CASE      =					42
      _SCREAMING_SNAKE_CASE      =					"TensorFlow"



      @property
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        return tf.__version__



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        # initialize GPU on separate process
        lowerCAmelCase_       :    List[Any]								=			self.args.strategy
        if strategy is None:
          raise ValueError('A device strategy has to be initialized before using TensorFlow.'	)
        lowerCAmelCase_       :    List[str]								=			self._prepare_inference_func(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
        return self._measure_speed(_inference	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Optional[int]								=			self.args.strategy
        if strategy is None:
          raise ValueError('A device strategy has to be initialized before using TensorFlow.'	)
        lowerCAmelCase_       :    Any								=			self._prepare_train_func(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
        return self._measure_speed(_train	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        # initialize GPU on separate process
        if self.args.is_gpu:
          tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]   ,      SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Any								=			self.args.strategy
        if strategy is None:
          raise ValueError('A device strategy has to be initialized before using TensorFlow.'	)
        lowerCAmelCase_       :    Optional[Any]								=			self._prepare_inference_func(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
        return self._measure_memory(_inference	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if self.args.is_gpu:
          tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]   ,      SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Any								=			self.args.strategy
        if strategy is None:
          raise ValueError('A device strategy has to be initialized before using TensorFlow.'	)

        lowerCAmelCase_       :    Optional[int]								=			self._prepare_train_func(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
        return self._measure_memory(_train	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Any								=			self.config_dict[model_name]

        if self.args.fpaa:
          raise NotImplementedError('Mixed precision is currently not supported.'	)

        lowerCAmelCase_       :    Union[str, Any]								=			(
            hasattr(SCREAMING_SNAKE_CASE_   ,      'architectures'	)
            and isinstance(config.architectures   ,      SCREAMING_SNAKE_CASE_	)
            and len(config.architectures	) > 0
        )
        if not self.args.only_pretrain_model and has_model_class_in_config:
          try:
            lowerCAmelCase_       :    Any								=			'TF' + config.architectures[0]  # prepend 'TF' for tensorflow model
            lowerCAmelCase_       :    Any								=			__import__('transformers'   ,      fromlist=[model_class]	)
            lowerCAmelCase_       :    Dict								=			getattr(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
            lowerCAmelCase_       :    List[str]								=			model_cls(SCREAMING_SNAKE_CASE_	)
          except ImportError:
            raise ImportError(
                F"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
                ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'	)
        else:
          lowerCAmelCase_       :    str								=			TF_MODEL_MAPPING[config.__class__](SCREAMING_SNAKE_CASE_	)

        # encoder-decoder has vocab size saved differently
        lowerCAmelCase_       :    List[Any]								=			config.vocab_size if hasattr(SCREAMING_SNAKE_CASE_   ,      'vocab_size'	) else config.encoder.vocab_size
        lowerCAmelCase_       :    Tuple								=			random_input_ids(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)

        @run_with_tf_optimizations(self.args.eager_mode   ,      self.args.use_xla	)
        def encoder_decoder_forward():
          return model(SCREAMING_SNAKE_CASE_   ,      decoder_input_ids=SCREAMING_SNAKE_CASE_   ,      training=SCREAMING_SNAKE_CASE_	)

        @run_with_tf_optimizations(self.args.eager_mode   ,      self.args.use_xla	)
        def encoder_forward():
          return model(SCREAMING_SNAKE_CASE_   ,      training=SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    List[Any]								=			encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

        return _inference



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Union[str, Any]								=			self.config_dict[model_name]

        if self.args.eager_mode is not False:
          raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.'	)

        if self.args.fpaa:
          raise NotImplementedError('Mixed precision is currently not supported.'	)

        lowerCAmelCase_       :    Dict								=			(
            hasattr(SCREAMING_SNAKE_CASE_   ,      'architectures'	)
            and isinstance(config.architectures   ,      SCREAMING_SNAKE_CASE_	)
            and len(config.architectures	) > 0
        )
        if not self.args.only_pretrain_model and has_model_class_in_config:
          try:
            lowerCAmelCase_       :    Optional[Any]								=			'TF' + config.architectures[0]  # prepend 'TF' for tensorflow model
            lowerCAmelCase_       :    int								=			__import__('transformers'   ,      fromlist=[model_class]	)
            lowerCAmelCase_       :    Any								=			getattr(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
            lowerCAmelCase_       :    Optional[Any]								=			model_cls(SCREAMING_SNAKE_CASE_	)
          except ImportError:
            raise ImportError(
                F"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
                ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'	)
        else:
          lowerCAmelCase_       :    Union[str, Any]								=			TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](SCREAMING_SNAKE_CASE_	)

        # encoder-decoder has vocab size saved differently
        lowerCAmelCase_       :    int								=			config.vocab_size if hasattr(SCREAMING_SNAKE_CASE_   ,      'vocab_size'	) else config.encoder.vocab_size
        lowerCAmelCase_       :    Optional[Any]								=			random_input_ids(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)

        @run_with_tf_optimizations(self.args.eager_mode   ,      self.args.use_xla	)
        def encoder_decoder_train():
          lowerCAmelCase_       :    str								=			model(SCREAMING_SNAKE_CASE_   ,      decoder_input_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_   ,      training=SCREAMING_SNAKE_CASE_	)[0]
          lowerCAmelCase_       :    Optional[int]								=			tf.gradients(SCREAMING_SNAKE_CASE_   ,      model.trainable_variables	)
          return gradients

        @run_with_tf_optimizations(self.args.eager_mode   ,      self.args.use_xla	)
        def encoder_train():
          lowerCAmelCase_       :    Dict								=			model(SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_   ,      training=SCREAMING_SNAKE_CASE_	)[0]
          lowerCAmelCase_       :    str								=			tf.gradients(SCREAMING_SNAKE_CASE_   ,      model.trainable_variables	)
          return gradients

        lowerCAmelCase_       :    int								=			encoder_decoder_train if config.is_encoder_decoder else encoder_train

        return _train



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Tuple	):
        with self.args.strategy.scope():
          try:
            if self.args.is_tpu or self.args.use_xla:
              # run additional 10 times to stabilize compilation for tpu
              logger.info('Do inference on TPU. Running model 5 times to stabilize compilation'	)
              timeit.repeat(SCREAMING_SNAKE_CASE_   ,      repeat=1   ,      number=5	)

            # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
            lowerCAmelCase_       :    Dict								=			timeit.repeat(
                SCREAMING_SNAKE_CASE_   ,      repeat=self.args.repeat   ,      number=1_0   ,      )

            return min(SCREAMING_SNAKE_CASE_	) / 10.0
          except ResourceExhaustedError as e:
            self.print_fn(F"Doesn't fit on GPU. {e}"	)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Callable[[], None]	):
        logger.info(
            'Note that TensorFlow allocates more memory than '
            'it might need to speed up computation. '
            'The memory reported here corresponds to the memory '
            'reported by `nvidia-smi`, which can vary depending '
            'on total available memory on the GPU that is used.'	)
        with self.args.strategy.scope():
          try:
            if self.args.trace_memory_line_by_line:
              if not self.args.eager_mode:
                raise ValueError(
                    '`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory'
                    ' consumption line by line.'	)
              lowerCAmelCase_       :    Union[str, Any]								=			start_memory_tracing('transformers'	)

            if self.args.is_tpu:
              # tpu
              raise NotImplementedError(
                  'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking'
                  ' with `args.memory=False`'	)
            elif self.args.is_gpu:
              # gpu
              if not is_pyanvml_available():
                logger.warning(
                    'py3nvml not installed, we won\'t log GPU memory usage. '
                    'Install py3nvml (pip install py3nvml) to log information about GPU.'	)
                lowerCAmelCase_       :    Tuple								=			'N/A'
              else:
                logger.info(
                    'Measuring total GPU usage on GPU device. Make sure to not have additional processes'
                    ' running on the same GPU.'	)
                # init nvml
                nvml.nvmlInit()
                func()
                lowerCAmelCase_       :    int								=			nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx	)
                lowerCAmelCase_       :    Union[str, Any]								=			nvml.nvmlDeviceGetMemoryInfo(SCREAMING_SNAKE_CASE_	)
                lowerCAmelCase_       :    List[Any]								=			meminfo.used
                lowerCAmelCase_       :    int								=			Memory(SCREAMING_SNAKE_CASE_	)
                # shutdown nvml
                nvml.nvmlShutdown()
            else:
              # cpu
              if self.args.trace_memory_line_by_line:
                logger.info(
                    'When enabling line by line tracing, the max peak memory for CPU is inaccurate in'
                    ' TensorFlow.'	)
                lowerCAmelCase_       :    Optional[int]								=			None
              else:
                lowerCAmelCase_       :    Union[str, Any]								=			measure_peak_memory_cpu(SCREAMING_SNAKE_CASE_	)
                lowerCAmelCase_       :    Any								=			Memory(SCREAMING_SNAKE_CASE_	) if isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) else memory_bytes
            if self.args.trace_memory_line_by_line:
              lowerCAmelCase_       :    List[Any]								=			stop_memory_tracing(SCREAMING_SNAKE_CASE_	)
              if memory is None:
                lowerCAmelCase_       :    Union[str, Any]								=			summary.total
            else:
              lowerCAmelCase_       :    List[str]								=			None

            return memory, summary
          except ResourceExhaustedError as e:
            self.print_fn(F"Doesn't fit on GPU. {e}"	)
            return "N/A", None










"""simple docstring"""







from abc import ABC, abstractmethod
from typing import List, Optional







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				int	):
        # test for the above condition
        self.test()



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        lowerCAmelCase_       :    Any								=			0
        lowerCAmelCase_       :    Optional[Any]								=			False
        while not completed:
          if counter == 1:
            self.reset()
          lowerCAmelCase_       :    Any								=			self.advance()
          if not self.does_advance(SCREAMING_SNAKE_CASE_	):
            raise Exception(
                'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'	)

          lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    List[str]								=			self.update(SCREAMING_SNAKE_CASE_	)
          counter += 1

          if counter > 1_0_0_0_0:
            raise Exception('update() does not fulfill the constraint.'	)

        if self.remaining() != 0:
          raise Exception('Custom Constraint is not defined correctly.'	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				int	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)



      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)





      @abstractmethod
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=False	):
        raise NotImplementedError(
            F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."	)







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				List[int]	):
        super(SCREAMING_SNAKE_CASE_   ,      self	).__init__()

        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or len(SCREAMING_SNAKE_CASE_	) == 0:
          raise ValueError(F"`token_ids` has to be a non-empty list, but is {token_ids}."	)
        if any((not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or token_id < 0) for token_id in token_ids	):
          raise ValueError(F"Each list in `token_ids` has to be a list of positive integers, but is {token_ids}."	)

        lowerCAmelCase_       :    Union[str, Any]								=			token_ids

        lowerCAmelCase_       :    Union[str, Any]								=			len(self.token_ids	)
        lowerCAmelCase_       :    Union[str, Any]								=			-1  # the index of the currently fulfilled step
        lowerCAmelCase_       :    Dict								=			False



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int	):
        if self.completed:
          return None
        return self.token_ids[self.fulfilled_idx + 1]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        if self.completed:
          return False

        return token_id == self.token_ids[self.fulfilled_idx + 1]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        lowerCAmelCase_       :    List[Any]								=			False
        lowerCAmelCase_       :    Optional[int]								=			False
        lowerCAmelCase_       :    Union[str, Any]								=			False

        if self.does_advance(SCREAMING_SNAKE_CASE_	):
          self.fulfilled_idx += 1
          lowerCAmelCase_       :    Optional[int]								=			True
          if self.fulfilled_idx == (self.seqlen - 1):
            lowerCAmelCase_       :    List[str]								=			True
          lowerCAmelCase_       :    List[str]								=			completed
        else:
          # failed to make progress.
          lowerCAmelCase_       :    Optional[Any]								=			True
          self.reset()
        return stepped, completed, reset



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Optional[int]								=			False
        lowerCAmelCase_       :    int								=			0



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        return self.seqlen - (self.fulfilled_idx + 1)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple=False	):
        lowerCAmelCase_       :    Any								=			PhrasalConstraint(self.token_ids	)

        if stateful:
          lowerCAmelCase_       :    int								=			self.seqlen
          lowerCAmelCase_       :    Dict								=			self.fulfilled_idx
          lowerCAmelCase_       :    Optional[Any]								=			self.completed

        return new_constraint







class 				UpperCamelCase__       :




      """simple docstring"""




      def __init__(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[List[int]]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=True	):
        lowerCAmelCase_       :    Tuple								=			max([len(SCREAMING_SNAKE_CASE_	) for one in nested_token_ids]	)

        lowerCAmelCase_       :    Optional[Any]								=			{}
        for token_ids in nested_token_ids:
          lowerCAmelCase_       :    Union[str, Any]								=			root
          for tidx, token_id in enumerate(SCREAMING_SNAKE_CASE_	):
            if token_id not in level:
              lowerCAmelCase_       :    Dict								=			{}

            lowerCAmelCase_       :    Tuple								=			level[token_id]

        if no_subsets and self.has_subsets(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(
              'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'
              F" {nested_token_ids}."	)

        lowerCAmelCase_       :    Union[str, Any]								=			root



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Any	):
        lowerCAmelCase_       :    str								=			self.trie

        for current_token in current_seq:
          lowerCAmelCase_       :    Optional[int]								=			start[current_token]

        lowerCAmelCase_       :    Dict								=			list(start.keys()	)

        return next_tokens



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str   ,      SCREAMING_SNAKE_CASE_    :				Any	):
        lowerCAmelCase_       :    Any								=			self.next_tokens(SCREAMING_SNAKE_CASE_	)

        return len(SCREAMING_SNAKE_CASE_	) == 0



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    Tuple								=			list(root.values()	)
        if len(SCREAMING_SNAKE_CASE_	) == 0:
          return 1
        else:
          return sum([self.count_leaves(SCREAMING_SNAKE_CASE_	) for nn in next_nodes]	)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]	):
        lowerCAmelCase_       :    Any								=			self.count_leaves(SCREAMING_SNAKE_CASE_	)
        return len(SCREAMING_SNAKE_CASE_	) != leaf_count







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[List[int]]	):
        super(SCREAMING_SNAKE_CASE_   ,      self	).__init__()

        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or len(SCREAMING_SNAKE_CASE_	) == 0:
          raise ValueError(F"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."	)
        if any(not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) for token_ids in nested_token_ids	):
          raise ValueError(F"`nested_token_ids` has to be a list of lists, but is {nested_token_ids}."	)
        if any(
            any((not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	) or token_id < 0) for token_id in token_ids	)
            for token_ids in nested_token_ids	):
          raise ValueError(
              F"Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}."	)

        lowerCAmelCase_       :    Dict								=			DisjunctiveTrie(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Optional[int]								=			nested_token_ids

        lowerCAmelCase_       :    Tuple								=			self.trie.max_height
        lowerCAmelCase_       :    Union[str, Any]								=			[]
        lowerCAmelCase_       :    Optional[Any]								=			False



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
        lowerCAmelCase_       :    int								=			self.trie.next_tokens(self.current_seq	)

        if len(SCREAMING_SNAKE_CASE_	) == 0:
          return None
        else:
          return token_list



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        lowerCAmelCase_       :    Optional[int]								=			self.trie.next_tokens(self.current_seq	)

        return token_id in next_tokens



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE_	)}"	)

        lowerCAmelCase_       :    int								=			False
        lowerCAmelCase_       :    Dict								=			False
        lowerCAmelCase_       :    Optional[Any]								=			False

        if self.does_advance(SCREAMING_SNAKE_CASE_	):
          self.current_seq.append(SCREAMING_SNAKE_CASE_	)
          lowerCAmelCase_       :    List[Any]								=			True
        else:
          lowerCAmelCase_       :    List[str]								=			True
          self.reset()

        lowerCAmelCase_       :    Dict								=			self.trie.reached_leaf(self.current_seq	)
        lowerCAmelCase_       :    List[str]								=			completed

        return stepped, completed, reset



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    int								=			False
        lowerCAmelCase_       :    Optional[Any]								=			[]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        if self.completed:
          # since this can be completed without reaching max height
          return 0
        else:
          return self.seqlen - len(self.current_seq	)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Dict=False	):
        lowerCAmelCase_       :    Dict								=			DisjunctiveConstraint(self.token_ids	)

        if stateful:
          lowerCAmelCase_       :    Dict								=			self.seqlen
          lowerCAmelCase_       :    Optional[Any]								=			self.current_seq
          lowerCAmelCase_       :    List[Any]								=			self.completed

        return new_constraint







class 				UpperCamelCase__       :




      """simple docstring"""




      def __init__(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				List[Constraint]	):
        lowerCAmelCase_       :    Optional[int]								=			constraints

        # max # of steps required to fulfill a given constraint
        lowerCAmelCase_       :    Optional[int]								=			max([c.seqlen for c in constraints]	)
        lowerCAmelCase_       :    List[str]								=			len(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    List[str]								=			False

        self.init_state()



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Tuple								=			[]
        lowerCAmelCase_       :    int								=			None
        lowerCAmelCase_       :    Optional[int]								=			[constraint.copy(stateful=SCREAMING_SNAKE_CASE_	) for constraint in self.constraints]



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int	):
        lowerCAmelCase_       :    Optional[Any]								=			0
        if self.inprogress_constraint:
          # extra points for having a constraint mid-fulfilled
          add += self.max_seqlen - self.inprogress_constraint.remaining()

        return (len(self.complete_constraints	) * self.max_seqlen) + add



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
        lowerCAmelCase_       :    List[str]								=			[]
        if self.inprogress_constraint is None:
          for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
            lowerCAmelCase_       :    List[Any]								=			constraint.advance()
            if isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
              token_list.append(SCREAMING_SNAKE_CASE_	)
            elif isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
              token_list.extend(SCREAMING_SNAKE_CASE_	)
        else:
          lowerCAmelCase_       :    Dict								=			self.inprogress_constraint.advance()
          if isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
            token_list.append(SCREAMING_SNAKE_CASE_	)
          elif isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
            token_list.extend(SCREAMING_SNAKE_CASE_	)

        if len(SCREAMING_SNAKE_CASE_	) == 0:
          return None
        else:
          return token_list



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[List[int]]	):
        self.init_state()

        if token_ids is not None:
          for token in token_ids:
            # completes or steps **one** constraint
            lowerCAmelCase_						,lowerCAmelCase_       :    Union[str, Any]								=			self.add(SCREAMING_SNAKE_CASE_	)

            # the entire list of constraints are fulfilled
            if self.completed:
              break



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int	):
        if not isinstance(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	):
          raise ValueError(F"`token_id` should be an `int`, but is `{token_id}`."	)

        lowerCAmelCase_						,lowerCAmelCase_       :    Tuple								=			False, False

        if self.completed:
          lowerCAmelCase_       :    Any								=			True
          lowerCAmelCase_       :    Dict								=			False
          return complete, stepped

        if self.inprogress_constraint is not None:
          # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
          # job, simply update the state

          lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    Any								=			self.inprogress_constraint.update(SCREAMING_SNAKE_CASE_	)
          if reset:
            # 1. If the next token breaks the progress, then we must restart.
            #     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

            #     But that doesn't mean we self.init_state(), since we only reset the state for this particular
            #     constraint, not the full list of constraints.

            self.pending_constraints.append(self.inprogress_constraint.copy(stateful=SCREAMING_SNAKE_CASE_	)	)
            lowerCAmelCase_       :    Optional[int]								=			None

          if complete:
            # 2. If the next token completes the constraint, move it to completed list, set
            #     inprogress to None. If there are no pending constraints either, then this full list of constraints
            #     is complete.

            self.complete_constraints.append(self.inprogress_constraint	)
            lowerCAmelCase_       :    str								=			None

            if len(self.pending_constraints	) == 0:
              # we're done!
              lowerCAmelCase_       :    Union[str, Any]								=			True

        else:
          # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
          # of constraints?

          for cidx, pending_constraint in enumerate(self.pending_constraints	):
            if pending_constraint.does_advance(SCREAMING_SNAKE_CASE_	):
              lowerCAmelCase_						,lowerCAmelCase_						,lowerCAmelCase_       :    str								=			pending_constraint.update(SCREAMING_SNAKE_CASE_	)

              if not stepped:
                raise Exception(
                    '`constraint.update(token_id)` is not yielding incremental progress, '
                    'even though `constraint.does_advance(token_id)` is true.'	)

              if complete:
                self.complete_constraints.append(SCREAMING_SNAKE_CASE_	)
                lowerCAmelCase_       :    Any								=			None

              if not complete and stepped:
                lowerCAmelCase_       :    Optional[Any]								=			pending_constraint

              if complete or stepped:
                # If we made any progress at all, then it's at least not a "pending constraint".

                lowerCAmelCase_       :    Optional[int]								=			(
                    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
                )

                if len(self.pending_constraints	) == 0 and self.inprogress_constraint is None:
                  # If there's no longer any pending after this and no inprogress either, then we must be
                  # complete.

                  lowerCAmelCase_       :    Optional[Any]								=			True

                break  # prevent accidentally stepping through multiple constraints with just one token.

        return complete, stepped





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				str=True	):
        lowerCAmelCase_       :    List[Any]								=			ConstraintListState(self.constraints	)  # we actually never though self.constraints objects
        # throughout this process. So it's at initialization state.

        if stateful:
          lowerCAmelCase_       :    Any								=			[
              constraint.copy(stateful=SCREAMING_SNAKE_CASE_	) for constraint in self.complete_constraints
          ]
          if self.inprogress_constraint is not None:
            lowerCAmelCase_       :    List[str]								=			self.inprogress_constraint.copy(stateful=SCREAMING_SNAKE_CASE_	)
          lowerCAmelCase_       :    List[Any]								=			[constraint.copy() for constraint in self.pending_constraints]

        return new_state





