






import inspect
import unittest

from transformers import DecisionTransformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import DecisionTransformerModel
		from transformers.models.decision_transformer.modeling_decision_transformer import (
		    DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
		)


class 							__a							:





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__ ,    UpperCamelCase__=13 ,    UpperCamelCase__=7 ,    UpperCamelCase__=6 ,    UpperCamelCase__=17 ,    UpperCamelCase__=23 ,    UpperCamelCase__=11 ,    UpperCamelCase__=True ,    ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   parent
						SCREAMING_SNAKE_CASE_   :	Any													=   batch_size
						SCREAMING_SNAKE_CASE_   :	List[str]													=   seq_length
						SCREAMING_SNAKE_CASE_   :	Dict													=   act_dim
						SCREAMING_SNAKE_CASE_   :	List[str]													=   state_dim
						SCREAMING_SNAKE_CASE_   :	Tuple													=   hidden_size
						SCREAMING_SNAKE_CASE_   :	List[str]													=   max_length
						SCREAMING_SNAKE_CASE_   :	List[str]													=   is_training


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   floats_tensor((self.batch_size, self.seq_length, self.state_dim)       )
						SCREAMING_SNAKE_CASE_   :	Tuple													=   floats_tensor((self.batch_size, self.seq_length, self.act_dim)       )
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   floats_tensor((self.batch_size, self.seq_length, 1)       )
						SCREAMING_SNAKE_CASE_   :	Dict													=   floats_tensor((self.batch_size, self.seq_length, 1)       )
						SCREAMING_SNAKE_CASE_   :	str													=   ids_tensor((self.batch_size, self.seq_length) ,    vocab_size=1000       )
						SCREAMING_SNAKE_CASE_   :	str													=   random_attention_mask((self.batch_size, self.seq_length)       )

						SCREAMING_SNAKE_CASE_   :	int													=   self.get_config()

						return (
						    config,
						    states,
						    actions,
						    rewards,
						    returns_to_go,
						    timesteps,
						    attention_mask,
						)


		def   __snake_case			(						self       ):
						return DecisionTransformerConfig(
						    batch_size=self.batch_size ,    seq_length=self.seq_length ,    act_dim=self.act_dim ,    state_dim=self.state_dim ,    hidden_size=self.hidden_size ,    max_length=self.max_length ,    )


		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    ):
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   DecisionTransformerModel(config=UpperCamelCase__       )
						model.to(UpperCamelCase__       )
						model.eval()
						SCREAMING_SNAKE_CASE_   :	Any													=   model(UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__ ,    UpperCamelCase__       )

						self.parent.assertEqual(result.state_preds.shape ,    states.shape       )
						self.parent.assertEqual(result.action_preds.shape ,    actions.shape       )
						self.parent.assertEqual(result.return_preds.shape ,    returns_to_go.shape       )
						self.parent.assertEqual(
						    result.last_hidden_state.shape ,    (self.batch_size, self.seq_length * 3, self.hidden_size)       )  # seq length *3 as there are 3 modelities: states, returns and actions






		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.prepare_config_and_inputs()
						(
						    SCREAMING_SNAKE_CASE_       
						)   :	Dict													=   config_and_inputs
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   {
						    'states': states,
						    'actions': actions,
						    'rewards': rewards,
						    'returns_to_go': returns_to_go,
						    'timesteps': timesteps,
						    'attention_mask': attention_mask,
						}
						return config, inputs_dict






@require_torch
class 							__a							(  __A ,	__A ,	__A ,	unittest.TestCase						):





		'''simple docstring'''



		UpperCAmelCase__      :				Dict				    =						(DecisionTransformerModel,) if is_torch_available() else ()
		UpperCAmelCase__      :				List[str]				    =						()
		UpperCAmelCase__      :				str				    =						{"""feature-extraction""": DecisionTransformerModel} if is_torch_available() else {}

		# Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids
		UpperCAmelCase__      :				Union[str, Any]				    =						False

		# Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features
		UpperCAmelCase__      :				Tuple				    =						False
		UpperCAmelCase__      :				List[Any]				    =						False
		UpperCAmelCase__      :				str				    =						False
		UpperCAmelCase__      :				Union[str, Any]				    =						False
		UpperCAmelCase__      :				Any				    =						False
		UpperCAmelCase__      :				Union[str, Any]				    =						False
		UpperCAmelCase__      :				str				    =						False
		UpperCAmelCase__      :				Optional[int]				    =						False
		UpperCAmelCase__      :				Optional[Any]				    =						False


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Any													=   DecisionTransformerModelTester(self       )
						SCREAMING_SNAKE_CASE_   :	List[str]													=   ConfigTester(self ,    config_class=UpperCamelCase__ ,    hidden_size=37       )


		def   __snake_case			(						self       ):
						self.config_tester.run_common_tests()


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	str													=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCamelCase__       )


		@slow
		def   __snake_case			(						self       ):
						for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										SCREAMING_SNAKE_CASE_   :	Any													=   DecisionTransformerModel.from_pretrained(UpperCamelCase__       )
										self.assertIsNotNone(UpperCamelCase__       )






		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   model_class(UpperCamelCase__       )
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   inspect.signature(model.forward       )
										# signature.parameters is an OrderedDict => so arg_names order is deterministic
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   [*signature.parameters.keys()]

										SCREAMING_SNAKE_CASE_   :	List[str]													=   [
										    'states',
										    'actions',
										    'rewards',
										    'returns_to_go',
										    'timesteps',
										    'attention_mask',
										]

										self.assertListEqual(arg_names[: len(UpperCamelCase__       )] ,    UpperCamelCase__       )






