





'''simple docstring'''







import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union


class        __a   (enum.Enum  ):
							__a       : Tuple          =							"timm"
							__a       : Tuple          =							"transformers"





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[Iterable[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Iterable[int]],      SCREAMING_SNAKE_CASE__   :      Optional[Iterable[str]] )			->						int:
						if stage_names is None:
												raise ValueError('''Stage_names must be set for transformers backbones''' )

						if out_features is not None:
												if not isinstance(SCREAMING_SNAKE_CASE__,      (list,) ):
																		raise ValueError(F"""out_features must be a list {type(SCREAMING_SNAKE_CASE__ )}""" )
												if any(feat not in stage_names for feat in out_features ):
																		raise ValueError(F"""out_features must be a subset of stage_names: {stage_names} got {out_features}""" )

						if out_indices is not None:
												if not isinstance(SCREAMING_SNAKE_CASE__,      (list, tuple) ):
																		raise ValueError(F"""out_indices must be a list or tuple, got {type(SCREAMING_SNAKE_CASE__ )}""" )
												if any(idx >= len(SCREAMING_SNAKE_CASE__ ) for idx in out_indices ):
																		raise ValueError('''out_indices must be valid indices for stage_names {stage_names}, got {out_indices}''' )

						if out_features is not None and out_indices is not None:
												if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ):
																		raise ValueError('''out_features and out_indices should have the same length if both are set''' )
												if out_features != [stage_names[idx] for idx in out_indices]:
																		raise ValueError('''out_features and out_indices should correspond to the same stages if both are set''' )





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[List[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Union[List[int], Tuple[int]]],      SCREAMING_SNAKE_CASE__   :      List[str],      )			->						Optional[Any]:
						if out_indices is None and out_features is None:
												UpperCAmelCase_      :   Union[str, Any]      =	[len(SCREAMING_SNAKE_CASE__ ) - 1]
												UpperCAmelCase_      :   str      =	[stage_names[-1]]
						elif out_indices is None and out_features is not None:
												UpperCAmelCase_      :   List[str]      =	[stage_names.index(SCREAMING_SNAKE_CASE__ ) for layer in out_features]
						elif out_features is None and out_indices is not None:
												UpperCAmelCase_      :   List[str]      =	[stage_names[idx] for idx in out_indices]
						return out_features, out_indices





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[List[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Union[List[int], Tuple[int]]],      SCREAMING_SNAKE_CASE__   :      List[str],      )			->						Tuple[List[str], List[int]]:
						verify_out_features_out_indices(out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_    ,							UpperCAmelCase_      :   Dict      =	_align_output_features_output_indices(
						    out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						# Verify that the aligned out_features and out_indices are valid
						verify_out_features_out_indices(out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						return output_features, output_indices


class        __a   :
							__a       : Optional[BackboneType]          =							None

							def      UpperCAmelCase__						(				self				:  Dict							,  __magic_name__				:  List[Any] )       ->							None:







													"""simple docstring"""
													if getattr(self							,  '''_backbone'''							,  __magic_name__ ) is None:
																			raise ValueError('''self._backbone must be set before calling _init_timm_backbone''' )

													# These will diagree with the defaults for the transformers models e.g. for resnet50
													# the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
													# the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
													UpperCAmelCase_      :   int      =	[stage['''module'''] for stage in self._backbone.feature_info.info]
													UpperCAmelCase_      :   Tuple      =	[stage['''num_chs'''] for stage in self._backbone.feature_info.info]
													UpperCAmelCase_      :   List[Any]      =	self._backbone.feature_info.out_indices
													UpperCAmelCase_      :   Any      =	self._backbone.feature_info.module_name()

													# We verify the out indices and out features are valid
													verify_out_features_out_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )
													UpperCAmelCase_    ,							UpperCAmelCase_      :   Optional[Any]      =	out_features, out_indices

							def      UpperCAmelCase__						(				self				:  str							,  __magic_name__				:  Dict )       ->							None:







													"""simple docstring"""
													UpperCAmelCase_      :   str      =	getattr(__magic_name__							,  '''stage_names''' )
													UpperCAmelCase_      :   Tuple      =	getattr(__magic_name__							,  '''out_features'''							,  __magic_name__ )
													UpperCAmelCase_      :   Union[str, Any]      =	getattr(__magic_name__							,  '''out_indices'''							,  __magic_name__ )

													UpperCAmelCase_      :   List[str]      =	stage_names
													UpperCAmelCase_    ,							UpperCAmelCase_      :   str      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=__magic_name__ )
													# Number of channels for each stage. This is set in the transformer backbone model init
													UpperCAmelCase_      :   List[str]      =	None

							def      UpperCAmelCase__						(				self				:  Any							,  __magic_name__				:  Tuple )       ->							None:







													"""simple docstring"""
													UpperCAmelCase_      :   int      =	config

													UpperCAmelCase_      :   str      =	getattr(__magic_name__							,  '''use_timm_backbone'''							,  __magic_name__ )
													UpperCAmelCase_      :   str      =	BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

													if self.backbone_type == BackboneType.TIMM:
																			self._init_timm_backbone(__magic_name__ )
													elif self.backbone_type == BackboneType.TRANSFORMERS:
																			self._init_transformers_backbone(__magic_name__ )
													else:
																			raise ValueError(F"""backbone_type {self.backbone_type} not supported.""" )

							@property
							def      UpperCAmelCase__						(				self				:  List[Any] )       ->							Optional[Any]:







													"""simple docstring"""
													return self._out_features

							@out_features.setter
							def      UpperCAmelCase__						(				self				:  int							,  __magic_name__				:  List[str] )       ->							List[str]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   Union[str, Any]      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  int )       ->							List[Any]:







													"""simple docstring"""
													return self._out_indices

							@out_indices.setter
							def      UpperCAmelCase__						(				self				:  Union[str, Any]							,  __magic_name__				:  Union[Tuple[int], List[int]] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   int      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  int )       ->							Optional[int]:







													"""simple docstring"""
													# the current backbones will output the number of channels for each stage
													# even if that stage is not in the out_features list.
													return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names )}

							@property
							def      UpperCAmelCase__						(				self				:  Tuple )       ->							Optional[Any]:







													"""simple docstring"""
													return [self.out_feature_channels[name] for name in self.out_features]

							def      UpperCAmelCase__						(				self				:  Any							,  *__magic_name__				:  Optional[int]							,  **__magic_name__				:  Dict )       ->							int:







													"""simple docstring"""
													UpperCAmelCase_      :   Tuple      =	dict(inspect.signature(self.forward ).parameters )
													UpperCAmelCase_      :   Optional[Any]      =	{k: v for k, v in kwargs.items() if k in signature}
													return self(*__magic_name__							,  **__magic_name__ )

							def      UpperCAmelCase__						(				self				:  Union[str, Any]							,  __magic_name__				:  List[str]							,  __magic_name__				:  Optional[bool] = None							,  __magic_name__				:  Optional[bool] = None							,  __magic_name__				:  Optional[bool] = None							,  )       ->							List[Any]:







													"""simple docstring"""
													raise NotImplementedError('''This method should be implemented by the derived class.''' )



							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_      :   List[Any]      =	super().to_dict()
													UpperCAmelCase_      :   List[Any]      =	output.pop('''_out_features''' )
													UpperCAmelCase_      :   Tuple      =	output.pop('''_out_indices''' )
													return output





