






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


_lowerCAmelCase         =							logging.getLogger(__name__)






def 			__UpperCamelCase	(		snake_case__=2   ,   snake_case__=3   ,   snake_case__=16   ,   snake_case__ = 10   ,   snake_case__ = 2  ):

	def get_dataset(snake_case__  ):
		A_		:						Any	    =   torch.randn(batch_size * n_batches   ,   1  )
		return TensorDataset(snake_case__   ,   a * x + b + 0.1 * torch.randn(batch_size * n_batches   ,   1  )  )

	A_		:						Dict	    =   get_dataset(snake_case__  )
	A_		:						str	    =   get_dataset(snake_case__  )
	A_		:						Optional[int]	    =   DataLoader(snake_case__   ,   shuffle=snake_case__   ,   batch_size=snake_case__   ,   num_workers=4  )
	A_		:						Union[str, Any]	    =   DataLoader(snake_case__   ,   shuffle=snake_case__   ,   batch_size=snake_case__   ,   num_workers=4  )
	return (train_dataloader, valid_dataloader)






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



class      SCREAMING_SNAKE_CASE  (				nn.Module						):





	"""simple docstring"""




	def __init__(self							):
		super().__init__()
		A_		:						Optional[Any]	    =   nn.Parameter(torch.randn(1							)							)
		A_		:						Optional[int]	    =   nn.Parameter(torch.randn(1							)							)





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






