
'''simple docstring'''



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




class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						def __init__(   self ):

												"""simple docstring"""



												self.test()




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					0
												_lowerCAmelCase    		=					False
												while not completed:
																		if counter == 1:
																								self.reset()
																		_lowerCAmelCase    		=					self.advance()
																		if not self.does_advance(_lowercase ):
																								raise Exception(
																								    """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.""" )

																		_lowerCAmelCase		,       _lowerCAmelCase		,       _lowerCAmelCase    		=					self.update(_lowercase )
																		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       ,  _lowercase ):

												"""simple docstring"""



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




						@abstractmethod
						def    _lowercase      (   self       ,  _lowercase ):

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

												"""simple docstring"""



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






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						def __init__(   self       ,  _lowercase ):

												"""simple docstring"""



												super(_lowercase       ,  self ).__init__()

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

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




						def    _lowercase      (   self ):

												"""simple docstring"""



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




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



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

												if self.completed:
																		return False

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




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



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

												_lowerCAmelCase    		=					False
												_lowerCAmelCase    		=					False
												_lowerCAmelCase    		=					False

												if self.does_advance(_lowercase ):
																		self.fulfilled_idx += 1
																		_lowerCAmelCase    		=					True
																		if self.fulfilled_idx == (self.seqlen - 1):
																								_lowerCAmelCase    		=					True
																		_lowerCAmelCase    		=					completed
												else:
																		# failed to make progress.
																		_lowerCAmelCase    		=					True
																		self.reset()
												return stepped, completed, reset




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					False
												_lowerCAmelCase    		=					0




						def    _lowercase      (   self ):

												"""simple docstring"""



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




						def    _lowercase      (   self       ,  _lowercase=False ):

												"""simple docstring"""



												_lowerCAmelCase    		=					PhrasalConstraint(self.token_ids )

												if stateful:
																		_lowerCAmelCase    		=					self.seqlen
																		_lowerCAmelCase    		=					self.fulfilled_idx
																		_lowerCAmelCase    		=					self.completed

												return new_constraint






class     UpperCAmelCase_	:






						'''simple docstring'''






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

												"""simple docstring"""



												_lowerCAmelCase    		=					max([len(_lowercase ) for one in nested_token_ids] )

												_lowerCAmelCase    		=					{}
												for token_ids in nested_token_ids:
																		_lowerCAmelCase    		=					root
																		for tidx, token_id in enumerate(_lowercase ):
																								if token_id not in level:
																														_lowerCAmelCase    		=					{}

																								_lowerCAmelCase    		=					level[token_id]

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

												_lowerCAmelCase    		=					root




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.trie

												for current_token in current_seq:
																		_lowerCAmelCase    		=					start[current_token]

												_lowerCAmelCase    		=					list(start.keys() )

												return next_tokens




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.next_tokens(_lowercase )

												return len(_lowercase ) == 0




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



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




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.count_leaves(_lowercase )
												return len(_lowercase ) != leaf_count






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						def __init__(   self       ,  _lowercase ):

												"""simple docstring"""



												super(_lowercase       ,  self ).__init__()

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

												_lowerCAmelCase    		=					self.trie.max_height
												_lowerCAmelCase    		=					[]
												_lowerCAmelCase    		=					False




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.trie.next_tokens(self.current_seq )

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




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



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

												_lowerCAmelCase    		=					self.trie.next_tokens(self.current_seq )

												return token_id in next_tokens




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



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

												_lowerCAmelCase    		=					False
												_lowerCAmelCase    		=					False
												_lowerCAmelCase    		=					False

												if self.does_advance(_lowercase ):
																		self.current_seq.append(_lowercase )
																		_lowerCAmelCase    		=					True
												else:
																		_lowerCAmelCase    		=					True
																		self.reset()

												_lowerCAmelCase    		=					self.trie.reached_leaf(self.current_seq )
												_lowerCAmelCase    		=					completed

												return stepped, completed, reset




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					False
												_lowerCAmelCase    		=					[]




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

												"""simple docstring"""



												_lowerCAmelCase    		=					DisjunctiveConstraint(self.token_ids )

												if stateful:
																		_lowerCAmelCase    		=					self.seqlen
																		_lowerCAmelCase    		=					self.current_seq
																		_lowerCAmelCase    		=					self.completed

												return new_constraint






