






import os
import unittest
from tempfile import TemporaryDirectory

import torch
import torch.nn as nn

from accelerate.utils import (
    OffloadedWeightsLoader,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
)





class 	snake_case__ (							nn.Module				):
	def __init__(    self			)							->				str:
							super().__init__()
							__magic_name__      :       Optional[int]       						= nn.Linear(3      ,       4			)
							__magic_name__      :       Union[str, Any]       						= nn.BatchNormad(4			)
							__magic_name__      :       Union[str, Any]       						= nn.Linear(4      ,       5			)







	def       __magic_name__    (    self      ,       lowerCAmelCase__			)							->				int:
							return self.lineara(self.batchnorm(self.lineara(__a			)			)			)





class 	snake_case__ (							unittest.TestCase				):
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       List[str]       						= ModelForTest()
							with TemporaryDirectory() as tmp_dir:
													offload_state_dict(__a      ,       model.state_dict()			)
													__magic_name__      :       List[str]       						= os.path.join(__a      ,       """index.json"""			)
													self.assertTrue(os.path.isfile(__a			)			)
													# TODO: add tests on what is inside the index

													for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]:
																			__magic_name__      :       List[Any]       						= os.path.join(__a      ,       F'{key}.dat'			)
																			self.assertTrue(os.path.isfile(__a			)			)
																			# TODO: add tests on the fact weights are properly loaded
	def       __magic_name__    (    self			)							->				Optional[int]:
							__magic_name__      :       str       						= [torch.floataa, torch.floataa, torch.bfloataa]

							for dtype in dtypes:
													__magic_name__      :       Tuple       						= torch.randn(2      ,       3      ,       dtype=__a			)
													with TemporaryDirectory() as tmp_dir:
																			__magic_name__      :       Tuple       						= offload_weight(__a      ,       """weight"""      ,       __a      ,       {}			)
																			__magic_name__      :       Dict       						= os.path.join(__a      ,       """weight.dat"""			)
																			self.assertTrue(os.path.isfile(__a			)			)
																			self.assertDictEqual(__a      ,       {"""weight""": {"""shape""": [2, 3], """dtype""": str(__a			).split("""."""			)[1]}}			)

																			__magic_name__      :       int       						= load_offloaded_weight(__a      ,       index["""weight"""]			)
																			self.assertTrue(torch.equal(__a      ,       __a			)			)
	def       __magic_name__    (    self			)							->				Optional[int]:
							__magic_name__      :       Any       						= ModelForTest()
							__magic_name__      :       Union[str, Any]       						= model.state_dict()
							__magic_name__      :       str       						= {k: v for k, v in state_dict.items() if """linear2""" not in k}
							__magic_name__      :       Optional[Any]       						= {k: v for k, v in state_dict.items() if """linear2""" in k}

							with TemporaryDirectory() as tmp_dir:
													offload_state_dict(__a      ,       __a			)
													__magic_name__      :       List[Any]       						= OffloadedWeightsLoader(state_dict=__a      ,       save_folder=__a			)

													# Every key is there with the right value
													self.assertEqual(sorted(__a			)      ,       sorted(state_dict.keys()			)			)
													for key, param in state_dict.items():
																			self.assertTrue(torch.allclose(__a      ,       weight_map[key]			)			)

							__magic_name__      :       List[Any]       						= {k: v for k, v in state_dict.items() if """weight""" in k}
							__magic_name__      :       Optional[int]       						= {k: v for k, v in state_dict.items() if """weight""" not in k}

							with TemporaryDirectory() as tmp_dir:
													offload_state_dict(__a      ,       __a			)
													__magic_name__      :       List[str]       						= OffloadedWeightsLoader(state_dict=__a      ,       save_folder=__a			)

													# Every key is there with the right value
													self.assertEqual(sorted(__a			)      ,       sorted(state_dict.keys()			)			)
													for key, param in state_dict.items():
																			self.assertTrue(torch.allclose(__a      ,       weight_map[key]			)			)

							with TemporaryDirectory() as tmp_dir:
													offload_state_dict(__a      ,       __a			)
													# Duplicates are removed
													__magic_name__      :       Dict       						= OffloadedWeightsLoader(state_dict=__a      ,       save_folder=__a			)

													# Every key is there with the right value
													self.assertEqual(sorted(__a			)      ,       sorted(state_dict.keys()			)			)
													for key, param in state_dict.items():
																			self.assertTrue(torch.allclose(__a      ,       weight_map[key]			)			)







	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       Dict       						= {"""a.1""": 0, """a.10""": 1, """a.2""": 2}
							__magic_name__      :       str       						= extract_submodules_state_dict(__a      ,       ["""a.1""", """a.2"""]			)
							self.assertDictEqual(__a      ,       {"""a.1""": 0, """a.2""": 2}			)

							__magic_name__      :       Optional[Any]       						= {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2}
							__magic_name__      :       str       						= extract_submodules_state_dict(__a      ,       ["""a.1""", """a.2"""]			)
							self.assertDictEqual(__a      ,       {"""a.1.a""": 0, """a.2.a""": 2}			)