@require_torch
class 							__a							(  unittest.TestCase						):





		'''simple docstring'''



		@slow
		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[str]													=   2  # number of steps of autoregressive prediction we will perform
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   10  # defined by the RL environment, may be normalized
						SCREAMING_SNAKE_CASE_   :	Dict													=   DecisionTransformerModel.from_pretrained('edbeeching/decision-transformer-gym-hopper-expert'       )
						SCREAMING_SNAKE_CASE_   :	int													=   model.to(UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   model.config
						torch.manual_seed(0       )
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   torch.randn(1 ,    1 ,    config.state_dim       ).to(device=UpperCamelCase__ ,    dtype=torch.floataa       )  # env.reset()

						SCREAMING_SNAKE_CASE_   :	List[Any]													=   torch.tensor(
						    [[0.24_27_93, -0.28_69_30_74, 0.8_74_26_13], [0.67_81_52_74, -0.08_10_10_85, -0.12_95_21_47]] ,    device=UpperCamelCase__       )

						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   torch.tensor(UpperCamelCase__ ,    device=UpperCamelCase__ ,    dtype=torch.floataa       ).reshape(1 ,    1 ,    1       )
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   state
						SCREAMING_SNAKE_CASE_   :	Any													=   torch.zeros(1 ,    0 ,    config.act_dim ,    device=UpperCamelCase__ ,    dtype=torch.floataa       )
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   torch.zeros(1 ,    0 ,    device=UpperCamelCase__ ,    dtype=torch.floataa       )
						SCREAMING_SNAKE_CASE_   :	Any													=   torch.tensor(0 ,    device=UpperCamelCase__ ,    dtype=torch.long       ).reshape(1 ,    1       )

						for step in range(UpperCamelCase__       ):
										SCREAMING_SNAKE_CASE_   :	str													=   torch.cat([actions, torch.zeros(1 ,    1 ,    config.act_dim ,    device=UpperCamelCase__       )] ,    dim=1       )
										SCREAMING_SNAKE_CASE_   :	Dict													=   torch.cat([rewards, torch.zeros(1 ,    1 ,    device=UpperCamelCase__       )] ,    dim=1       )

										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   torch.ones(1 ,    states.shape[1]       ).to(dtype=torch.long ,    device=states.device       )

										with torch.no_grad():
														SCREAMING_SNAKE_CASE_   :	List[str]													=   model(
														    states=UpperCamelCase__ ,    actions=UpperCamelCase__ ,    rewards=UpperCamelCase__ ,    returns_to_go=UpperCamelCase__ ,    timesteps=UpperCamelCase__ ,    attention_mask=UpperCamelCase__ ,    return_dict=UpperCamelCase__ ,    )

										self.assertEqual(action_pred.shape ,    actions.shape       )
										self.assertTrue(torch.allclose(action_pred[0, -1] ,    expected_outputs[step] ,    atol=1E-4       )       )
										SCREAMING_SNAKE_CASE_   :	str													=   (  # env.step(action)
										    torch.randn(1 ,    1 ,    config.state_dim       ).to(device=UpperCamelCase__ ,    dtype=torch.floataa       ),
										    1.0,
										    False,
										    {},
										)

										SCREAMING_SNAKE_CASE_   :	Optional[int]													=   action_pred[0, -1]
										SCREAMING_SNAKE_CASE_   :	Optional[int]													=   torch.cat([states, state] ,    dim=1       )
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   returns_to_go[0, -1] - reward
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   torch.cat([returns_to_go, pred_return.reshape(1 ,    1 ,    1       )] ,    dim=1       )
										SCREAMING_SNAKE_CASE_   :	Optional[int]													=   torch.cat(
										    [timesteps, torch.ones((1, 1) ,    device=UpperCamelCase__ ,    dtype=torch.long       ) * (step + 1)] ,    dim=1       )







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


class 							__a							(  __A						):





		'''simple docstring'''



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


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

										SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Any													=   self.update(UpperCamelCase__       )
										counter += 1

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

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


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


		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )


		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )


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


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






		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )






class 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						super(UpperCamelCase__ ,    self       ).__init__()

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

						SCREAMING_SNAKE_CASE_   :	List[str]													=   token_ids

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


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


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						if self.completed:
										return False

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


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   False

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


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	List[str]													=   0


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






		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						SCREAMING_SNAKE_CASE_   :	str													=   PhrasalConstraint(self.token_ids       )

						if stateful:
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.seqlen
										SCREAMING_SNAKE_CASE_   :	Any													=   self.fulfilled_idx
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   self.completed

						return new_constraint






class 							__a							:





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__ ,    UpperCamelCase__=True       ):
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   max([len(UpperCamelCase__       ) for one in nested_token_ids]       )

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

														SCREAMING_SNAKE_CASE_   :	List[str]													=   level[token_id]

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

						SCREAMING_SNAKE_CASE_   :	Tuple													=   root


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	int													=   self.trie

						for current_token in current_seq:
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   start[current_token]

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   list(start.keys()       )

						return next_tokens


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.next_tokens(UpperCamelCase__       )

						return len(UpperCamelCase__       ) == 0


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	List[str]													=   list(root.values()       )
						if len(UpperCamelCase__       ) == 0:
										return 1
						else:
										return sum([self.count_leaves(UpperCamelCase__       ) for nn in next_nodes]       )






		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Dict													=   self.count_leaves(UpperCamelCase__       )
						return len(UpperCamelCase__       ) != leaf_count






class 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						super(UpperCamelCase__ ,    self       ).__init__()

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

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

						SCREAMING_SNAKE_CASE_   :	List[str]													=   self.trie.max_height
						SCREAMING_SNAKE_CASE_   :	str													=   []
						SCREAMING_SNAKE_CASE_   :	List[str]													=   False


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[str]													=   self.trie.next_tokens(self.current_seq       )

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


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						SCREAMING_SNAKE_CASE_   :	str													=   self.trie.next_tokens(self.current_seq       )

						return token_id in next_tokens


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   False
						SCREAMING_SNAKE_CASE_   :	Tuple													=   False
						SCREAMING_SNAKE_CASE_   :	Dict													=   False

						if self.does_advance(UpperCamelCase__       ):
										self.current_seq.append(UpperCamelCase__       )
										SCREAMING_SNAKE_CASE_   :	int													=   True
						else:
										SCREAMING_SNAKE_CASE_   :	Tuple													=   True
										self.reset()

						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   self.trie.reached_leaf(self.current_seq       )
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   completed

						return stepped, completed, reset


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   False
						SCREAMING_SNAKE_CASE_   :	Dict													=   []


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






		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						SCREAMING_SNAKE_CASE_   :	Any													=   DisjunctiveConstraint(self.token_ids       )

						if stateful:
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   self.seqlen
										SCREAMING_SNAKE_CASE_   :	Optional[int]													=   self.current_seq
										SCREAMING_SNAKE_CASE_   :	List[str]													=   self.completed

						return new_constraint






class 							__a							:





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Any													=   constraints

						# max # of steps required to fulfill a given constraint
						SCREAMING_SNAKE_CASE_   :	Dict													=   max([c.seqlen for c in constraints]       )
						SCREAMING_SNAKE_CASE_   :	Tuple													=   len(UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   False

						self.init_state()


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


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Union[str, 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   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   []
						if self.inprogress_constraint is None:
										for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
														SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   constraint.advance()
														if isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
																		token_list.append(UpperCamelCase__       )
														elif isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
																		token_list.extend(UpperCamelCase__       )
						else:
										SCREAMING_SNAKE_CASE_   :	List[str]													=   self.inprogress_constraint.advance()
										if isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
														token_list.append(UpperCamelCase__       )
										elif isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
														token_list.extend(UpperCamelCase__       )

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


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						self.init_state()

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

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


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.'''       )

						SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   False, False

						if self.completed:
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   True
										SCREAMING_SNAKE_CASE_   :	Union[str, 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

										SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   self.inprogress_constraint.update(UpperCamelCase__       )
										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=UpperCamelCase__       )       )
														SCREAMING_SNAKE_CASE_   :	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       )
														SCREAMING_SNAKE_CASE_   :	str													=   None

														if len(self.pending_constraints       ) == 0:
																		# we're done!
																		SCREAMING_SNAKE_CASE_   :	Tuple													=   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(UpperCamelCase__       ):
																		SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   pending_constraint.update(UpperCamelCase__       )

																		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(UpperCamelCase__       )
																						SCREAMING_SNAKE_CASE_   :	List[str]													=   None

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

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

																						SCREAMING_SNAKE_CASE_   :	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.

																										SCREAMING_SNAKE_CASE_   :	Dict													=   True

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

						return complete, stepped






		def   __snake_case			(						self ,    UpperCamelCase__=True       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   ConstraintListState(self.constraints       )  # we actually never though self.constraints objects
						# throughout this process. So it's at initialization state.

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

						return new_state