"""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


SCREAMING_SNAKE_CASE__      						=  logging.getLogger(__name__)





def    lowerCAmelCase__    (			_UpperCamelCase       :				str=2 ,			_UpperCamelCase       :				Any=3 ,			_UpperCamelCase       :				int=1_6 ,			_UpperCamelCase       :				int = 1_0 ,			_UpperCamelCase       :				int = 2					)					->				Union[str, Any]:





						"""simple docstring"""






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

						snake_case								=			get_dataset(_UpperCamelCase					)
						snake_case								=			get_dataset(_UpperCamelCase					)
						snake_case								=			DataLoader(_UpperCamelCase ,			shuffle=_UpperCamelCase ,			batch_size=_UpperCamelCase ,			num_workers=4					)
						snake_case								=			DataLoader(_UpperCamelCase ,			shuffle=_UpperCamelCase ,			batch_size=_UpperCamelCase ,			num_workers=4					)
						return (train_dataloader, valid_dataloader)





def    lowerCAmelCase__    (			_UpperCamelCase       :				str ,			_UpperCamelCase       :				Dict ,			_UpperCamelCase       :				Optional[int] ,			_UpperCamelCase       :				Optional[int] ,			_UpperCamelCase       :				str ,			_UpperCamelCase       :				Tuple=None					)					->				Optional[int]:





						"""simple docstring"""






						snake_case								=			[]
						for epoch in range(_UpperCamelCase					):
												# Train quickly
												model.train()
												for batch in dataloader:
																		snake_case					,snake_case								=			batch
																		snake_case								=			model(_UpperCamelCase					)
																		snake_case								=			torch.nn.functional.mse_loss(_UpperCamelCase ,			_UpperCamelCase					)
																		accelerator.backward(_UpperCamelCase					)
																		optimizer.step()
																		optimizer.zero_grad()
												rands.append(random.random()					)  # Introduce some randomness
												if scheduler is not None:
																		scheduler.step()
						return rands



class   lowerCAmelCase_    (			nn.Module					):



				"""simple docstring"""

				def __init__(				self    ):






										"""simple docstring"""

										super().__init__()
										snake_case								=			nn.Parameter(torch.randn(1    )    )
										snake_case								=			nn.Parameter(torch.randn(1    )    )

				def 		snake_case (				self		,    lowerCAmelCase    ):






										"""simple docstring"""

										return x * self.a + self.b





class   lowerCAmelCase_    (			unittest.TestCase					):



				"""simple docstring"""

				def 		snake_case (				self    ):






										"""simple docstring"""

										with tempfile.TemporaryDirectory() as tmpdir:
																set_seed(42    )
																snake_case								=			DummyModel()
																snake_case								=			torch.optim.Adam(params=model.parameters()		,    lr=1E-3    )
																snake_case					,snake_case								=			dummy_dataloaders()
																snake_case								=			ProjectConfiguration(total_limit=1		,    project_dir=lowerCAmelCase		,    automatic_checkpoint_naming=lowerCAmelCase    )
																# Train baseline
																snake_case								=			Accelerator(project_config=lowerCAmelCase    )
																snake_case					,snake_case					,snake_case					,snake_case								=			accelerator.prepare(
																    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																# Save initial
																accelerator.save_state()

																# Save second state
																accelerator.save_state()
																self.assertEqual(len(os.listdir(accelerator.project_dir    )    )		,    1    )

				def 		snake_case (				self    ):






										"""simple docstring"""

										with tempfile.TemporaryDirectory() as tmpdir:
																set_seed(42    )
																snake_case								=			DummyModel()
																snake_case								=			torch.optim.Adam(params=model.parameters()		,    lr=1E-3    )
																snake_case					,snake_case								=			dummy_dataloaders()
																# Train baseline
																snake_case								=			Accelerator()
																snake_case					,snake_case					,snake_case					,snake_case								=			accelerator.prepare(
																    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																# Save initial
																snake_case								=			os.path.join(lowerCAmelCase		,    'initial'    )
																accelerator.save_state(lowerCAmelCase    )
																((snake_case)					,(snake_case))								=			model.a.item(), model.b.item()
																snake_case								=			optimizer.state_dict()
																snake_case								=			train(3		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																((snake_case)					,(snake_case))								=			model.a.item(), model.b.item()
																snake_case								=			optimizer.state_dict()

																# Train partially
																set_seed(42    )
																snake_case								=			DummyModel()
																snake_case								=			torch.optim.Adam(params=model.parameters()		,    lr=1E-3    )
																snake_case					,snake_case								=			dummy_dataloaders()
																snake_case								=			Accelerator()
																snake_case					,snake_case					,snake_case					,snake_case								=			accelerator.prepare(
																    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																accelerator.load_state(lowerCAmelCase    )
																((snake_case)					,(snake_case))								=			model.a.item(), model.b.item()
																snake_case								=			optimizer.state_dict()
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )

																snake_case								=			train(2		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																# Save everything
																snake_case								=			os.path.join(lowerCAmelCase		,    'checkpoint'    )
																accelerator.save_state(lowerCAmelCase    )

																# Load everything back in and make sure all states work
																accelerator.load_state(lowerCAmelCase    )
																test_rands += train(1		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																((snake_case)					,(snake_case))								=			model.a.item(), model.b.item()
																snake_case								=			optimizer.state_dict()
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )

				def 		snake_case (				self    ):






										"""simple docstring"""

										with tempfile.TemporaryDirectory() as tmpdir:
																set_seed(42    )
																snake_case								=			DummyModel()
																snake_case								=			torch.optim.Adam(params=model.parameters()		,    lr=1E-3    )
																snake_case					,snake_case								=			dummy_dataloaders()
																snake_case								=			ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase    )

																# Train baseline
																snake_case								=			Accelerator(project_dir=lowerCAmelCase		,    project_config=lowerCAmelCase    )
																snake_case					,snake_case					,snake_case					,snake_case								=			accelerator.prepare(
																    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																# Save initial
																accelerator.save_state()
																((snake_case)					,(snake_case))								=			model.a.item(), model.b.item()
																snake_case								=			optimizer.state_dict()
																snake_case								=			train(3		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																((snake_case)					,(snake_case))								=			model.a.item(), model.b.item()
																snake_case								=			optimizer.state_dict()

																# Train partially
																set_seed(42    )
																snake_case								=			DummyModel()
																snake_case								=			torch.optim.Adam(params=model.parameters()		,    lr=1E-3    )
																snake_case					,snake_case								=			dummy_dataloaders()
																snake_case								=			ProjectConfiguration(iteration=1		,    automatic_checkpoint_naming=lowerCAmelCase    )
																snake_case								=			Accelerator(project_dir=lowerCAmelCase		,    project_config=lowerCAmelCase    )
																snake_case					,snake_case					,snake_case					,snake_case								=			accelerator.prepare(
																    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																accelerator.load_state(os.path.join(lowerCAmelCase		,    'checkpoints'		,    'checkpoint_0'    )    )
																((snake_case)					,(snake_case))								=			model.a.item(), model.b.item()
																snake_case								=			optimizer.state_dict()
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )

																snake_case								=			train(2		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																# Save everything
																accelerator.save_state()

																# Load everything back in and make sure all states work
																accelerator.load_state(os.path.join(lowerCAmelCase		,    'checkpoints'		,    'checkpoint_1'    )    )
																test_rands += train(1		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																((snake_case)					,(snake_case))								=			model.a.item(), model.b.item()
																snake_case								=			optimizer.state_dict()
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )
																self.assertEqual(lowerCAmelCase		,    lowerCAmelCase    )

				def 		snake_case (				self    ):






										"""simple docstring"""

										snake_case								=			torch.tensor([1, 2, 3]    )
										snake_case								=			torch.tensor([2, 3, 4]    )
										snake_case								=			DummyModel()
										snake_case								=			torch.optim.Adam(net.parameters()    )
										snake_case								=			Accelerator()
										with self.assertRaises(lowerCAmelCase    ) as ve:
																accelerator.register_for_checkpointing(lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
										snake_case								=			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 		snake_case (				self    ):






										"""simple docstring"""

										with tempfile.TemporaryDirectory() as tmpdir:
																set_seed(42    )
																snake_case								=			DummyModel()
																snake_case								=			torch.optim.Adam(params=model.parameters()		,    lr=1E-3    )
																snake_case								=			torch.optim.lr_scheduler.StepLR(lowerCAmelCase		,    step_size=1		,    gamma=0.99    )
																snake_case					,snake_case								=			dummy_dataloaders()
																snake_case								=			ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase    )
																# Train baseline
																snake_case								=			Accelerator(project_dir=lowerCAmelCase		,    project_config=lowerCAmelCase    )
																snake_case					,snake_case					,snake_case					,snake_case					,snake_case								=			accelerator.prepare(
																    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																# Save initial
																accelerator.save_state()
																snake_case								=			scheduler.state_dict()
																train(3		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase		,    lowerCAmelCase    )
																self.assertNotEqual(lowerCAmelCase		,    scheduler.state_dict()    )

																# Load everything back in and make sure all states work
																accelerator.load_state(os.path.join(lowerCAmelCase		,    'checkpoints'		,    'checkpoint_0'    )    )
																self.assertEqual(lowerCAmelCase		,    scheduler.state_dict()    )

				def 		snake_case (				self    ):






										"""simple docstring"""

										with tempfile.TemporaryDirectory() as tmpdir:
																set_seed(42    )
																snake_case								=			DummyModel()
																snake_case								=			ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase		,    total_limit=2    )
																# Train baseline
																snake_case								=			Accelerator(project_dir=lowerCAmelCase		,    project_config=lowerCAmelCase    )
																snake_case								=			accelerator.prepare(lowerCAmelCase    )
																# Save 3 states:
																for _ in range(11    ):
																						accelerator.save_state()
																self.assertTrue(not os.path.exists(os.path.join(lowerCAmelCase		,    'checkpoints'		,    'checkpoint_0'    )    )    )
																self.assertTrue(os.path.exists(os.path.join(lowerCAmelCase		,    'checkpoints'		,    'checkpoint_9'    )    )    )
																self.assertTrue(os.path.exists(os.path.join(lowerCAmelCase		,    'checkpoints'		,    'checkpoint_10'    )    )    )

				@require_cuda
				def 		snake_case (				self    ):






										"""simple docstring"""

										snake_case								=			['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__    )]
										execute_subprocess_async(lowerCAmelCase		,    env=os.environ.copy()    )


if __name__ == "__main__":
					SCREAMING_SNAKE_CASE__      						=  "/tmp/accelerate/state_checkpointing"
					SCREAMING_SNAKE_CASE__      						=  DummyModel()
					SCREAMING_SNAKE_CASE__      						=  torch.optim.Adam(params=model.parameters(), lr=1E-3)
					SCREAMING_SNAKE_CASE__      						=  torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
					SCREAMING_SNAKE_CASE__						,       SCREAMING_SNAKE_CASE__      						=  dummy_dataloaders()
					SCREAMING_SNAKE_CASE__      						=  ProjectConfiguration(automatic_checkpoint_naming=True)
					# Train baseline
					SCREAMING_SNAKE_CASE__      						=  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)
					SCREAMING_SNAKE_CASE__						,       SCREAMING_SNAKE_CASE__						,       SCREAMING_SNAKE_CASE__						,       SCREAMING_SNAKE_CASE__						,       SCREAMING_SNAKE_CASE__      						=  accelerator.prepare(
					    model, optimizer, train_dataloader, valid_dataloader, scheduler
					)
					SCREAMING_SNAKE_CASE__						,       SCREAMING_SNAKE_CASE__      						=  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:
										SCREAMING_SNAKE_CASE__      						=  group["params"][0].device
										break
					assert param_device.type == accelerator.device.type
					SCREAMING_SNAKE_CASE__      						=  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:
										SCREAMING_SNAKE_CASE__      						=  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:
										SCREAMING_SNAKE_CASE__      						=  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    lowerCAmelCase__    (			_UpperCamelCase       :				int ,			_UpperCamelCase       :				int					)					->				int:





						"""simple docstring"""






						return int((input_a, input_a).count(0					) == 0					)





def    lowerCAmelCase__    (			)					->				None:





						"""simple docstring"""






						assert and_gate(0 ,			0					) == 0
						assert and_gate(0 ,			1					) == 0
						assert and_gate(1 ,			0					) == 0
						assert and_gate(1 ,			1					) == 1


if __name__ == "__main__":
					test_and_gate()
					print(and_gate(1, 0))
					print(and_gate(0, 0))
					print(and_gate(0, 1))
					print(and_gate(1, 1))


