





"""simple docstring"""






import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


__UpperCAmelCase						=			logging.getLogger(__name__)






def      lowercase__ (					lowerCAmelCase__   :			Tuple=2							,			lowerCAmelCase__   :			str=3							,			lowerCAmelCase__   :			Optional[Any]=1_6							,			lowerCAmelCase__   :			int = 1_0							,			lowerCAmelCase__   :			int = 2			)    ->			str:



			'''simple docstring'''

			def get_dataset(lowerCAmelCase__   :			List[str]			):
						a__  :	str		 =			torch.randn(batch_size * n_batches							,			1			)
						return TensorDataset(lowerCAmelCase__							,			a * x + b + 0.1 * torch.randn(batch_size * n_batches							,			1			)			)

			a__  :	Union[str, Any]		 =			get_dataset(lowerCAmelCase__			)
			a__  :	str		 =			get_dataset(lowerCAmelCase__			)
			a__  :	List[str]		 =			DataLoader(lowerCAmelCase__							,			shuffle=lowerCAmelCase__							,			batch_size=lowerCAmelCase__							,			num_workers=4			)
			a__  :	Optional[int]		 =			DataLoader(lowerCAmelCase__							,			shuffle=lowerCAmelCase__							,			batch_size=lowerCAmelCase__							,			num_workers=4			)
			return (train_dataloader, valid_dataloader)






def      lowercase__ (					lowerCAmelCase__   :			Any							,			lowerCAmelCase__   :			Any							,			lowerCAmelCase__   :			Any							,			lowerCAmelCase__   :			Dict							,			lowerCAmelCase__   :			Optional[Any]							,			lowerCAmelCase__   :			List[str]=None			)    ->			str:



			'''simple docstring'''
			a__  :	int		 =			[]
			for epoch in range(lowerCAmelCase__			):
						# Train quickly
						model.train()
						for batch in dataloader:
									a__ ,	a__  :	Union[str, Any]		 =			batch
									a__  :	int		 =			model(lowerCAmelCase__			)
									a__  :	int		 =			torch.nn.functional.mse_loss(lowerCAmelCase__							,			lowerCAmelCase__			)
									accelerator.backward(lowerCAmelCase__			)
									optimizer.step()
									optimizer.zero_grad()
						rands.append(random.random()			)  # Introduce some randomness
						if scheduler is not None:
									scheduler.step()
			return rands



class 					__UpperCAmelCase							(						nn.Module  ):
				def __init__(		self    :			Union[str, Any]    )	->	str:



							'''simple docstring'''



							super().__init__()
							a__  :	Dict		 =			nn.Parameter(torch.randn(1    )    )
							a__  :	List[str]		 =			nn.Parameter(torch.randn(1    )    )






				def       UpperCAmelCase      (		self    :			str	, a_    :			int    )	->	List[Any]:



							'''simple docstring'''



							return x * self.a + self.b



