


"""simple docstring"""







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


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       def __init__(						self						):






         """simple docstring"""





         self.test()

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Union[str, Any]								=							0
         lowerCAmelCase					:					Dict								=							False
         while not completed:
           if counter == 1:
             self.reset()
           lowerCAmelCase					:					Tuple								=							self.advance()
           if not self.does_advance(snake_case__						):
             raise Exception(
                 "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."						)

           lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase					:					Dict								=							self.update(snake_case__						)
           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						):






         """simple docstring"""





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

       @abstractmethod
       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





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

       @abstractmethod
       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





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

       @abstractmethod
       def 	lowercase__							(						self						):






         """simple docstring"""





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

       @abstractmethod
       def 	lowercase__							(						self						):






         """simple docstring"""





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







       @abstractmethod
       def 	lowercase__							(						self		,					snake_case__=False						):






         """simple docstring"""





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


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       def __init__(						self		,					snake_case__						):






         """simple docstring"""





         super(snake_case__		,					self						).__init__()

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

         lowerCAmelCase					:					Any								=							len(self.token_ids						)
         lowerCAmelCase					:					Any								=							-1  # the index of the currently fulfilled step
         lowerCAmelCase					:					Any								=							False

       def 	lowercase__							(						self						):






         """simple docstring"""





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

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





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

         if self.completed:
           return False

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

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





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

         lowerCAmelCase					:					Union[str, Any]								=							False
         lowerCAmelCase					:					str								=							False
         lowerCAmelCase					:					Tuple								=							False

         if self.does_advance(snake_case__						):
           self.fulfilled_idx += 1
           lowerCAmelCase					:					int								=							True
           if self.fulfilled_idx == (self.seqlen - 1):
             lowerCAmelCase					:					Tuple								=							True
           lowerCAmelCase					:					str								=							completed
         else:
           # failed to make progress.
           lowerCAmelCase					:					int								=							True
           self.reset()
         return stepped, completed, reset

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					List[Any]								=							False
         lowerCAmelCase					:					Optional[Any]								=							0

       def 	lowercase__							(						self						):






         """simple docstring"""





         return self.seqlen - (self.fulfilled_idx + 1)







       def 	lowercase__							(						self		,					snake_case__=False						):






         """simple docstring"""





         lowerCAmelCase					:					Dict								=							PhrasalConstraint(self.token_ids						)

         if stateful:
           lowerCAmelCase					:					List[Any]								=							self.seqlen
           lowerCAmelCase					:					Optional[Any]								=							self.fulfilled_idx
           lowerCAmelCase					:					Union[str, Any]								=							self.completed

         return new_constraint


