
"""simple docstring"""




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







class   _lowercase						(       UpperCamelCase__				):


					'''simple docstring'''





					def __init__(      self  )->					List[str]:
										# test for the above condition
										self.test()



					def  lowerCAmelCase__       (      self  )->					Dict:
										UpperCAmelCase__							: List[Any] 							=						0
										UpperCAmelCase__							: List[str] 							=						False
										while not completed:
															if counter == 1:
																				self.reset()
															UpperCAmelCase__							: 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."  )

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

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

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



					@abstractmethod
					def  lowerCAmelCase__       (      self  )->					Dict:
										raise NotImplementedError(
										    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."  )



					@abstractmethod
					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Optional[int]:
										raise NotImplementedError(
										    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."  )



					@abstractmethod
					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Any:
										raise NotImplementedError(
										    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."  )



					@abstractmethod
					def  lowerCAmelCase__       (      self  )->					int:
										raise NotImplementedError(
										    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."  )



					@abstractmethod
					def  lowerCAmelCase__       (      self  )->					int:
										raise NotImplementedError(
										    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."  )



					@abstractmethod
					def  lowerCAmelCase__       (      self ,			__UpperCamelCase=False  )->					str:
										raise NotImplementedError(
										    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called."  )







class   _lowercase						(       UpperCamelCase__				):


					'''simple docstring'''





					def __init__(      self ,			__UpperCamelCase  )->					Dict:
										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}."  )

										UpperCAmelCase__							: List[Any] 							=						token_ids

										UpperCAmelCase__							: str 							=						len(self.token_ids  )
										UpperCAmelCase__							: str 							=						-1  # the index of the currently fulfilled step
										UpperCAmelCase__							: Optional[int] 							=						False



					def  lowerCAmelCase__       (      self  )->					Optional[int]:
										if self.completed:
															return None
										return self.token_ids[self.fulfilled_idx + 1]



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					str:
										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  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					int:
										if not isinstance(__UpperCamelCase ,			__UpperCamelCase  ):
															raise ValueError(F"`token_id` has to be an `int`, but is {token_id} of type {type(__UpperCamelCase  )}"  )

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

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



					def  lowerCAmelCase__       (      self  )->					Union[str, Any]:
										UpperCAmelCase__							: Union[str, Any] 							=						False
										UpperCAmelCase__							: str 							=						0



					def  lowerCAmelCase__       (      self  )->					Optional[int]:
										return self.seqlen - (self.fulfilled_idx + 1)



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase=False  )->					Optional[Any]:
										UpperCAmelCase__							: List[Any] 							=						PhrasalConstraint(self.token_ids  )

										if stateful:
															UpperCAmelCase__							: List[Any] 							=						self.seqlen
															UpperCAmelCase__							: str 							=						self.fulfilled_idx
															UpperCAmelCase__							: List[str] 							=						self.completed

										return new_constraint







class   _lowercase						:


					'''simple docstring'''





					def __init__(      self ,			__UpperCamelCase ,			__UpperCamelCase=True  )->					Optional[int]:
										UpperCAmelCase__							: Any 							=						max([len(__UpperCamelCase  ) for one in nested_token_ids]  )

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

																				UpperCAmelCase__							: Tuple 							=						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}."  )

										UpperCAmelCase__							: Dict 							=						root



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					int:
										UpperCAmelCase__							: Tuple 							=						self.trie

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

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

										return next_tokens



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					str:
										UpperCAmelCase__							: List[str] 							=						self.next_tokens(__UpperCamelCase  )

										return len(__UpperCamelCase  ) == 0



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Optional[int]:
										UpperCAmelCase__							: Optional[int] 							=						list(root.values()  )
										if len(__UpperCamelCase  ) == 0:
															return 1
										else:
															return sum([self.count_leaves(__UpperCamelCase  ) for nn in next_nodes]  )



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase  )->					Optional[Any]:
										UpperCAmelCase__							: List[Any] 							=						self.count_leaves(__UpperCamelCase  )
										return len(__UpperCamelCase  ) != leaf_count







class   _lowercase						(       UpperCamelCase__				):


					'''simple docstring'''





					def __init__(      self ,			__UpperCamelCase  )->					List[Any]:
										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}."  )

										UpperCAmelCase__							: int 							=						DisjunctiveTrie(__UpperCamelCase  )
										UpperCAmelCase__							: List[Any] 							=						nested_token_ids

										UpperCAmelCase__							: Dict 							=						self.trie.max_height
										UpperCAmelCase__							: Optional[Any] 							=						[]
										UpperCAmelCase__							: int 							=						False



					def  lowerCAmelCase__       (      self  )->					List[Any]:
										UpperCAmelCase__							: Optional[Any] 							=						self.trie.next_tokens(self.current_seq  )

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



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					List[str]:
										if not isinstance(__UpperCamelCase ,			__UpperCamelCase  ):
															raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(__UpperCamelCase  )}"  )

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

										return token_id in next_tokens



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					int:
										if not isinstance(__UpperCamelCase ,			__UpperCamelCase  ):
															raise ValueError(F"`token_id` is supposed to be type `int`, but is {token_id} of type {type(__UpperCamelCase  )}"  )

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

										if self.does_advance(__UpperCamelCase  ):
															self.current_seq.append(__UpperCamelCase  )
															UpperCAmelCase__							: Tuple 							=						True
										else:
															UpperCAmelCase__							: Optional[Any] 							=						True
															self.reset()

										UpperCAmelCase__							: str 							=						self.trie.reached_leaf(self.current_seq  )
										UpperCAmelCase__							: Tuple 							=						completed

										return stepped, completed, reset



					def  lowerCAmelCase__       (      self  )->					Dict:
										UpperCAmelCase__							: Optional[int] 							=						False
										UpperCAmelCase__							: Any 							=						[]



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



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase=False  )->					Union[str, Any]:
										UpperCAmelCase__							: str 							=						DisjunctiveConstraint(self.token_ids  )

										if stateful:
															UpperCAmelCase__							: Union[str, Any] 							=						self.seqlen
															UpperCAmelCase__							: Tuple 							=						self.current_seq
															UpperCAmelCase__							: List[Any] 							=						self.completed

										return new_constraint