class        __a   :

							@property
							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							str:







													"""simple docstring"""
													return self._out_features

							@out_features.setter
							def      UpperCAmelCase__						(				self				:  int							,  __magic_name__				:  List[str] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   List[Any]      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							int:







													"""simple docstring"""
													return self._out_indices

							@out_indices.setter
							def      UpperCAmelCase__						(				self				:  List[Any]							,  __magic_name__				:  Union[Tuple[int], List[int]] )       ->							str:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   str      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )



							def      UpperCAmelCase__						(				self				:  Union[str, Any] )       ->							int:







													"""simple docstring"""
													UpperCAmelCase_      :   str      =	super().to_dict()
													UpperCAmelCase_      :   Union[str, Any]      =	output.pop('''_out_features''' )
													UpperCAmelCase_      :   Any      =	output.pop('''_out_indices''' )
													return output












'''simple docstring'''







from manim import *


class        __a   (lowerCamelCase  ):

							def      UpperCAmelCase__						(				self				:  str )       ->							Any:







													"""simple docstring"""
													UpperCAmelCase_      :   List[str]      =	Rectangle(height=0.5							,  width=0.5 )
													UpperCAmelCase_      :   int      =	Rectangle(height=0.4_6							,  width=0.4_6 ).set_stroke(width=0 )
													UpperCAmelCase_      :   str      =	Rectangle(height=0.2_5							,  width=0.2_5 )

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

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

													UpperCAmelCase_      :   Dict      =	[mem.copy() for i in range(6 )]
													UpperCAmelCase_      :   Optional[Any]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )

													UpperCAmelCase_      :   Dict      =	Text('''Model'''							,  font_size=24 )
													UpperCAmelCase_      :   str      =	Group(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0.5							,  aligned_edge=__magic_name__ )
													model.move_to([3, -1.0, 0] )
													self.add(__magic_name__ )

													UpperCAmelCase_      :   List[str]      =	[]
													UpperCAmelCase_      :   int      =	[]

													for i, rect in enumerate(__magic_name__ ):
																			rect.set_stroke(__magic_name__ )

																			UpperCAmelCase_      :   List[Any]      =	Rectangle(height=0.4_6 / 4							,  width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(__magic_name__							,  opacity=0.7 )

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

													self.add(*__magic_name__							,  *__magic_name__ )

													UpperCAmelCase_      :   Any      =	[meta_mem.copy() for i in range(6 )]
													UpperCAmelCase_      :   int      =	[meta_mem.copy() for i in range(6 )]
													UpperCAmelCase_      :   Optional[Any]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   Optional[int]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   Dict      =	VGroup(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   Optional[Any]      =	Text('''Disk'''							,  font_size=24 )
													UpperCAmelCase_      :   Any      =	Group(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0.5							,  aligned_edge=__magic_name__ )
													disk.move_to([-4.0, -1.2_5, 0] )
													self.add(__magic_name__							,  __magic_name__ )

													UpperCAmelCase_      :   Optional[Any]      =	[]

													for i in range(6 ):
																			UpperCAmelCase_      :   Tuple      =	fill.copy().set_fill(__magic_name__							,  opacity=0.8 )
																			target.move_to(disk_left_col_base[i] ).scale(0.5 )
																			cpu_disk_arr.append(__magic_name__ )

													self.add(*__magic_name__ )

													UpperCAmelCase_      :   List[str]      =	Square(side_length=2.2 )
													key.move_to([-5, 2, 0] )

													UpperCAmelCase_      :   Union[str, 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(__magic_name__							,  __magic_name__ )

													UpperCAmelCase_      :   Union[str, Any]      =	MarkupText(
													    F"""<span fgcolor='{BLUE}'>●</span> Checkpoint"""							,  font_size=18							,  )

													blue_text.next_to(__magic_name__							,  DOWN * 2.4							,  aligned_edge=key_text.get_left() )
													self.add(__magic_name__ )

													UpperCAmelCase_      :   Dict      =	MarkupText(F"""The offloaded weights are all sent to the CPU."""							,  font_size=24 )
													step_a.move_to([2, 2, 0] )

													self.play(Write(__magic_name__							,  run_time=3 ) )

													for i in range(6 ):
																			UpperCAmelCase_      :   Dict      =	cpu_disk_arr[i]
																			UpperCAmelCase_      :   int      =	rect.copy().set_fill(__magic_name__							,  opacity=0.8 ).scale(2.0 )
																			cpa.generate_target()
																			cpa.target.move_to(model_base[i] )

																			if i == 0:
																									rect.set_fill(__magic_name__							,  opacity=0.8 )
																									rect.generate_target()
																									rect.target.move_to(cpu_left_col_base[0] ).scale(2.0 )

																									self.remove(
																									    *__magic_name__							,  *__magic_name__							,  )

																			else:
																									rect.generate_target()
																									rect.target.move_to(cpu_left_col_base[i] ).scale(2.0 )
																			self.play(MoveToTarget(__magic_name__ )							,  MoveToTarget(__magic_name__ )							,  model_base[i].animate.set_stroke(__magic_name__ ) )
													self.play(FadeOut(__magic_name__ ) )

													UpperCAmelCase_      :   int      =	MarkupText(
													    F"""Finally, hooks are added to each weight in the model\nto transfer the weights from CPU to GPU\n\t\tand back when needed."""							,  font_size=24							,  )
													step_a.move_to([2, 2, 0] )

													self.play(Write(__magic_name__							,  run_time=3 ) )

													UpperCAmelCase_      :   Union[str, Any]      =	[]
													UpperCAmelCase_      :   Tuple      =	[]
													for i in range(6 ):
																			UpperCAmelCase_      :   List[Any]      =	Arrow(start=__magic_name__							,  end=__magic_name__							,  color=__magic_name__							,  buff=0.5 )
																			a.next_to(model_base[i].get_left()							,  __magic_name__							,  buff=0.2 )
																			arrows.append(__magic_name__ )
																			animations.append(Write(__magic_name__ ) )
													self.play(*__magic_name__ )
													self.wait()





