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


lowercase__		:Union[str, Any]			  =   logging.getLogger(__name__)



def 	UpperCamelCase   (							lowerCAmelCase__=2			,      lowerCAmelCase__=3			,      lowerCAmelCase__=16			,      lowerCAmelCase__ = 10			,      lowerCAmelCase__ = 2		):
					'''simple docstring'''



					def get_dataset(lowerCAmelCase__		):
										lowercase						     =						torch.randn(batch_size * n_batches			,      1		)
										return TensorDataset(A__			,      a * x + b + 0.1 * torch.randn(batch_size * n_batches			,      1		)		)

					lowercase						     =						get_dataset(A__		)
					lowercase						     =						get_dataset(A__		)
					lowercase						     =						DataLoader(A__			,      shuffle=A__			,      batch_size=A__			,      num_workers=4		)
					lowercase						     =						DataLoader(A__			,      shuffle=A__			,      batch_size=A__			,      num_workers=4		)
					return (train_dataloader, valid_dataloader)



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







class     lowercase		( nn.Module		):




							def __init__(    self):
												super().__init__()
												lowercase						     =						nn.Parameter(torch.randn(1))
												lowercase						     =						nn.Parameter(torch.randn(1))





							def 			A__				(    self       ,A__):
												return x * self.a + self.b







class     lowercase		( unittest.TestCase		):




							def 			A__				(    self):
												with tempfile.TemporaryDirectory() as tmpdir:
																	set_seed(4_2)
																	lowercase						     =						DummyModel()
																	lowercase						     =						torch.optim.Adam(params=model.parameters()       ,lr=1E-3)
																	lowercase     ,						lowercase						     =						dummy_dataloaders()
																	lowercase						     =						ProjectConfiguration(total_limit=1       ,project_dir=UpperCamelCase_       ,automatic_checkpoint_naming=UpperCamelCase_)
																	# Train baseline
																	lowercase						     =						Accelerator(project_config=UpperCamelCase_)
																	lowercase     ,						lowercase     ,						lowercase     ,						lowercase						     =						accelerator.prepare(
																	    UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_)
																	# Save initial
																	accelerator.save_state()

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




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

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

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

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




							def 			A__				(    self):
												with tempfile.TemporaryDirectory() as tmpdir:
																	set_seed(4_2)
																	lowercase						     =						DummyModel()
																	lowercase						     =						torch.optim.Adam(params=model.parameters()       ,lr=1E-3)
																	lowercase     ,						lowercase						     =						dummy_dataloaders()
																	lowercase						     =						ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_)

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

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

																	lowercase						     =						train(2       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_)
																	# Save everything
																	accelerator.save_state()

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




							def 			A__				(    self):
												lowercase						     =						torch.tensor([1, 2, 3])
												lowercase						     =						torch.tensor([2, 3, 4])
												lowercase						     =						DummyModel()
												lowercase						     =						torch.optim.Adam(net.parameters())
												lowercase						     =						Accelerator()
												with self.assertRaises(UpperCamelCase_) as ve:
																	accelerator.register_for_checkpointing(UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_)
												lowercase						     =						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 			A__				(    self):
												with tempfile.TemporaryDirectory() as tmpdir:
																	set_seed(4_2)
																	lowercase						     =						DummyModel()
																	lowercase						     =						torch.optim.Adam(params=model.parameters()       ,lr=1E-3)
																	lowercase						     =						torch.optim.lr_scheduler.StepLR(UpperCamelCase_       ,step_size=1       ,gamma=0.99)
																	lowercase     ,						lowercase						     =						dummy_dataloaders()
																	lowercase						     =						ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_)
																	# Train baseline
																	lowercase						     =						Accelerator(project_dir=UpperCamelCase_       ,project_config=UpperCamelCase_)
																	lowercase     ,						lowercase     ,						lowercase     ,						lowercase     ,						lowercase						     =						accelerator.prepare(
																	    UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_)
																	# Save initial
																	accelerator.save_state()
																	lowercase						     =						scheduler.state_dict()
																	train(3       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_       ,UpperCamelCase_)
																	self.assertNotEqual(UpperCamelCase_       ,scheduler.state_dict())

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




							def 			A__				(    self):
												with tempfile.TemporaryDirectory() as tmpdir:
																	set_seed(4_2)
																	lowercase						     =						DummyModel()
																	lowercase						     =						ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_       ,total_limit=2)
																	# Train baseline
																	lowercase						     =						Accelerator(project_dir=UpperCamelCase_       ,project_config=UpperCamelCase_)
																	lowercase						     =						accelerator.prepare(UpperCamelCase_)
																	# Save 3 states:
																	for _ in range(1_1):
																						accelerator.save_state()
																	self.assertTrue(not os.path.exists(os.path.join(UpperCamelCase_       ,'''checkpoints'''       ,'''checkpoint_0''')))
																	self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_       ,'''checkpoints'''       ,'''checkpoint_9''')))
																	self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_       ,'''checkpoints'''       ,'''checkpoint_10''')))





							@require_cuda
							def 			A__				(    self):
												lowercase						     =						['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__)]
												execute_subprocess_async(UpperCamelCase_       ,env=os.environ.copy())


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






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


lowercase__		:str			  =   {"configuration_vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig", "ViTOnnxConfig"]}

try:
							if not is_vision_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowercase__		:str			  =   ["ViTFeatureExtractor"]
							lowercase__		:int			  =   ["ViTImageProcessor"]

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowercase__		:int			  =   [
							    "VIT_PRETRAINED_MODEL_ARCHIVE_LIST",
							    "ViTForImageClassification",
							    "ViTForMaskedImageModeling",
							    "ViTModel",
							    "ViTPreTrainedModel",
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowercase__		:Any			  =   [
							    "TFViTForImageClassification",
							    "TFViTModel",
							    "TFViTPreTrainedModel",
							]

try:
							if not is_flax_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowercase__		:Optional[int]			  =   [
							    "FlaxViTForImageClassification",
							    "FlaxViTModel",
							    "FlaxViTPreTrainedModel",
							]

if TYPE_CHECKING:
							from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig

							try:
														if not is_vision_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .feature_extraction_vit import ViTFeatureExtractor
														from .image_processing_vit import ViTImageProcessor

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_vit import (
														    VIT_PRETRAINED_MODEL_ARCHIVE_LIST,
														    ViTForImageClassification,
														    ViTForMaskedImageModeling,
														    ViTModel,
														    ViTPreTrainedModel,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel

							try:
														if not is_flax_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel


else:
							import sys

							lowercase__		:Dict			  =   _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