class      SCREAMING_SNAKE_CASE  (				unittest.TestCase						):





	"""simple docstring"""




	def    lowerCamelCase(self							):
		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42							)
			A_		:						Tuple	    =   DummyModel()
			A_		:						Tuple	    =   torch.optim.Adam(params=model.parameters()     ,     lr=1e-3							)
			A_		:						Any	    =   dummy_dataloaders()
			A_		:						Tuple	    =   ProjectConfiguration(total_limit=1     ,     project_dir=lowerCAmelCase_     ,     automatic_checkpoint_naming=lowerCAmelCase_							)
			# Train baseline
			A_		:						List[Any]	    =   Accelerator(project_config=lowerCAmelCase_							)
			A_		:						Union[str, Any]	    =   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    lowerCamelCase(self							):
		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42							)
			A_		:						str	    =   DummyModel()
			A_		:						List[Any]	    =   torch.optim.Adam(params=model.parameters()     ,     lr=1e-3							)
			A_		:						Any	    =   dummy_dataloaders()
			# Train baseline
			A_		:						Dict	    =   Accelerator()
			A_		:						Dict	    =   accelerator.prepare(
			    lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							)
			# Save initial
			A_		:						Optional[int]	    =   os.path.join(lowerCAmelCase_     ,     """initial"""							)
			accelerator.save_state(lowerCAmelCase_							)
			(A_)		:						int	    =   model.a.item(), model.b.item()
			A_		:						Optional[int]	    =   optimizer.state_dict()
			A_		:						Union[str, Any]	    =   train(3     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							)
			(A_)		:						Dict	    =   model.a.item(), model.b.item()
			A_		:						Optional[Any]	    =   optimizer.state_dict()

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

			A_		:						str	    =   train(2     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							)
			# Save everything
			A_		:						Optional[int]	    =   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_							)
			(A_)		:						List[Any]	    =   model.a.item(), model.b.item()
			A_		:						Optional[Any]	    =   optimizer.state_dict()
			self.assertEqual(lowerCAmelCase_     ,     lowerCAmelCase_							)
			self.assertEqual(lowerCAmelCase_     ,     lowerCAmelCase_							)
			self.assertEqual(lowerCAmelCase_     ,     lowerCAmelCase_							)
			self.assertEqual(lowerCAmelCase_     ,     lowerCAmelCase_							)





	def    lowerCamelCase(self							):
		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42							)
			A_		:						Optional[int]	    =   DummyModel()
			A_		:						Optional[Any]	    =   torch.optim.Adam(params=model.parameters()     ,     lr=1e-3							)
			A_		:						Optional[Any]	    =   dummy_dataloaders()
			A_		:						Any	    =   ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase_							)

			# Train baseline
			A_		:						Optional[Any]	    =   Accelerator(project_dir=lowerCAmelCase_     ,     project_config=lowerCAmelCase_							)
			A_		:						Any	    =   accelerator.prepare(
			    lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							)
			# Save initial
			accelerator.save_state()
			(A_)		:						Any	    =   model.a.item(), model.b.item()
			A_		:						Dict	    =   optimizer.state_dict()
			A_		:						Optional[Any]	    =   train(3     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							)
			(A_)		:						List[Any]	    =   model.a.item(), model.b.item()
			A_		:						Optional[int]	    =   optimizer.state_dict()

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

			A_		:						str	    =   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_							)
			(A_)		:						Dict	    =   model.a.item(), model.b.item()
			A_		:						List[str]	    =   optimizer.state_dict()
			self.assertEqual(lowerCAmelCase_     ,     lowerCAmelCase_							)
			self.assertEqual(lowerCAmelCase_     ,     lowerCAmelCase_							)
			self.assertEqual(lowerCAmelCase_     ,     lowerCAmelCase_							)
			self.assertEqual(lowerCAmelCase_     ,     lowerCAmelCase_							)





	def    lowerCamelCase(self							):
		A_		:						str	    =   torch.tensor([1, 2, 3]							)
		A_		:						Tuple	    =   torch.tensor([2, 3, 4]							)
		A_		:						Dict	    =   DummyModel()
		A_		:						str	    =   torch.optim.Adam(net.parameters()							)
		A_		:						Tuple	    =   Accelerator()
		with self.assertRaises(lowerCAmelCase_							) as ve:
			accelerator.register_for_checkpointing(lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							)
		A_		:						List[Any]	    =   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    lowerCamelCase(self							):
		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42							)
			A_		:						Dict	    =   DummyModel()
			A_		:						str	    =   torch.optim.Adam(params=model.parameters()     ,     lr=1e-3							)
			A_		:						Optional[Any]	    =   torch.optim.lr_scheduler.StepLR(lowerCAmelCase_     ,     step_size=1     ,     gamma=0.99							)
			A_		:						Any	    =   dummy_dataloaders()
			A_		:						Dict	    =   ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase_							)
			# Train baseline
			A_		:						Dict	    =   Accelerator(project_dir=lowerCAmelCase_     ,     project_config=lowerCAmelCase_							)
			A_		:						Dict	    =   accelerator.prepare(
			    lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							)
			# Save initial
			accelerator.save_state()
			A_		:						int	    =   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    lowerCamelCase(self							):
		with tempfile.TemporaryDirectory() as tmpdir:
			set_seed(42							)
			A_		:						Tuple	    =   DummyModel()
			A_		:						Dict	    =   ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase_     ,     total_limit=2							)
			# Train baseline
			A_		:						Optional[Any]	    =   Accelerator(project_dir=lowerCAmelCase_     ,     project_config=lowerCAmelCase_							)
			A_		:						Optional[int]	    =   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    lowerCamelCase(self							):
		A_		:						Tuple	    =   ["""torchrun""", f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__							)]
		execute_subprocess_async(lowerCAmelCase_     ,     env=os.environ.copy()							)


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

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


_lowerCAmelCase         =							logging.get_logger(__name__)

_lowerCAmelCase         =							{
    "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json",
}



