
'''simple docstring'''







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  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self		):


											"""simple docstring"""





											super().__init__()
											lowercase_	:     Optional[int]													=       nn.Linear(3				,							4		)
											lowercase_	:     Optional[Any]													=       nn.BatchNormad(4		)
											lowercase_	:     Dict													=       nn.Linear(4				,							5		)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											return self.lineara(self.batchnorm(self.lineara(__SCREAMING_SNAKE_CASE		)		)		)







class  lowerCAmelCase__   (  unittest.TestCase     ):






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     List[Any]													=       ModelForTest()
											with TemporaryDirectory() as tmp_dir:
																	offload_state_dict(__SCREAMING_SNAKE_CASE				,							model.state_dict()		)
																	lowercase_	:     List[str]													=       os.path.join(__SCREAMING_SNAKE_CASE				,							'''index.json'''		)
																	self.assertTrue(os.path.isfile(__SCREAMING_SNAKE_CASE		)		)
																	# TODO: add tests on what is inside the index

																	for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]:
																							lowercase_	:     Any													=       os.path.join(__SCREAMING_SNAKE_CASE				,							F'''{key}.dat'''		)
																							self.assertTrue(os.path.isfile(__SCREAMING_SNAKE_CASE		)		)
																							# TODO: add tests on the fact weights are properly loaded






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Tuple													=       [torch.floataa, torch.floataa, torch.bfloataa]

											for dtype in dtypes:
																	lowercase_	:     Optional[int]													=       torch.randn(2				,							3				,							dtype=__SCREAMING_SNAKE_CASE		)
																	with TemporaryDirectory() as tmp_dir:
																							lowercase_	:     Optional[Any]													=       offload_weight(__SCREAMING_SNAKE_CASE				,							'''weight'''				,							__SCREAMING_SNAKE_CASE				,							{}		)
																							lowercase_	:     str													=       os.path.join(__SCREAMING_SNAKE_CASE				,							'''weight.dat'''		)
																							self.assertTrue(os.path.isfile(__SCREAMING_SNAKE_CASE		)		)
																							self.assertDictEqual(__SCREAMING_SNAKE_CASE				,							{'''weight''': {'''shape''': [2, 3], '''dtype''': str(__SCREAMING_SNAKE_CASE		).split('''.'''		)[1]}}		)

																							lowercase_	:     int													=       load_offloaded_weight(__SCREAMING_SNAKE_CASE				,							index['''weight''']		)
																							self.assertTrue(torch.equal(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)		)






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     str													=       ModelForTest()
											lowercase_	:     Any													=       model.state_dict()
											lowercase_	:     Dict													=       {k: v for k, v in state_dict.items() if '''linear2''' not in k}
											lowercase_	:     int													=       {k: v for k, v in state_dict.items() if '''linear2''' in k}

											with TemporaryDirectory() as tmp_dir:
																	offload_state_dict(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)
																	lowercase_	:     Dict													=       OffloadedWeightsLoader(state_dict=__SCREAMING_SNAKE_CASE				,							save_folder=__SCREAMING_SNAKE_CASE		)

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

											lowercase_	:     Dict													=       {k: v for k, v in state_dict.items() if '''weight''' in k}
											lowercase_	:     str													=       {k: v for k, v in state_dict.items() if '''weight''' not in k}

											with TemporaryDirectory() as tmp_dir:
																	offload_state_dict(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)
																	lowercase_	:     Any													=       OffloadedWeightsLoader(state_dict=__SCREAMING_SNAKE_CASE				,							save_folder=__SCREAMING_SNAKE_CASE		)

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

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

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






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Optional[Any]													=       {'''a.1''': 0, '''a.10''': 1, '''a.2''': 2}
											lowercase_	:     Dict													=       extract_submodules_state_dict(__SCREAMING_SNAKE_CASE				,							['''a.1''', '''a.2''']		)
											self.assertDictEqual(__SCREAMING_SNAKE_CASE				,							{'''a.1''': 0, '''a.2''': 2}		)

											lowercase_	:     Any													=       {'''a.1.a''': 0, '''a.10.a''': 1, '''a.2.a''': 2}
											lowercase_	:     Optional[int]													=       extract_submodules_state_dict(__SCREAMING_SNAKE_CASE				,							['''a.1''', '''a.2''']		)
											self.assertDictEqual(__SCREAMING_SNAKE_CASE				,							{'''a.1.a''': 0, '''a.2.a''': 2}		)





'''simple docstring'''







_lowercase :  int    							=       [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)]
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: int							):



						"""simple docstring"""





						lowercase_	:     Optional[int]													=       0
						while number:
												# Increased Speed Slightly by checking every 5 digits together.
												sum_of_digits_squared += DIGITS_SQUARED[number % 100000]
												number //= 100000

						return sum_of_digits_squared


# There are 2 Chains made,
# One ends with 89 with the chain member 58 being the one which when declared first,
# there will be the least number of iterations for all the members to be checked.

# The other one ends with 1 and has only one element 1.

# So 58 and 1 are chosen to be declared at the starting.

# Changed dictionary to an array to quicken the solution
_lowercase :  list[bool | None]    							=       [None] * 1_0_0_0_0_0_0_0
_lowercase :  List[str]    							=       True
_lowercase :  Optional[int]    							=       False
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: int							):



						"""simple docstring"""





						if CHAINS[number - 1] is not None:
												return CHAINS[number - 1]  # type: ignore

						lowercase_	:     Tuple													=       chain(next_number(__SCREAMING_SNAKE_CASE							)							)
						lowercase_	:     Union[str, Any]													=       number_chain

						while number < 10000000:
												lowercase_	:     int													=       number_chain
												number *= 10

						return number_chain
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: int = 10000000							):



						"""simple docstring"""





						for i in range(1      ,      __SCREAMING_SNAKE_CASE							):
												if CHAINS[i] is None:
																		chain(i + 1							)

						return CHAINS[:number].count(__SCREAMING_SNAKE_CASE							)


if __name__ == "__main__":
							import doctest

							doctest.testmod()
							print(f"""{solution() = }""")