class   _lowercase						:


					'''simple docstring'''





					def __init__(      self ,			__UpperCamelCase  )->					Union[str, Any]:
										UpperCAmelCase__							: Union[str, Any] 							=						constraints

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

										self.init_state()



					def  lowerCAmelCase__       (      self  )->					Union[str, Any]:
										UpperCAmelCase__							: Dict 							=						[]
										UpperCAmelCase__							: Tuple 							=						None
										UpperCAmelCase__							: Union[str, Any] 							=						[constraint.copy(stateful=__UpperCamelCase  ) for constraint in self.constraints]



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

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

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



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Dict:
										if not isinstance(__UpperCamelCase ,			__UpperCamelCase  ):
															raise ValueError(F"`token_id` should be an `int`, but is `{token_id}`."  )

										UpperCAmelCase__							,	UpperCAmelCase__							: Optional[int] 							=						False, False

										if self.completed:
															UpperCAmelCase__							: str 							=						True
															UpperCAmelCase__							: str 							=						False
															return complete, stepped

										if self.inprogress_constraint is not None:
															# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
															# job, simply update the state

															UpperCAmelCase__							,	UpperCAmelCase__							,	UpperCAmelCase__							: int 							=						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  )  )
																				UpperCAmelCase__							: List[str] 							=						None

															if complete:
																				# 2. If the next token completes the constraint, move it to completed list, set
																				#     inprogress to None. If there are no pending constraints either, then this full list of constraints
																				#     is complete.

																				self.complete_constraints.append(self.inprogress_constraint  )
																				UpperCAmelCase__							: Tuple 							=						None

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

																									if not complete and stepped:
																														UpperCAmelCase__							: Tuple 							=						pending_constraint

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

																														UpperCAmelCase__							: str 							=						(
																														    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
																														)

																														if len(self.pending_constraints  ) == 0 and self.inprogress_constraint is None:
																																			# If there's no longer any pending after this and no inprogress either, then we must be
																																			# complete.

																																			UpperCAmelCase__							: List[str] 							=						True

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

										return complete, stepped



					def  lowerCAmelCase__       (      self ,			__UpperCamelCase=True  )->					str:
										UpperCAmelCase__							: str 							=						ConstraintListState(self.constraints  )  # we actually never though self.constraints objects
										# throughout this process. So it's at initialization state.

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

										return new_state





"""simple docstring"""