class      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	_A       :				List[str]    =				"""deta"""
	_A       :				Tuple    =				{
	    """hidden_size""": """d_model""",
	    """num_attention_heads""": """encoder_attention_heads""",
	}





	def __init__(self     ,     lowerCAmelCase_=None     ,     lowerCAmelCase_=900     ,     lowerCAmelCase_=2048     ,     lowerCAmelCase_=6     ,     lowerCAmelCase_=2048     ,     lowerCAmelCase_=8     ,     lowerCAmelCase_=6     ,     lowerCAmelCase_=1024     ,     lowerCAmelCase_=8     ,     lowerCAmelCase_=0.0     ,     lowerCAmelCase_=True     ,     lowerCAmelCase_="relu"     ,     lowerCAmelCase_=256     ,     lowerCAmelCase_=0.1     ,     lowerCAmelCase_=0.0     ,     lowerCAmelCase_=0.0     ,     lowerCAmelCase_=0.02     ,     lowerCAmelCase_=1.0     ,     lowerCAmelCase_=True     ,     lowerCAmelCase_=False     ,     lowerCAmelCase_="sine"     ,     lowerCAmelCase_=5     ,     lowerCAmelCase_=4     ,     lowerCAmelCase_=4     ,     lowerCAmelCase_=True     ,     lowerCAmelCase_=300     ,     lowerCAmelCase_=True     ,     lowerCAmelCase_=True     ,     lowerCAmelCase_=1     ,     lowerCAmelCase_=5     ,     lowerCAmelCase_=2     ,     lowerCAmelCase_=1     ,     lowerCAmelCase_=1     ,     lowerCAmelCase_=5     ,     lowerCAmelCase_=2     ,     lowerCAmelCase_=0.1     ,     lowerCAmelCase_=0.25     ,     **lowerCAmelCase_     ,     ):
		if backbone_config is None:
			logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""							)
			A_		:						Any	    =   CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""]							)
		else:
			if isinstance(lowerCAmelCase_     ,     lowerCAmelCase_							):
				A_		:						List[str]	    =   backbone_config.pop("""model_type"""							)
				A_		:						List[str]	    =   CONFIG_MAPPING[backbone_model_type]
				A_		:						Tuple	    =   config_class.from_dict(lowerCAmelCase_							)

		A_		:						List[Any]	    =   backbone_config
		A_		:						List[str]	    =   num_queries
		A_		:						List[Any]	    =   max_position_embeddings
		A_		:						int	    =   d_model
		A_		:						Optional[Any]	    =   encoder_ffn_dim
		A_		:						Optional[Any]	    =   encoder_layers
		A_		:						List[Any]	    =   encoder_attention_heads
		A_		:						int	    =   decoder_ffn_dim
		A_		:						Dict	    =   decoder_layers
		A_		:						Dict	    =   decoder_attention_heads
		A_		:						Optional[Any]	    =   dropout
		A_		:						str	    =   attention_dropout
		A_		:						Any	    =   activation_dropout
		A_		:						Union[str, Any]	    =   activation_function
		A_		:						int	    =   init_std
		A_		:						List[Any]	    =   init_xavier_std
		A_		:						List[Any]	    =   encoder_layerdrop
		A_		:						Any	    =   auxiliary_loss
		A_		:						Tuple	    =   position_embedding_type
		# deformable attributes
		A_		:						List[str]	    =   num_feature_levels
		A_		:						Tuple	    =   encoder_n_points
		A_		:						str	    =   decoder_n_points
		A_		:						List[Any]	    =   two_stage
		A_		:						Optional[Any]	    =   two_stage_num_proposals
		A_		:						Union[str, Any]	    =   with_box_refine
		A_		:						Optional[int]	    =   assign_first_stage
		if two_stage is True and with_box_refine is False:
			raise ValueError("""If two_stage is True, with_box_refine must be True."""							)
		# Hungarian matcher
		A_		:						List[Any]	    =   class_cost
		A_		:						str	    =   bbox_cost
		A_		:						Tuple	    =   giou_cost
		# Loss coefficients
		A_		:						int	    =   mask_loss_coefficient
		A_		:						Union[str, Any]	    =   dice_loss_coefficient
		A_		:						Union[str, Any]	    =   bbox_loss_coefficient
		A_		:						Optional[Any]	    =   giou_loss_coefficient
		A_		:						List[str]	    =   eos_coefficient
		A_		:						Optional[Any]	    =   focal_alpha
		super().__init__(is_encoder_decoder=lowerCAmelCase_     ,     **lowerCAmelCase_							)





	@property
	def    lowerCamelCase(self							):
		return self.encoder_attention_heads





	@property
	def    lowerCamelCase(self							):
		return self.d_model





	def    lowerCamelCase(self							):
		A_		:						str	    =   copy.deepcopy(self.__dict__							)
		A_		:						int	    =   self.backbone_config.to_dict()
		A_		:						Dict	    =   self.__class__.model_type
		return output