from manim import *





class 	snake_case__ (							_lowerCAmelCase				):
	def       __magic_name__    (    self			)							->				Dict:
							__magic_name__      :       int       						= Rectangle(height=0.5      ,       width=0.5			)
							__magic_name__      :       Optional[int]       						= Rectangle(height=0.2_5      ,       width=0.2_5			)
							__magic_name__      :       str       						= Rectangle(height=0.4_6      ,       width=0.4_6			).set_stroke(width=0			)

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

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

							__magic_name__      :       Union[str, Any]       						= [mem.copy() for i in range(6			)]
							__magic_name__      :       Union[str, Any]       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)

							__magic_name__      :       str       						= Text("""Model"""      ,       font_size=24			)
							__magic_name__      :       Optional[int]       						= Group(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0.5      ,       aligned_edge=lowerCAmelCase__			)
							model.move_to([3, -1.0, 0]			)
							self.add(lowerCAmelCase__			)

							__magic_name__      :       str       						= []
							__magic_name__      :       Tuple       						= []
							__magic_name__      :       Union[str, Any]       						= []

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

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

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

							self.add(*lowerCAmelCase__      ,       *lowerCAmelCase__      ,       *lowerCAmelCase__			)

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

							__magic_name__      :       Any       						= Text("""Loaded Checkpoint"""      ,       font_size=24			)
							__magic_name__      :       Optional[int]       						= Group(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0.5      ,       aligned_edge=lowerCAmelCase__			)
							checkpoint.move_to([3, 0.5, 0]			)

							self.add(lowerCAmelCase__			)

							__magic_name__      :       Optional[int]       						= []
							__magic_name__      :       Tuple       						= []

							for i, rect in enumerate(lowerCAmelCase__			):
													__magic_name__      :       Dict       						= fill.copy().set_fill(lowerCAmelCase__      ,       opacity=0.7			)
													target.move_to(lowerCAmelCase__			)
													ckpt_arr.append(lowerCAmelCase__			)

													__magic_name__      :       int       						= target.copy()
													if i < 5:
																			cpu_target.move_to(cpu_left_col_base[i + 1]			)
													else:
																			cpu_target.move_to(cpu_right_col_base[i - 5]			)
													ckpt_cpu_arr.append(lowerCAmelCase__			)
							self.add(*lowerCAmelCase__      ,       *lowerCAmelCase__			)

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

							__magic_name__      :       str       						= 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(lowerCAmelCase__      ,       lowerCAmelCase__			)

							__magic_name__      :       Any       						= MarkupText(
							    F'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint'      ,       font_size=18      ,       )

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

							__magic_name__      :       Optional[Any]       						= MarkupText(
							    F'Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.'      ,       font_size=24      ,       )
							step_a.move_to([2, 2, 0]			)

							__magic_name__      :       int       						= [meta_mem.copy() for i in range(6			)]
							__magic_name__      :       Union[str, Any]       						= [meta_mem.copy() for i in range(6			)]
							__magic_name__      :       Any       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       str       						= VGroup(*lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       Tuple       						= VGroup(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0			)
							__magic_name__      :       int       						= Text("""Disk"""      ,       font_size=24			)
							__magic_name__      :       Union[str, Any]       						= Group(lowerCAmelCase__      ,       lowerCAmelCase__			).arrange(lowerCAmelCase__      ,       buff=0.5      ,       aligned_edge=lowerCAmelCase__			)
							disk.move_to([-4.0, -1.2_5, 0]			)
							self.play(Write(lowerCAmelCase__      ,       run_time=3			)      ,       Write(lowerCAmelCase__      ,       run_time=1			)      ,       Create(lowerCAmelCase__      ,       run_time=1			)			)

							__magic_name__      :       List[Any]       						= []
							for i, rect in enumerate(lowerCAmelCase__			):
													__magic_name__      :       Dict       						= rect.copy()
													target.generate_target()
													target.target.move_to(disk_left_col_base[i]			).scale(0.5			)
													animations.append(MoveToTarget(lowerCAmelCase__      ,       run_time=1.5			)			)
							self.play(*lowerCAmelCase__			)

							self.play(FadeOut(lowerCAmelCase__			)			)

							__magic_name__      :       str       						= MarkupText(F'Then, the checkpoint is removed from memory\nthrough garbage collection.'      ,       font_size=24			)
							step_a.move_to([2, 2, 0]			)

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

							self.play(
							    FadeOut(lowerCAmelCase__      ,       lowerCAmelCase__      ,       *lowerCAmelCase__      ,       *lowerCAmelCase__			)      ,       )

							self.wait()
