

"""simple docstring"""




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







class   __lowercase      (     __lowerCamelCase       ):

  def __init__(	self		:      Tuple     ):






   '''simple docstring'''
   # test for the above condition
   self.test()

  def  __lowercase							(	self		:      Optional[int]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	List[Any]        =       0
   UpperCAmelCase__       :	List[str]        =       False
   while not completed:
    if counter == 1:
     self.reset()
    UpperCAmelCase__       :	List[str]        =       self.advance()
    if not self.does_advance(A     ):
     raise Exception(
         """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."""     )

    UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	int        =       self.update(A     )
    counter += 1

    if counter > 10_000:
     raise Exception("""update() does not fulfill the constraint."""     )

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

  @abstractmethod
  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."     )

  @abstractmethod
  def  __lowercase							(	self		:      str       ,A		:      int     ):






   '''simple docstring'''
   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."     )

  @abstractmethod
  def  __lowercase							(	self		:      Optional[Any]       ,A		:      int     ):






   '''simple docstring'''
   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."     )

  @abstractmethod
  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."     )

  @abstractmethod
  def  __lowercase							(	self		:      Any     ):






   '''simple docstring'''
   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."     )




  @abstractmethod
  def  __lowercase							(	self		:      str       ,A		:      Optional[int]=False     ):






   '''simple docstring'''
   raise NotImplementedError(
       f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."     )







class   __lowercase      (     __lowerCamelCase       ):

  def __init__(	self		:      List[str]       ,A		:      List[int]     ):






   '''simple docstring'''
   super(A       ,self     ).__init__()

   if not isinstance(A       ,A     ) or len(A     ) == 0:
    raise ValueError(f"`token_ids` has to be a non-empty list, but is {token_ids}."     )
   if any((not isinstance(A       ,A     ) 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}."     )

   UpperCAmelCase__       :	Optional[int]        =       token_ids

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

  def  __lowercase							(	self		:      Dict     ):






   '''simple docstring'''
   if self.completed:
    return None
   return self.token_ids[self.fulfilled_idx + 1]

  def  __lowercase							(	self		:      Optional[Any]       ,A		:      int     ):






   '''simple docstring'''
   if not isinstance(A       ,A     ):
    raise ValueError(f"`token_id` has to be an `int`, but is {token_id} of type {type(A     )}"     )

   if self.completed:
    return False

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

  def  __lowercase							(	self		:      str       ,A		:      int     ):






   '''simple docstring'''
   if not isinstance(A       ,A     ):
    raise ValueError(f"`token_id` has to be an `int`, but is {token_id} of type {type(A     )}"     )

   UpperCAmelCase__       :	Union[str, Any]        =       False
   UpperCAmelCase__       :	Dict        =       False
   UpperCAmelCase__       :	Union[str, Any]        =       False

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

  def  __lowercase							(	self		:      Union[str, Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	List[Any]        =       False
   UpperCAmelCase__       :	Optional[Any]        =       0

  def  __lowercase							(	self		:      Optional[int]     ):






   '''simple docstring'''
   return self.seqlen - (self.fulfilled_idx + 1)




  def  __lowercase							(	self		:      List[str]       ,A		:      List[str]=False     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Any        =       PhrasalConstraint(self.token_ids     )

   if stateful:
    UpperCAmelCase__       :	int        =       self.seqlen
    UpperCAmelCase__       :	Optional[int]        =       self.fulfilled_idx
    UpperCAmelCase__       :	int        =       self.completed

   return new_constraint







class   __lowercase      :

  def __init__(	self		:      Dict       ,A		:      List[List[int]]       ,A		:      Tuple=True     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       max([len(A     ) for one in nested_token_ids]     )

   UpperCAmelCase__       :	List[Any]        =       {}
   for token_ids in nested_token_ids:
    UpperCAmelCase__       :	Tuple        =       root
    for tidx, token_id in enumerate(A     ):
     if token_id not in level:
      UpperCAmelCase__       :	Dict        =       {}

     UpperCAmelCase__       :	Optional[Any]        =       level[token_id]

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

   UpperCAmelCase__       :	int        =       root

  def  __lowercase							(	self		:      List[str]       ,A		:      Any     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[Any]        =       self.trie

   for current_token in current_seq:
    UpperCAmelCase__       :	int        =       start[current_token]

   UpperCAmelCase__       :	str        =       list(start.keys()     )

   return next_tokens

  def  __lowercase							(	self		:      List[str]       ,A		:      Optional[int]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       self.next_tokens(A     )

   return len(A     ) == 0

  def  __lowercase							(	self		:      Union[str, Any]       ,A		:      List[str]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       list(root.values()     )
   if len(A     ) == 0:
    return 1
   else:
    return sum([self.count_leaves(A     ) for nn in next_nodes]     )




  def  __lowercase							(	self		:      Optional[Any]       ,A		:      List[Any]       ,A		:      List[str]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	int        =       self.count_leaves(A     )
   return len(A     ) != leaf_count







class   __lowercase      (     __lowerCamelCase       ):

  def __init__(	self		:      str       ,A		:      List[List[int]]     ):






   '''simple docstring'''
   super(A       ,self     ).__init__()

   if not isinstance(A       ,A     ) or len(A     ) == 0:
    raise ValueError(f"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."     )
   if any(not isinstance(A       ,A     ) 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(A       ,A     ) 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}."     )

   UpperCAmelCase__       :	List[Any]        =       DisjunctiveTrie(A     )
   UpperCAmelCase__       :	Dict        =       nested_token_ids

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

  def  __lowercase							(	self		:      List[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	List[str]        =       self.trie.next_tokens(self.current_seq     )

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

  def  __lowercase							(	self		:      Union[str, Any]       ,A		:      int     ):






   '''simple docstring'''
   if not isinstance(A       ,A     ):
    raise ValueError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(A     )}"     )

   UpperCAmelCase__       :	List[Any]        =       self.trie.next_tokens(self.current_seq     )

   return token_id in next_tokens

  def  __lowercase							(	self		:      Dict       ,A		:      int     ):






   '''simple docstring'''
   if not isinstance(A       ,A     ):
    raise ValueError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(A     )}"     )

   UpperCAmelCase__       :	List[Any]        =       False
   UpperCAmelCase__       :	List[str]        =       False
   UpperCAmelCase__       :	Optional[Any]        =       False

   if self.does_advance(A     ):
    self.current_seq.append(A     )
    UpperCAmelCase__       :	Dict        =       True
   else:
    UpperCAmelCase__       :	Optional[int]        =       True
    self.reset()

   UpperCAmelCase__       :	Optional[Any]        =       self.trie.reached_leaf(self.current_seq     )
   UpperCAmelCase__       :	int        =       completed

   return stepped, completed, reset

  def  __lowercase							(	self		:      List[Any]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       False
   UpperCAmelCase__       :	List[str]        =       []

  def  __lowercase							(	self		:      int     ):






   '''simple docstring'''
   if self.completed:
    # since this can be completed without reaching max height
    return 0
   else:
    return self.seqlen - len(self.current_seq     )




  def  __lowercase							(	self		:      Optional[int]       ,A		:      Optional[int]=False     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Optional[int]        =       DisjunctiveConstraint(self.token_ids     )

   if stateful:
    UpperCAmelCase__       :	Optional[int]        =       self.seqlen
    UpperCAmelCase__       :	Tuple        =       self.current_seq
    UpperCAmelCase__       :	List[str]        =       self.completed

   return new_constraint







class   __lowercase      :

  def __init__(	self		:      List[str]       ,A		:      List[Constraint]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	str        =       constraints

   # max # of steps required to fulfill a given constraint
   UpperCAmelCase__       :	List[str]        =       max([c.seqlen for c in constraints]     )
   UpperCAmelCase__       :	Any        =       len(A     )
   UpperCAmelCase__       :	List[Any]        =       False

   self.init_state()

  def  __lowercase							(	self		:      Tuple     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       []
   UpperCAmelCase__       :	Optional[Any]        =       None
   UpperCAmelCase__       :	Dict        =       [constraint.copy(stateful=A     ) for constraint in self.constraints]

  def  __lowercase							(	self		:      List[str]     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Tuple        =       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  __lowercase							(	self		:      Tuple     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       []
   if self.inprogress_constraint is None:
    for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
     UpperCAmelCase__       :	str        =       constraint.advance()
     if isinstance(A       ,A     ):
      token_list.append(A     )
     elif isinstance(A       ,A     ):
      token_list.extend(A     )
   else:
    UpperCAmelCase__       :	List[Any]        =       self.inprogress_constraint.advance()
    if isinstance(A       ,A     ):
     token_list.append(A     )
    elif isinstance(A       ,A     ):
     token_list.extend(A     )

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

  def  __lowercase							(	self		:      Dict       ,A		:      Optional[List[int]]     ):






   '''simple docstring'''
   self.init_state()

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

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

  def  __lowercase							(	self		:      Tuple       ,A		:      int     ):






   '''simple docstring'''
   if not isinstance(A       ,A     ):
    raise ValueError(f"`token_id` should be an `int`, but is `{token_id}`."     )

   UpperCAmelCase__ ,   UpperCAmelCase__       :	int        =       False, False

   if self.completed:
    UpperCAmelCase__       :	Dict        =       True
    UpperCAmelCase__       :	Optional[Any]        =       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

    UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	Tuple        =       self.inprogress_constraint.update(A     )
    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=A     )     )
     UpperCAmelCase__       :	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     )
     UpperCAmelCase__       :	Optional[Any]        =       None

     if len(self.pending_constraints     ) == 0:
      # we're done!
      UpperCAmelCase__       :	Optional[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(A     ):
      UpperCAmelCase__ ,   UpperCAmelCase__ ,   UpperCAmelCase__       :	str        =       pending_constraint.update(A     )

      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(A     )
       UpperCAmelCase__       :	str        =       None

      if not complete and stepped:
       UpperCAmelCase__       :	List[str]        =       pending_constraint

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

       UpperCAmelCase__       :	Any        =       (
           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.

        UpperCAmelCase__       :	Tuple        =       True

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

   return complete, stepped




  def  __lowercase							(	self		:      Any       ,A		:      Optional[int]=True     ):






   '''simple docstring'''
   UpperCAmelCase__       :	Union[str, Any]        =       ConstraintListState(self.constraints     )  # we actually never though self.constraints objects
   # throughout this process. So it's at initialization state.

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

   return new_state










from typing import Callable, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCamelCase    :		int		      =    logging.get_logger(__name__)

_lowerCamelCase    :		Union[str, Any]		      =    {
    """microsoft/xprophetnet-large-wiki100-cased""": (
        """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json"""
    ),
}


class 						lowercase    (							SCREAMING_SNAKE_CASE_):
						'''simple docstring'''


						UpperCAmelCase			:		Tuple		=		'xlm-prophetnet'
						UpperCAmelCase			:		int		=		['past_key_values']
						UpperCAmelCase			:		List[Any]		=		{
						    'num_attention_heads': 'num_encoder_attention_heads',
						}







						def __init__(  self    :				List[Any]       ,	snake_case    :				Optional[float] = 0.1       ,	snake_case    :				Optional[Union[str, Callable]] = "gelu"       ,	snake_case    :				Optional[int] = 30522       ,	snake_case    :				Optional[int] = 1024       ,	snake_case    :				Optional[int] = 4096       ,	snake_case    :				Optional[int] = 12       ,	snake_case    :				Optional[int] = 16       ,	snake_case    :				Optional[int] = 4096       ,	snake_case    :				Optional[int] = 12       ,	snake_case    :				Optional[int] = 16       ,	snake_case    :				Optional[float] = 0.1       ,	snake_case    :				Optional[float] = 0.1       ,	snake_case    :				Optional[int] = 512       ,	snake_case    :				Optional[float] = 0.02       ,	snake_case    :				Optional[bool] = True       ,	snake_case    :				Optional[bool] = True       ,	snake_case    :				Optional[int] = 0       ,	snake_case    :				Optional[int] = 2       ,	snake_case    :				Optional[int] = 32       ,	snake_case    :				Optional[int] = 128       ,	snake_case    :				Optional[bool] = False       ,	snake_case    :				Optional[float] = 0.0       ,	snake_case    :				Optional[bool] = True       ,	snake_case    :				Optional[int] = 0       ,	snake_case    :				Optional[int] = 1       ,	snake_case    :				Optional[int] = 2       ,	**snake_case    :				Optional[int]       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				vocab_size
											SCREAMING_SNAKE_CASE							:     int						=				hidden_size
											SCREAMING_SNAKE_CASE							:     Dict						=				encoder_ffn_dim
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				num_encoder_layers
											SCREAMING_SNAKE_CASE							:     str						=				num_encoder_attention_heads
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				decoder_ffn_dim
											SCREAMING_SNAKE_CASE							:     Any						=				num_decoder_layers
											SCREAMING_SNAKE_CASE							:     List[str]						=				num_decoder_attention_heads
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				max_position_embeddings
											SCREAMING_SNAKE_CASE							:     Any						=				init_std  # Normal(0, this parameter)
											SCREAMING_SNAKE_CASE							:     List[str]						=				activation_function

											# parameters for xlmprophetnet
											SCREAMING_SNAKE_CASE							:     Tuple						=				ngram
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				num_buckets
											SCREAMING_SNAKE_CASE							:     Any						=				relative_max_distance
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				disable_ngram_loss
											SCREAMING_SNAKE_CASE							:     List[str]						=				eps

											# 3 Types of Dropout
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				attention_dropout
											SCREAMING_SNAKE_CASE							:     Any						=				activation_dropout
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				dropout

											SCREAMING_SNAKE_CASE							:     Tuple						=				use_cache

											super().__init__(
											    pad_token_id=snake_case       ,	bos_token_id=snake_case       ,	eos_token_id=snake_case       ,	is_encoder_decoder=snake_case       ,	add_cross_attention=snake_case       ,	decoder_start_token_id=snake_case       ,	**snake_case       ,	)







						@property
						def       lowerCamelCase_				(  self    :				Optional[Any]	):



											'''simple docstring'''


											return self.num_encoder_layers + self.num_decoder_layers







						@num_hidden_layers.setter
						def       lowerCamelCase_				(  self    :				List[Any]       ,	snake_case    :				Optional[int]	):



											'''simple docstring'''


											raise NotImplementedError(
											    'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and'
											    ' `num_decoder_layers`.'	)