class 					__UpperCAmelCase							(						unittest.TestCase  ):
				def       UpperCAmelCase      (		self    :			Optional[int]    )	->	str:



							'''simple docstring'''



							with tempfile.TemporaryDirectory() as tmpdir:
										set_seed(42    )
										a__  :	int		 =			DummyModel()
										a__  :	Optional[Any]		 =			torch.optim.Adam(params=model.parameters()	, lr=1E-3    )
										a__ ,	a__  :	str		 =			dummy_dataloaders()
										a__  :	Any		 =			ProjectConfiguration(total_limit=1	, project_dir=a_	, automatic_checkpoint_naming=a_    )
										# Train baseline
										a__  :	List[Any]		 =			Accelerator(project_config=a_    )
										a__ ,	a__ ,	a__ ,	a__  :	Union[str, Any]		 =			accelerator.prepare(
										    a_	, a_	, a_	, a_    )
										# Save initial
										accelerator.save_state()

										# Save second state
										accelerator.save_state()
										self.assertEqual(len(os.listdir(accelerator.project_dir    )    )	, 1    )
				def       UpperCAmelCase      (		self    :			Dict    )	->	Tuple:



							'''simple docstring'''



							with tempfile.TemporaryDirectory() as tmpdir:
										set_seed(42    )
										a__  :	Union[str, Any]		 =			DummyModel()
										a__  :	int		 =			torch.optim.Adam(params=model.parameters()	, lr=1E-3    )
										a__ ,	a__  :	List[str]		 =			dummy_dataloaders()
										# Train baseline
										a__  :	str		 =			Accelerator()
										a__ ,	a__ ,	a__ ,	a__  :	List[Any]		 =			accelerator.prepare(
										    a_	, a_	, a_	, a_    )
										# Save initial
										a__  :	str		 =			os.path.join(a_	, "initial"    )
										accelerator.save_state(a_    )
										((a__) ,	(a__))  :	str		 =			model.a.item(), model.b.item()
										a__  :	Optional[int]		 =			optimizer.state_dict()
										a__  :	List[str]		 =			train(3	, a_	, a_	, a_	, a_    )
										((a__) ,	(a__))  :	Tuple		 =			model.a.item(), model.b.item()
										a__  :	List[Any]		 =			optimizer.state_dict()

										# Train partially
										set_seed(42    )
										a__  :	str		 =			DummyModel()
										a__  :	Tuple		 =			torch.optim.Adam(params=model.parameters()	, lr=1E-3    )
										a__ ,	a__  :	List[str]		 =			dummy_dataloaders()
										a__  :	List[str]		 =			Accelerator()
										a__ ,	a__ ,	a__ ,	a__  :	Union[str, Any]		 =			accelerator.prepare(
										    a_	, a_	, a_	, a_    )
										accelerator.load_state(a_    )
										((a__) ,	(a__))  :	Optional[Any]		 =			model.a.item(), model.b.item()
										a__  :	Union[str, Any]		 =			optimizer.state_dict()
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )

										a__  :	List[str]		 =			train(2	, a_	, a_	, a_	, a_    )
										# Save everything
										a__  :	Dict		 =			os.path.join(a_	, "checkpoint"    )
										accelerator.save_state(a_    )

										# Load everything back in and make sure all states work
										accelerator.load_state(a_    )
										test_rands += train(1	, a_	, a_	, a_	, a_    )
										((a__) ,	(a__))  :	str		 =			model.a.item(), model.b.item()
										a__  :	int		 =			optimizer.state_dict()
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )
				def       UpperCAmelCase      (		self    :			Optional[Any]    )	->	Tuple:



							'''simple docstring'''



							with tempfile.TemporaryDirectory() as tmpdir:
										set_seed(42    )
										a__  :	List[str]		 =			DummyModel()
										a__  :	List[Any]		 =			torch.optim.Adam(params=model.parameters()	, lr=1E-3    )
										a__ ,	a__  :	int		 =			dummy_dataloaders()
										a__  :	List[str]		 =			ProjectConfiguration(automatic_checkpoint_naming=a_    )

										# Train baseline
										a__  :	Union[str, Any]		 =			Accelerator(project_dir=a_	, project_config=a_    )
										a__ ,	a__ ,	a__ ,	a__  :	List[Any]		 =			accelerator.prepare(
										    a_	, a_	, a_	, a_    )
										# Save initial
										accelerator.save_state()
										((a__) ,	(a__))  :	Tuple		 =			model.a.item(), model.b.item()
										a__  :	List[str]		 =			optimizer.state_dict()
										a__  :	Optional[Any]		 =			train(3	, a_	, a_	, a_	, a_    )
										((a__) ,	(a__))  :	str		 =			model.a.item(), model.b.item()
										a__  :	List[str]		 =			optimizer.state_dict()

										# Train partially
										set_seed(42    )
										a__  :	int		 =			DummyModel()
										a__  :	List[Any]		 =			torch.optim.Adam(params=model.parameters()	, lr=1E-3    )
										a__ ,	a__  :	Optional[int]		 =			dummy_dataloaders()
										a__  :	str		 =			ProjectConfiguration(iteration=1	, automatic_checkpoint_naming=a_    )
										a__  :	List[str]		 =			Accelerator(project_dir=a_	, project_config=a_    )
										a__ ,	a__ ,	a__ ,	a__  :	Tuple		 =			accelerator.prepare(
										    a_	, a_	, a_	, a_    )
										accelerator.load_state(os.path.join(a_	, "checkpoints"	, "checkpoint_0"    )    )
										((a__) ,	(a__))  :	int		 =			model.a.item(), model.b.item()
										a__  :	Any		 =			optimizer.state_dict()
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )

										a__  :	Optional[int]		 =			train(2	, a_	, a_	, a_	, a_    )
										# Save everything
										accelerator.save_state()

										# Load everything back in and make sure all states work
										accelerator.load_state(os.path.join(a_	, "checkpoints"	, "checkpoint_1"    )    )
										test_rands += train(1	, a_	, a_	, a_	, a_    )
										((a__) ,	(a__))  :	Dict		 =			model.a.item(), model.b.item()
										a__  :	Optional[Any]		 =			optimizer.state_dict()
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )
										self.assertEqual(a_	, a_    )
				def       UpperCAmelCase      (		self    :			Any    )	->	Any:



							'''simple docstring'''



							a__  :	Any		 =			torch.tensor([1, 2, 3]    )
							a__  :	str		 =			torch.tensor([2, 3, 4]    )
							a__  :	Tuple		 =			DummyModel()
							a__  :	Dict		 =			torch.optim.Adam(net.parameters()    )
							a__  :	List[Any]		 =			Accelerator()
							with self.assertRaises(a_    ) as ve:
										accelerator.register_for_checkpointing(a_	, a_	, a_	, a_    )
							a__  :	Optional[int]		 =			str(ve.exception    )
							self.assertTrue("Item at index 0" in message    )
							self.assertTrue("Item at index 1" in message    )
							self.assertFalse("Item at index 2" in message    )
							self.assertFalse("Item at index 3" in message    )
				def       UpperCAmelCase      (		self    :			Tuple    )	->	Tuple:



							'''simple docstring'''



							with tempfile.TemporaryDirectory() as tmpdir:
										set_seed(42    )
										a__  :	Union[str, Any]		 =			DummyModel()
										a__  :	int		 =			torch.optim.Adam(params=model.parameters()	, lr=1E-3    )
										a__  :	Union[str, Any]		 =			torch.optim.lr_scheduler.StepLR(a_	, step_size=1	, gamma=0.99    )
										a__ ,	a__  :	Tuple		 =			dummy_dataloaders()
										a__  :	int		 =			ProjectConfiguration(automatic_checkpoint_naming=a_    )
										# Train baseline
										a__  :	List[Any]		 =			Accelerator(project_dir=a_	, project_config=a_    )
										a__ ,	a__ ,	a__ ,	a__ ,	a__  :	List[str]		 =			accelerator.prepare(
										    a_	, a_	, a_	, a_	, a_    )
										# Save initial
										accelerator.save_state()
										a__  :	Optional[Any]		 =			scheduler.state_dict()
										train(3	, a_	, a_	, a_	, a_	, a_    )
										self.assertNotEqual(a_	, scheduler.state_dict()    )

										# Load everything back in and make sure all states work
										accelerator.load_state(os.path.join(a_	, "checkpoints"	, "checkpoint_0"    )    )
										self.assertEqual(a_	, scheduler.state_dict()    )
				def       UpperCAmelCase      (		self    :			Optional[int]    )	->	Dict:



							'''simple docstring'''



							with tempfile.TemporaryDirectory() as tmpdir:
										set_seed(42    )
										a__  :	Optional[Any]		 =			DummyModel()
										a__  :	Union[str, Any]		 =			ProjectConfiguration(automatic_checkpoint_naming=a_	, total_limit=2    )
										# Train baseline
										a__  :	Dict		 =			Accelerator(project_dir=a_	, project_config=a_    )
										a__  :	Tuple		 =			accelerator.prepare(a_    )
										# Save 3 states:
										for _ in range(11    ):
													accelerator.save_state()
										self.assertTrue(not os.path.exists(os.path.join(a_	, "checkpoints"	, "checkpoint_0"    )    )    )
										self.assertTrue(os.path.exists(os.path.join(a_	, "checkpoints"	, "checkpoint_9"    )    )    )
										self.assertTrue(os.path.exists(os.path.join(a_	, "checkpoints"	, "checkpoint_10"    )    )    )






				@require_cuda
				def       UpperCAmelCase      (		self    :			Tuple    )	->	int:



							'''simple docstring'''



							a__  :	Any		 =			["torchrun", F"--nproc_per_node={torch.cuda.device_count()}", inspect.getfile(self.__class__    )]
							execute_subprocess_async(a_	, env=os.environ.copy()    )