from manim import *







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     def  lowerCAmelCase__       (      self  )->					Tuple:
          UpperCAmelCase__							: str 							=						Rectangle(height=0.5 ,			width=0.5  )
          UpperCAmelCase__							: List[str] 							=						Rectangle(height=0.46 ,			width=0.46  ).set_stroke(width=0  )

          UpperCAmelCase__							: List[Any] 							=						[mem.copy() for i in range(6  )]
          UpperCAmelCase__							: Union[str, Any] 							=						[mem.copy() for i in range(6  )]
          UpperCAmelCase__							: List[Any] 							=						VGroup(*__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0  )
          UpperCAmelCase__							: int 							=						VGroup(*__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0  )
          UpperCAmelCase__							: Tuple 							=						VGroup(__UpperCamelCase ,			__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0  )
          UpperCAmelCase__							: Tuple 							=						Text("CPU" ,			font_size=24  )
          UpperCAmelCase__							: Any 							=						Group(__UpperCamelCase ,			__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0.5 ,			aligned_edge=__UpperCamelCase  )
          cpu.move_to([-2.5, -0.5, 0]  )
          self.add(__UpperCamelCase  )

          UpperCAmelCase__							: List[Any] 							=						[mem.copy() for i in range(4  )]
          UpperCAmelCase__							: List[str] 							=						VGroup(*__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0  )
          UpperCAmelCase__							: Union[str, Any] 							=						Text("GPU" ,			font_size=24  )
          UpperCAmelCase__							: Dict 							=						Group(__UpperCamelCase ,			__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0.5 ,			aligned_edge=__UpperCamelCase  )
          gpu.move_to([-1, -1, 0]  )
          self.add(__UpperCamelCase  )

          UpperCAmelCase__							: Optional[int] 							=						[mem.copy() for i in range(6  )]
          UpperCAmelCase__							: List[str] 							=						VGroup(*__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0  )

          UpperCAmelCase__							: Tuple 							=						Text("Model" ,			font_size=24  )
          UpperCAmelCase__							: Dict 							=						Group(__UpperCamelCase ,			__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0.5 ,			aligned_edge=__UpperCamelCase  )
          model.move_to([3, -1.0, 0]  )
          self.add(__UpperCamelCase  )

          UpperCAmelCase__							: List[str] 							=						[]
          for i, rect in enumerate(__UpperCamelCase  ):
               rect.set_stroke(__UpperCamelCase  )
               # target = fill.copy().set_fill(YELLOW, opacity=0.7)
               # target.move_to(rect)
               # self.add(target)

               UpperCAmelCase__							: int 							=						Rectangle(height=0.46 / 4 ,			width=0.46 / 3  ).set_stroke(width=0.0  ).set_fill(__UpperCamelCase ,			opacity=0.7  )

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

          UpperCAmelCase__							: List[Any] 							=						[mem.copy() for i in range(6  )]
          UpperCAmelCase__							: Any 							=						VGroup(*__UpperCamelCase  ).arrange(__UpperCamelCase ,			buff=0  )

          UpperCAmelCase__							: Tuple 							=						Text("Loaded Checkpoint" ,			font_size=24  )
          UpperCAmelCase__							: Any 							=						Group(__UpperCamelCase ,			__UpperCamelCase  ).arrange(__UpperCamelCase ,			aligned_edge=__UpperCamelCase ,			buff=0.4  )
          checkpoint.move_to([3, 0.5, 0]  )

          UpperCAmelCase__							: Optional[Any] 							=						Square(side_length=2.2  )
          key.move_to([-5, 2, 0]  )

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

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

          self.add(__UpperCamelCase ,			__UpperCamelCase  )

          UpperCAmelCase__							: str 							=						MarkupText(
              F"<span fgcolor='{BLUE}'>●</span> Checkpoint" ,			font_size=18 ,			)

          blue_text.next_to(__UpperCamelCase ,			DOWN * 2.4 ,			aligned_edge=key_text.get_left()  )

          UpperCAmelCase__							: Optional[Any] 							=						MarkupText(
              F"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." ,			font_size=24 ,			)
          step_a.move_to([2, 2, 0]  )
          self.play(Write(__UpperCamelCase  ) ,			Write(__UpperCamelCase  )  )

          self.play(Write(__UpperCamelCase ,			run_time=1  ) ,			Create(__UpperCamelCase ,			run_time=1  )  )

          UpperCAmelCase__							: Union[str, Any] 							=						[]
          UpperCAmelCase__							: List[str] 							=						[]
          for i, rect in enumerate(__UpperCamelCase  ):
               UpperCAmelCase__							: Optional[Any] 							=						fill.copy().set_fill(__UpperCamelCase ,			opacity=0.7  )
               target.move_to(__UpperCamelCase  )
               first_animations.append(GrowFromCenter(__UpperCamelCase ,			run_time=1  )  )

               UpperCAmelCase__							: List[str] 							=						target.copy()
               cpu_target.generate_target()
               if i < 5:
                    cpu_target.target.move_to(cpu_left_col_base[i + 1]  )
               else:
                    cpu_target.target.move_to(cpu_right_col_base[i - 5]  )
               second_animations.append(MoveToTarget(__UpperCamelCase ,			run_time=1.5  )  )

          self.play(*__UpperCamelCase  )
          self.play(*__UpperCamelCase  )
          self.wait()