class     UpperCAmelCase_	:






						'''simple docstring'''






						def __init__(   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					constraints

												# max # of steps required to fulfill a given constraint
												_lowerCAmelCase    		=					max([c.seqlen for c in constraints] )
												_lowerCAmelCase    		=					len(_lowercase )
												_lowerCAmelCase    		=					False

												self.init_state()




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					[]
												_lowerCAmelCase    		=					None
												_lowerCAmelCase    		=					[constraint.copy(stateful=_lowercase ) for constraint in self.constraints]




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					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    		=					[]
												if self.inprogress_constraint is None:
																		for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
																								_lowerCAmelCase    		=					constraint.advance()
																								if isinstance(_lowercase       ,  _lowercase ):
																														token_list.append(_lowercase )
																								elif isinstance(_lowercase       ,  _lowercase ):
																														token_list.extend(_lowercase )
												else:
																		_lowerCAmelCase    		=					self.inprogress_constraint.advance()
																		if isinstance(_lowercase       ,  _lowercase ):
																								token_list.append(_lowercase )
																		elif isinstance(_lowercase       ,  _lowercase ):
																								token_list.extend(_lowercase )

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




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												self.init_state()

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

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




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



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

												_lowerCAmelCase		,       _lowerCAmelCase    		=					False, False

												if self.completed:
																		_lowerCAmelCase    		=					True
																		_lowerCAmelCase    		=					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    		=					self.inprogress_constraint.update(_lowercase )
																		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=_lowercase ) )
																								_lowerCAmelCase    		=					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    		=					None

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

																														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(_lowercase )
																																				_lowerCAmelCase    		=					None

																														if not complete and stepped:
																																				_lowerCAmelCase    		=					pending_constraint

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

																																				_lowerCAmelCase    		=					(
																																				    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    		=					True

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

												return complete, stepped




						def    _lowercase      (   self       ,  _lowercase=True ):

												"""simple docstring"""



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

												if stateful:
																		_lowerCAmelCase    		=					[
																		    constraint.copy(stateful=_lowercase ) for constraint in self.complete_constraints
																		]
																		if self.inprogress_constraint is not None:
																								_lowerCAmelCase    		=					self.inprogress_constraint.copy(stateful=_lowercase )
																		_lowerCAmelCase    		=					[constraint.copy() for constraint in self.pending_constraints]

												return new_state


'''simple docstring'''



from manim import *




class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					Rectangle(height=0.5       ,  width=0.5 )
												_lowerCAmelCase    		=					Rectangle(height=0.46       ,  width=0.46 ).set_stroke(width=0 )

												_lowerCAmelCase    		=					[mem.copy() for i in range(6 )]
												_lowerCAmelCase    		=					[mem.copy() for i in range(6 )]
												_lowerCAmelCase    		=					VGroup(*_lowercase ).arrange(_lowercase       ,  buff=0 )
												_lowerCAmelCase    		=					VGroup(*_lowercase ).arrange(_lowercase       ,  buff=0 )
												_lowerCAmelCase    		=					VGroup(_lowercase       ,  _lowercase ).arrange(_lowercase       ,  buff=0 )
												_lowerCAmelCase    		=					Text("""CPU"""       ,  font_size=24 )
												_lowerCAmelCase    		=					Group(_lowercase       ,  _lowercase ).arrange(_lowercase       ,  buff=0.5       ,  aligned_edge=_lowercase )
												cpu.move_to([-2.5, -0.5, 0] )
												self.add(_lowercase )

												_lowerCAmelCase    		=					[mem.copy() for i in range(1 )]
												_lowerCAmelCase    		=					VGroup(*_lowercase ).arrange(_lowercase       ,  buff=0 )
												_lowerCAmelCase    		=					Text("""GPU"""       ,  font_size=24 )
												_lowerCAmelCase    		=					Group(_lowercase       ,  _lowercase ).arrange(_lowercase       ,  buff=0.5       ,  aligned_edge=_lowercase )
												gpu.align_to(_lowercase       ,  _lowercase )
												gpu.set_x(gpu.get_x() - 1 )

												self.add(_lowercase )

												_lowerCAmelCase    		=					[mem.copy() for i in range(6 )]
												_lowerCAmelCase    		=					VGroup(*_lowercase ).arrange(_lowercase       ,  buff=0 )

												_lowerCAmelCase    		=					Text("""Model"""       ,  font_size=24 )
												_lowerCAmelCase    		=					Group(_lowercase       ,  _lowercase ).arrange(_lowercase       ,  buff=0.5       ,  aligned_edge=_lowercase )
												model.move_to([3, -1.0, 0] )

												self.play(
												    Create(_lowercase       ,  run_time=1 )       ,  Create(_lowercase       ,  run_time=1 )       ,  Create(_lowercase       ,  run_time=1 )       ,  )

												_lowerCAmelCase    		=					MarkupText(
												    F'First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.'       ,  font_size=24       ,  )

												_lowerCAmelCase    		=					Square(side_length=2.2 )
												key.move_to([-5, 2, 0] )

												_lowerCAmelCase    		=					MarkupText(
												    F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model'       ,  font_size=18       ,  )

												key_text.move_to([-5, 2.4, 0] )

												step_a.move_to([2, 2, 0] )
												self.play(Write(_lowercase       ,  run_time=2.5 )       ,  Write(_lowercase )       ,  Write(_lowercase ) )

												self.add(_lowercase )

												_lowerCAmelCase    		=					[]
												_lowerCAmelCase    		=					[]
												_lowerCAmelCase    		=					[]
												for i, rect in enumerate(_lowercase ):
																		_lowerCAmelCase    		=					Rectangle(height=0.46       ,  width=0.46 ).set_stroke(width=0.0 ).set_fill(_lowercase       ,  opacity=0.7 )
																		cpu_target.move_to(_lowercase )
																		cpu_target.generate_target()
																		_lowerCAmelCase    		=					0.46 / 4
																		_lowerCAmelCase    		=					0.46 / 3

																		if i == 0:
																								cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT )       ,  buff=0.02       ,  direction=_lowercase )
																								cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 )
																		elif i == 3:
																								cpu_target.target.next_to(cpu_targs[0].target       ,  direction=_lowercase       ,  buff=0.0 )
																		else:
																								cpu_target.target.next_to(cpu_targs[i - 1].target       ,  direction=_lowercase       ,  buff=0.0 )
																		cpu_targs.append(_lowercase )

																		first_animations.append(rect.animate(run_time=0.5 ).set_stroke(_lowercase ) )
																		second_animations.append(MoveToTarget(_lowercase       ,  run_time=1.5 ) )

												self.play(*_lowercase )
												self.play(*_lowercase )

												self.wait()