class 				SCREAMING_SNAKE_CASE__    :
       """simple docstring"""


       def __init__(						self		,					snake_case__		,					snake_case__=True						):






         """simple docstring"""





         lowerCAmelCase					:					int								=							max([len(snake_case__						) for one in nested_token_ids]						)

         lowerCAmelCase					:					List[Any]								=							{}
         for token_ids in nested_token_ids:
           lowerCAmelCase					:					Any								=							root
           for tidx, token_id in enumerate(snake_case__						):
             if token_id not in level:
               lowerCAmelCase					:					int								=							{}

             lowerCAmelCase					:					str								=							level[token_id]

         if no_subsets and self.has_subsets(snake_case__		,					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					:					Tuple								=							root

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					Optional[Any]								=							self.trie

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

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

         return next_tokens

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					List[Any]								=							self.next_tokens(snake_case__						)

         return len(snake_case__						) == 0

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					int								=							list(root.values()						)
         if len(snake_case__						) == 0:
           return 1
         else:
           return sum([self.count_leaves(snake_case__						) for nn in next_nodes]						)







       def 	lowercase__							(						self		,					snake_case__		,					snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					Optional[Any]								=							self.count_leaves(snake_case__						)
         return len(snake_case__						) != leaf_count


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       def __init__(						self		,					snake_case__						):






         """simple docstring"""





         super(snake_case__		,					self						).__init__()

         if not isinstance(snake_case__		,					snake_case__						) or len(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(snake_case__		,					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(snake_case__		,					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					:					str								=							DisjunctiveTrie(snake_case__						)
         lowerCAmelCase					:					int								=							nested_token_ids

         lowerCAmelCase					:					int								=							self.trie.max_height
         lowerCAmelCase					:					int								=							[]
         lowerCAmelCase					:					Tuple								=							False

       def 	lowercase__							(						self						):






         """simple docstring"""





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

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

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





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

         lowerCAmelCase					:					Optional[Any]								=							self.trie.next_tokens(self.current_seq						)

         return token_id in next_tokens

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





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

         lowerCAmelCase					:					Optional[Any]								=							False
         lowerCAmelCase					:					List[Any]								=							False
         lowerCAmelCase					:					Dict								=							False

         if self.does_advance(snake_case__						):
           self.current_seq.append(snake_case__						)
           lowerCAmelCase					:					Optional[int]								=							True
         else:
           lowerCAmelCase					:					Any								=							True
           self.reset()

         lowerCAmelCase					:					str								=							self.trie.reached_leaf(self.current_seq						)
         lowerCAmelCase					:					Any								=							completed

         return stepped, completed, reset

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Dict								=							False
         lowerCAmelCase					:					Optional[Any]								=							[]

       def 	lowercase__							(						self						):






         """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		,					snake_case__=False						):






         """simple docstring"""





         lowerCAmelCase					:					Union[str, Any]								=							DisjunctiveConstraint(self.token_ids						)

         if stateful:
           lowerCAmelCase					:					Any								=							self.seqlen
           lowerCAmelCase					:					List[Any]								=							self.current_seq
           lowerCAmelCase					:					List[str]								=							self.completed

         return new_constraint


class 				SCREAMING_SNAKE_CASE__    :
       """simple docstring"""


       def __init__(						self		,					snake_case__						):






         """simple docstring"""





         lowerCAmelCase					:					str								=							constraints

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

         self.init_state()

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Tuple								=							[]
         lowerCAmelCase					:					str								=							None
         lowerCAmelCase					:					List[Any]								=							[constraint.copy(stateful=snake_case__						) for constraint in self.constraints]

       def 	lowercase__							(						self						):






         """simple docstring"""





         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 	lowercase__							(						self						):






         """simple docstring"""





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

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

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





         self.init_state()

         if token_ids is not None:
           for token in token_ids:
             # completes or steps **one** constraint
             lowerCAmelCase						,  lowerCAmelCase					:					Tuple								=							self.add(snake_case__						)

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

       def 	lowercase__							(						self		,					snake_case__						):






         """simple docstring"""





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

         lowerCAmelCase						,  lowerCAmelCase					:					List[Any]								=							False, False

         if self.completed:
           lowerCAmelCase					:					Optional[Any]								=							True
           lowerCAmelCase					:					List[str]								=							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					:					Union[str, Any]								=							self.inprogress_constraint.update(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=snake_case__						)						)
             lowerCAmelCase					:					Dict								=							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					:					Dict								=							None

             if len(self.pending_constraints						) == 0:
               # we're done!
               lowerCAmelCase					:					List[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(snake_case__						):
               lowerCAmelCase						,  lowerCAmelCase						,  lowerCAmelCase					:					str								=							pending_constraint.update(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(snake_case__						)
                 lowerCAmelCase					:					Tuple								=							None

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

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

                 lowerCAmelCase					:					List[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.

                   lowerCAmelCase					:					Union[str, Any]								=							True

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

         return complete, stepped







       def 	lowercase__							(						self		,					snake_case__=True						):






         """simple docstring"""





         lowerCAmelCase					:					Tuple								=							ConstraintListState(self.constraints						)  # we actually never though self.constraints objects
         # throughout this process. So it's at initialization state.

         if stateful:
           lowerCAmelCase					:					int								=							[
               constraint.copy(stateful=snake_case__						) for constraint in self.complete_constraints
           ]
           if self.inprogress_constraint is not None:
             lowerCAmelCase					:					List[Any]								=							self.inprogress_constraint.copy(stateful=snake_case__						)
           lowerCAmelCase					:					int								=							[constraint.copy() for constraint in self.pending_constraints]

         return new_state









"""simple docstring"""







from typing import List, Optional

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


lowerCAmelCase__				    =       logging.get_logger(__name__)

lowerCAmelCase__				    =       {
    '''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}


class 				SCREAMING_SNAKE_CASE__    (		lowercase    ):
       """simple docstring"""


       a  :    Dict       ="autoformer"
       a  :    Dict       ={
           "hidden_size": "d_model",
           "num_attention_heads": "encoder_attention_heads",
           "num_hidden_layers": "encoder_layers",
       }

       def __init__(						self		,					snake_case__ = None		,					snake_case__ = None		,					snake_case__ = "student_t"		,					snake_case__ = "nll"		,					snake_case__ = 1		,					snake_case__ = [1, 2, 3, 4, 5, 6, 7]		,					snake_case__ = True		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = 0		,					snake_case__ = None		,					snake_case__ = None		,					snake_case__ = 64		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 2		,					snake_case__ = 32		,					snake_case__ = 32		,					snake_case__ = "gelu"		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 0.1		,					snake_case__ = 100		,					snake_case__ = 0.02		,					snake_case__ = True		,					snake_case__=True		,					snake_case__ = 10		,					snake_case__ = 25		,					snake_case__ = 3		,					**snake_case__		,					):






         """simple docstring"""





         lowerCAmelCase					:					Any								=							prediction_length
         lowerCAmelCase					:					Dict								=							context_length if context_length is not None else prediction_length
         lowerCAmelCase					:					Tuple								=							distribution_output
         lowerCAmelCase					:					List[Any]								=							loss
         lowerCAmelCase					:					int								=							input_size
         lowerCAmelCase					:					str								=							num_time_features
         lowerCAmelCase					:					str								=							lags_sequence
         lowerCAmelCase					:					List[str]								=							scaling
         lowerCAmelCase					:					List[Any]								=							num_dynamic_real_features
         lowerCAmelCase					:					Tuple								=							num_static_real_features
         lowerCAmelCase					:					Dict								=							num_static_categorical_features
         if cardinality is not None and num_static_categorical_features > 0:
           if len(snake_case__						) != num_static_categorical_features:
             raise ValueError(
                 "The cardinality should be a list of the same length as `num_static_categorical_features`"						)
           lowerCAmelCase					:					Any								=							cardinality
         else:
           lowerCAmelCase					:					Union[str, Any]								=							[0]
         if embedding_dimension is not None and num_static_categorical_features > 0:
           if len(snake_case__						) != num_static_categorical_features:
             raise ValueError(
                 "The embedding dimension should be a list of the same length as `num_static_categorical_features`"						)
           lowerCAmelCase					:					Tuple								=							embedding_dimension
         else:
           lowerCAmelCase					:					Any								=							[min(50		,					(cat + 1) // 2						) for cat in self.cardinality]
         lowerCAmelCase					:					Any								=							num_parallel_samples

         # Transformer architecture configuration
         lowerCAmelCase					:					str								=							input_size * len(self.lags_sequence						) + self._number_of_features
         lowerCAmelCase					:					Any								=							d_model
         lowerCAmelCase					:					List[str]								=							encoder_attention_heads
         lowerCAmelCase					:					Union[str, Any]								=							decoder_attention_heads
         lowerCAmelCase					:					Optional[int]								=							encoder_ffn_dim
         lowerCAmelCase					:					Optional[Any]								=							decoder_ffn_dim
         lowerCAmelCase					:					int								=							encoder_layers
         lowerCAmelCase					:					int								=							decoder_layers

         lowerCAmelCase					:					List[Any]								=							dropout
         lowerCAmelCase					:					Optional[int]								=							attention_dropout
         lowerCAmelCase					:					Union[str, Any]								=							activation_dropout
         lowerCAmelCase					:					Optional[int]								=							encoder_layerdrop
         lowerCAmelCase					:					Dict								=							decoder_layerdrop

         lowerCAmelCase					:					Tuple								=							activation_function
         lowerCAmelCase					:					Optional[Any]								=							init_std

         lowerCAmelCase					:					List[Any]								=							use_cache

         # Autoformer
         lowerCAmelCase					:					Any								=							label_length
         lowerCAmelCase					:					Any								=							moving_average
         lowerCAmelCase					:					Optional[Any]								=							autocorrelation_factor

         super().__init__(is_encoder_decoder=snake_case__		,					**snake_case__						)







       @property
       def 	lowercase__							(						self						):






         """simple docstring"""





         return (
             sum(self.embedding_dimension						)
             + self.num_dynamic_real_features
             + self.num_time_features
             + self.num_static_real_features
             + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
         )





