



"""simple docstring"""







import unittest

from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_PRETRAINING_MAPPING,
					    AlbertForMaskedLM,
					    AlbertForMultipleChoice,
					    AlbertForPreTraining,
					    AlbertForQuestionAnswering,
					    AlbertForSequenceClassification,
					    AlbertForTokenClassification,
					    AlbertModel,
					)
					from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST







class 				UpperCamelCase__       :




						"""simple docstring"""




						def __init__(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Dict=1_3   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=7   ,      SCREAMING_SNAKE_CASE_    :				Dict=True   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=True   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=True   ,      SCREAMING_SNAKE_CASE_    :				str=True   ,      SCREAMING_SNAKE_CASE_    :				List[str]=9_9   ,      SCREAMING_SNAKE_CASE_    :				int=1_6   ,      SCREAMING_SNAKE_CASE_    :				List[str]=3_6   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=6   ,      SCREAMING_SNAKE_CASE_    :				Tuple=6   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=6   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=3_7   ,      SCREAMING_SNAKE_CASE_    :				Tuple="gelu"   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=0.1   ,      SCREAMING_SNAKE_CASE_    :				int=0.1   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=5_1_2   ,      SCREAMING_SNAKE_CASE_    :				List[str]=1_6   ,      SCREAMING_SNAKE_CASE_    :				List[str]=2   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=0.02   ,      SCREAMING_SNAKE_CASE_    :				Dict=3   ,      SCREAMING_SNAKE_CASE_    :				int=4   ,      SCREAMING_SNAKE_CASE_    :				Tuple=None   ,      ):
								lowerCAmelCase_       :    Any								=			parent
								lowerCAmelCase_       :    Optional[int]								=			batch_size
								lowerCAmelCase_       :    Dict								=			seq_length
								lowerCAmelCase_       :    Tuple								=			is_training
								lowerCAmelCase_       :    str								=			use_input_mask
								lowerCAmelCase_       :    Union[str, Any]								=			use_token_type_ids
								lowerCAmelCase_       :    Tuple								=			use_labels
								lowerCAmelCase_       :    Optional[int]								=			vocab_size
								lowerCAmelCase_       :    Any								=			embedding_size
								lowerCAmelCase_       :    Optional[Any]								=			hidden_size
								lowerCAmelCase_       :    str								=			num_hidden_layers
								lowerCAmelCase_       :    Optional[Any]								=			num_hidden_groups
								lowerCAmelCase_       :    Dict								=			num_attention_heads
								lowerCAmelCase_       :    Optional[Any]								=			intermediate_size
								lowerCAmelCase_       :    Any								=			hidden_act
								lowerCAmelCase_       :    Union[str, Any]								=			hidden_dropout_prob
								lowerCAmelCase_       :    int								=			attention_probs_dropout_prob
								lowerCAmelCase_       :    int								=			max_position_embeddings
								lowerCAmelCase_       :    List[Any]								=			type_vocab_size
								lowerCAmelCase_       :    Any								=			type_sequence_label_size
								lowerCAmelCase_       :    Optional[int]								=			initializer_range
								lowerCAmelCase_       :    Tuple								=			num_labels
								lowerCAmelCase_       :    Dict								=			num_choices
								lowerCAmelCase_       :    Tuple								=			scope



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):
								lowerCAmelCase_       :    List[str]								=			ids_tensor([self.batch_size, self.seq_length]   ,      self.vocab_size	)

								lowerCAmelCase_       :    str								=			None
								if self.use_input_mask:
										lowerCAmelCase_       :    int								=			random_attention_mask([self.batch_size, self.seq_length]	)

								lowerCAmelCase_       :    List[Any]								=			None
								if self.use_token_type_ids:
										lowerCAmelCase_       :    str								=			ids_tensor([self.batch_size, self.seq_length]   ,      self.type_vocab_size	)

								lowerCAmelCase_       :    List[str]								=			None
								lowerCAmelCase_       :    Union[str, Any]								=			None
								lowerCAmelCase_       :    str								=			None
								if self.use_labels:
										lowerCAmelCase_       :    Any								=			ids_tensor([self.batch_size]   ,      self.type_sequence_label_size	)
										lowerCAmelCase_       :    List[str]								=			ids_tensor([self.batch_size, self.seq_length]   ,      self.num_labels	)
										lowerCAmelCase_       :    Dict								=			ids_tensor([self.batch_size]   ,      self.num_choices	)

								lowerCAmelCase_       :    List[Any]								=			self.get_config()

								return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
								return AlbertConfig(
								    vocab_size=self.vocab_size   ,      hidden_size=self.hidden_size   ,      num_hidden_layers=self.num_hidden_layers   ,      num_attention_heads=self.num_attention_heads   ,      intermediate_size=self.intermediate_size   ,      hidden_act=self.hidden_act   ,      hidden_dropout_prob=self.hidden_dropout_prob   ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,      max_position_embeddings=self.max_position_embeddings   ,      type_vocab_size=self.type_vocab_size   ,      initializer_range=self.initializer_range   ,      num_hidden_groups=self.num_hidden_groups   ,      )



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				str	):
								lowerCAmelCase_       :    Union[str, Any]								=			AlbertModel(config=SCREAMING_SNAKE_CASE_	)
								model.to(SCREAMING_SNAKE_CASE_	)
								model.eval()
								lowerCAmelCase_       :    List[str]								=			model(SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_	)
								lowerCAmelCase_       :    List[Any]								=			model(SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_	)
								lowerCAmelCase_       :    int								=			model(SCREAMING_SNAKE_CASE_	)
								self.parent.assertEqual(result.last_hidden_state.shape   ,      (self.batch_size, self.seq_length, self.hidden_size)	)
								self.parent.assertEqual(result.pooler_output.shape   ,      (self.batch_size, self.hidden_size)	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Tuple	):
								lowerCAmelCase_       :    Optional[Any]								=			AlbertForPreTraining(config=SCREAMING_SNAKE_CASE_	)
								model.to(SCREAMING_SNAKE_CASE_	)
								model.eval()
								lowerCAmelCase_       :    Optional[Any]								=			model(
								    SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_   ,      sentence_order_label=SCREAMING_SNAKE_CASE_   ,      )
								self.parent.assertEqual(result.prediction_logits.shape   ,      (self.batch_size, self.seq_length, self.vocab_size)	)
								self.parent.assertEqual(result.sop_logits.shape   ,      (self.batch_size, config.num_labels)	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Dict	):
								lowerCAmelCase_       :    str								=			AlbertForMaskedLM(config=SCREAMING_SNAKE_CASE_	)
								model.to(SCREAMING_SNAKE_CASE_	)
								model.eval()
								lowerCAmelCase_       :    str								=			model(SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)
								self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.seq_length, self.vocab_size)	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				str   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]	):
								lowerCAmelCase_       :    List[str]								=			AlbertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_	)
								model.to(SCREAMING_SNAKE_CASE_	)
								model.eval()
								lowerCAmelCase_       :    Any								=			model(
								    SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_   ,      )
								self.parent.assertEqual(result.start_logits.shape   ,      (self.batch_size, self.seq_length)	)
								self.parent.assertEqual(result.end_logits.shape   ,      (self.batch_size, self.seq_length)	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Dict	):
								lowerCAmelCase_       :    Union[str, Any]								=			self.num_labels
								lowerCAmelCase_       :    Union[str, Any]								=			AlbertForSequenceClassification(SCREAMING_SNAKE_CASE_	)
								model.to(SCREAMING_SNAKE_CASE_	)
								model.eval()
								lowerCAmelCase_       :    Union[str, Any]								=			model(SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)
								self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_labels)	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[str]	):
								lowerCAmelCase_       :    List[str]								=			self.num_labels
								lowerCAmelCase_       :    List[Any]								=			AlbertForTokenClassification(config=SCREAMING_SNAKE_CASE_	)
								model.to(SCREAMING_SNAKE_CASE_	)
								model.eval()
								lowerCAmelCase_       :    str								=			model(SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)
								self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.seq_length, self.num_labels)	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				List[str]	):
								lowerCAmelCase_       :    Optional[Any]								=			self.num_choices
								lowerCAmelCase_       :    int								=			AlbertForMultipleChoice(config=SCREAMING_SNAKE_CASE_	)
								model.to(SCREAMING_SNAKE_CASE_	)
								model.eval()
								lowerCAmelCase_       :    Optional[int]								=			input_ids.unsqueeze(1	).expand(-1   ,      self.num_choices   ,      -1	).contiguous()
								lowerCAmelCase_       :    List[Any]								=			token_type_ids.unsqueeze(1	).expand(-1   ,      self.num_choices   ,      -1	).contiguous()
								lowerCAmelCase_       :    List[Any]								=			input_mask.unsqueeze(1	).expand(-1   ,      self.num_choices   ,      -1	).contiguous()
								lowerCAmelCase_       :    List[Any]								=			model(
								    SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_   ,      )
								self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_choices)	)





						def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
								lowerCAmelCase_       :    Optional[int]								=			self.prepare_config_and_inputs()
								(
								    lowerCAmelCase_
								)       :    Optional[int]								=			config_and_inputs
								lowerCAmelCase_       :    Dict								=			{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
								return config, inputs_dict







@require_torch
class 				UpperCamelCase__       (     lowercase_, lowercase_, unittest.TestCase  ):




						"""simple docstring"""




						_SCREAMING_SNAKE_CASE      =					(
						    (
						        AlbertModel,
						        AlbertForPreTraining,
						        AlbertForMaskedLM,
						        AlbertForMultipleChoice,
						        AlbertForSequenceClassification,
						        AlbertForTokenClassification,
						        AlbertForQuestionAnswering,
						    )
						    if is_torch_available()
						    else ()
						)
						_SCREAMING_SNAKE_CASE      =					(
						    {
						        """feature-extraction""": AlbertModel,
						        """fill-mask""": AlbertForMaskedLM,
						        """question-answering""": AlbertForQuestionAnswering,
						        """text-classification""": AlbertForSequenceClassification,
						        """token-classification""": AlbertForTokenClassification,
						        """zero-shot""": AlbertForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)
						_SCREAMING_SNAKE_CASE      =					True



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				str=False	):
								lowerCAmelCase_       :    List[str]								=			super()._prepare_for_class(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      return_labels=SCREAMING_SNAKE_CASE_	)

								if return_labels:
										if model_class in get_values(SCREAMING_SNAKE_CASE_	):
												lowerCAmelCase_       :    List[str]								=			torch.zeros(
												    (self.model_tester.batch_size, self.model_tester.seq_length)   ,      dtype=torch.long   ,      device=SCREAMING_SNAKE_CASE_	)
												lowerCAmelCase_       :    Any								=			torch.zeros(
												    self.model_tester.batch_size   ,      dtype=torch.long   ,      device=SCREAMING_SNAKE_CASE_	)
								return inputs_dict



						def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
								lowerCAmelCase_       :    str								=			AlbertModelTester(self	)
								lowerCAmelCase_       :    Optional[int]								=			ConfigTester(self   ,      config_class=SCREAMING_SNAKE_CASE_   ,      hidden_size=3_7	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
								self.config_tester.run_common_tests()



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
								lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
								lowerCAmelCase_       :    Any								=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE_	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
								lowerCAmelCase_       :    Tuple								=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
								lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
								lowerCAmelCase_       :    str								=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
								lowerCAmelCase_       :    Optional[int]								=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_	)



						def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
								lowerCAmelCase_       :    Tuple								=			self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
										lowerCAmelCase_       :    int								=			type
										self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_	)





						@slow
						def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
								for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowerCAmelCase_       :    Optional[Any]								=			AlbertModel.from_pretrained(SCREAMING_SNAKE_CASE_	)
										self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)







@require_torch
class 				UpperCamelCase__       (     unittest.TestCase  ):




						"""simple docstring"""




						@slow
						def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
								lowerCAmelCase_       :    Any								=			AlbertModel.from_pretrained('albert-base-v2'	)
								lowerCAmelCase_       :    Tuple								=			torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]	)
								lowerCAmelCase_       :    Tuple								=			torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]	)
								with torch.no_grad():
										lowerCAmelCase_       :    List[Any]								=			model(SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_	)[0]
								lowerCAmelCase_       :    str								=			torch.Size((1, 1_1, 7_6_8)	)
								self.assertEqual(output.shape   ,      SCREAMING_SNAKE_CASE_	)
								lowerCAmelCase_       :    int								=			torch.tensor(
								    [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]]	)

								self.assertTrue(torch.allclose(output[:, 1:4, 1:4]   ,      SCREAMING_SNAKE_CASE_   ,      atol=1E-4	)	)










"""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