if __name__ == "__main__":
		__UpperCAmelCase						=			'''/tmp/accelerate/state_checkpointing'''
		__UpperCAmelCase						=			DummyModel()
		__UpperCAmelCase						=			torch.optim.Adam(params=model.parameters(), lr=1e-3)
		__UpperCAmelCase						=			torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
		__UpperCAmelCase	,	__UpperCAmelCase						=			dummy_dataloaders()
		__UpperCAmelCase						=			ProjectConfiguration(automatic_checkpoint_naming=True)
		# Train baseline
		__UpperCAmelCase						=			Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='''no''')
		if accelerator.process_index == 0:
				if os.path.exists(savedir):
						shutil.rmtree(savedir)
				os.makedirs(savedir)
		__UpperCAmelCase	,	__UpperCAmelCase	,	__UpperCAmelCase	,	__UpperCAmelCase	,	__UpperCAmelCase						=			accelerator.prepare(
		    model, optimizer, train_dataloader, valid_dataloader, scheduler
		)
		__UpperCAmelCase	,	__UpperCAmelCase						=			accelerator.prepare(model, optimizer)
		train(3, model, train_dataloader, optimizer, accelerator, scheduler)
		# Check that the intial optimizer is loaded on the GPU
		for group in optimizer.param_groups:
				__UpperCAmelCase						=			group['''params'''][0].device
				break
		assert param_device.type == accelerator.device.type
		__UpperCAmelCase						=			model.cpu()
		accelerator.wait_for_everyone()
		accelerator.save_state()
		accelerator.wait_for_everyone()

		# Check CPU state
		accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''cpu''')
		for group in optimizer.param_groups:
				__UpperCAmelCase						=			group['''params'''][0].device
				break
		assert (
		    param_device.type == torch.device('''cpu''').type
		), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

		# Check device state
		model.to(accelerator.device)
		accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''on_device''')
		for group in optimizer.param_groups:
				__UpperCAmelCase						=			group['''params'''][0].device
				break
		assert (
		    param_device.type == accelerator.device.type
		), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

		# Check error
		with pytest.raises(TypeError, match='''Unsupported optimizer map location passed'''):
				accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''invalid''')
		accelerator.wait_for_everyone()
		if accelerator.process_index == 0:
				shutil.rmtree(savedir)
		accelerator.wait_for_everyone()






"""simple docstring"""






def      lowercase__ (					lowerCAmelCase__   :			str			)    ->			list[int]:



			'''simple docstring'''
			a__  :	List[str]		 =			[0 for i in range(len(lowerCAmelCase__			)			)]

			# initialize interval's left pointer and right pointer
			a__ ,	a__  :	int		 =			0, 0

			for i in range(1							,			len(lowerCAmelCase__			)			):
						# case when current index is inside the interval
						if i <= right_pointer:
									a__  :	List[Any]		 =			min(right_pointer - i + 1							,			z_result[i - left_pointer]			)
									a__  :	List[str]		 =			min_edge

						while go_next(lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__			):
									z_result[i] += 1

						# if new index's result gives us more right interval,
						# we've to update left_pointer and right_pointer
						if i + z_result[i] - 1 > right_pointer:
									a__ ,	a__  :	str		 =			i, i + z_result[i] - 1

			return z_result






def      lowercase__ (					lowerCAmelCase__   :			int							,			lowerCAmelCase__   :			list[int]							,			lowerCAmelCase__   :			str			)    ->			bool:



			'''simple docstring'''
			return i + z_result[i] < len(lowerCAmelCase__			) and s[z_result[i]] == s[i + z_result[i]]






def      lowercase__ (					lowerCAmelCase__   :			str							,			lowerCAmelCase__   :			str			)    ->			int:



			'''simple docstring'''
			a__  :	List[Any]		 =			0
			# concatenate 'pattern' and 'input_str' and call z_function
			# with concatenated string
			a__  :	List[str]		 =			z_function(pattern + input_str			)

			for val in z_result:
						# if value is greater then length of the pattern string
						# that means this index is starting position of substring
						# which is equal to pattern string
						if val >= len(lowerCAmelCase__			):
									answer += 1

			return answer


if __name__ == "__main__":
		import doctest

		doctest.testmod()