


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


__snake_case				 =	logging.getLogger(__name__)


def      a (     __a=2					,   __a=3					,   __a=16					,   __a = 10					,   __a = 2  )    ->      str:



					'''simple docstring'''






					def get_dataset(__a  ):
										UpperCamelCase__  :Union[str, Any]				   =					torch.randn(batch_size * n_batches					,   1  )
										return TensorDataset(lowercase_					,   a * x + b + 0.1 * torch.randn(batch_size * n_batches					,   1  )  )

					UpperCamelCase__  :int				   =					get_dataset(lowercase_  )
					UpperCamelCase__  :Any				   =					get_dataset(lowercase_  )
					UpperCamelCase__  :Dict				   =					DataLoader(lowercase_					,   shuffle=lowercase_					,   batch_size=lowercase_					,   num_workers=4  )
					UpperCamelCase__  :List[Any]				   =					DataLoader(lowercase_					,   shuffle=lowercase_					,   batch_size=lowercase_					,   num_workers=4  )
					return (train_dataloader, valid_dataloader)


def      a (     __a					,   __a					,   __a					,   __a					,   __a					,   __a=None  )    ->      Dict:



					'''simple docstring'''






					UpperCamelCase__  :List[str]				   =					[]
					for epoch in range(lowercase_  ):
										# Train quickly
										model.train()
										for batch in dataloader:
															UpperCamelCase__  :Optional[int]				   =					batch
															UpperCamelCase__  :int				   =					model(lowercase_  )
															UpperCamelCase__  :int				   =					torch.nn.functional.mse_loss(lowercase_					,   lowercase_  )
															accelerator.backward(lowercase_  )
															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   ):

		"""simple docstring"""

		def __init__(						self				):

							'''simple docstring'''


							super().__init__()
							UpperCamelCase__  :Any				   =					nn.Parameter(torch.randn(1				)				)
							UpperCamelCase__  :Tuple				   =					nn.Parameter(torch.randn(1				)				)




		def        lowerCAmelCase__							(						self       ,  UpperCamelCase_				):

							'''simple docstring'''


							return x * self.a + self.b



class   lowercase      (				unittest.TestCase   ):

		"""simple docstring"""

		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							with tempfile.TemporaryDirectory() as tmpdir:
												set_seed(42				)
												UpperCamelCase__  :Dict				   =					DummyModel()
												UpperCamelCase__  :List[Any]				   =					torch.optim.Adam(params=model.parameters()       ,  lr=1e-3				)
												UpperCamelCase__  :List[str]				   =					dummy_dataloaders()
												UpperCamelCase__  :Dict				   =					ProjectConfiguration(total_limit=1       ,  project_dir=A__       ,  automatic_checkpoint_naming=A__				)
												# Train baseline
												UpperCamelCase__  :Union[str, Any]				   =					Accelerator(project_config=A__				)
												UpperCamelCase__  :List[str]				   =					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        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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

												# Train partially
												set_seed(42				)
												UpperCamelCase__  :Optional[int]				   =					DummyModel()
												UpperCamelCase__  :Optional[int]				   =					torch.optim.Adam(params=model.parameters()       ,  lr=1e-3				)
												UpperCamelCase__  :Optional[int]				   =					dummy_dataloaders()
												UpperCamelCase__  :Optional[int]				   =					Accelerator()
												UpperCamelCase__  :Optional[int]				   =					accelerator.prepare(
												    A__       ,  A__       ,  A__       ,  A__				)
												accelerator.load_state(A__				)
												(UpperCamelCase__)  :int				   =					model.a.item(), model.b.item()
												UpperCamelCase__  :Dict				   =					optimizer.state_dict()
												self.assertEqual(A__       ,  A__				)
												self.assertEqual(A__       ,  A__				)
												self.assertEqual(A__       ,  A__				)

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




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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

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

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

												UpperCamelCase__  :Tuple				   =					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__				)
												(UpperCamelCase__)  :Optional[int]				   =					model.a.item(), model.b.item()
												UpperCamelCase__  :int				   =					optimizer.state_dict()
												self.assertEqual(A__       ,  A__				)
												self.assertEqual(A__       ,  A__				)
												self.assertEqual(A__       ,  A__				)
												self.assertEqual(A__       ,  A__				)




		def        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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

							'''simple docstring'''


							with tempfile.TemporaryDirectory() as tmpdir:
												set_seed(42				)
												UpperCamelCase__  :int				   =					DummyModel()
												UpperCamelCase__  :List[str]				   =					torch.optim.Adam(params=model.parameters()       ,  lr=1e-3				)
												UpperCamelCase__  :List[str]				   =					torch.optim.lr_scheduler.StepLR(A__       ,  step_size=1       ,  gamma=0.99				)
												UpperCamelCase__  :Tuple				   =					dummy_dataloaders()
												UpperCamelCase__  :List[Any]				   =					ProjectConfiguration(automatic_checkpoint_naming=A__				)
												# Train baseline
												UpperCamelCase__  :str				   =					Accelerator(project_dir=A__       ,  project_config=A__				)
												UpperCamelCase__  :Any				   =					accelerator.prepare(
												    A__       ,  A__       ,  A__       ,  A__       ,  A__				)
												# Save initial
												accelerator.save_state()
												UpperCamelCase__  :Optional[int]				   =					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        lowerCAmelCase__							(						self				):

							'''simple docstring'''


							with tempfile.TemporaryDirectory() as tmpdir:
												set_seed(42				)
												UpperCamelCase__  :int				   =					DummyModel()
												UpperCamelCase__  :str				   =					ProjectConfiguration(automatic_checkpoint_naming=A__       ,  total_limit=2				)
												# Train baseline
												UpperCamelCase__  :Dict				   =					Accelerator(project_dir=A__       ,  project_config=A__				)
												UpperCamelCase__  :str				   =					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        lowerCAmelCase__							(						self				):

							'''simple docstring'''


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


import tensorflow as tf

from ...tf_utils import shape_list



class        _a		(tf.keras.layers.Layer							):


					'''simple docstring'''






					def __init__(					self       ,			A__       ,			A__       ,			A__       ,			A__       ,			A__=1       ,			A__=False       ,			**A__     ):
						super().__init__(**A__     )

						A__				:       Tuple	  =						vocab_size
						A__				:       List[str]	  =						d_embed
						A__				:       int	  =						d_proj

						A__				:       Tuple	  =						cutoffs + [vocab_size]
						A__				:       Any	  =						[0] + self.cutoffs
						A__				:       str	  =						div_val

						A__				:       int	  =						self.cutoffs[0]
						A__				:       List[str]	  =						len(self.cutoffs     ) - 1
						A__				:       Optional[int]	  =						self.shortlist_size + self.n_clusters
						A__				:       List[Any]	  =						keep_order

						A__				:       Optional[int]	  =						[]
						A__				:       Optional[Any]	  =						[]






					def     __A     (					self       ,			A__     ):
						if self.n_clusters > 0:
							A__				:       List[str]	  =						self.add_weight(
							    shape=(self.n_clusters, self.d_embed)       ,			initializer="""zeros"""       ,			trainable=A__       ,			name="""cluster_weight"""     )
							A__				:       Union[str, Any]	  =						self.add_weight(
							    shape=(self.n_clusters,)       ,			initializer="""zeros"""       ,			trainable=A__       ,			name="""cluster_bias"""     )

						if self.div_val == 1:
							for i in range(len(self.cutoffs     )     ):
								if self.d_proj != self.d_embed:
									A__				:       List[str]	  =						self.add_weight(
									    shape=(self.d_embed, self.d_proj)       ,			initializer="""zeros"""       ,			trainable=A__       ,			name=F"""out_projs_._{i}"""       ,			)
									self.out_projs.append(A__     )
								else:
									self.out_projs.append(A__     )
								A__				:       int	  =						self.add_weight(
								    shape=(self.vocab_size, self.d_embed)       ,			initializer="""zeros"""       ,			trainable=A__       ,			name=F"""out_layers_._{i}_._weight"""       ,			)
								A__				:       str	  =						self.add_weight(
								    shape=(self.vocab_size,)       ,			initializer="""zeros"""       ,			trainable=A__       ,			name=F"""out_layers_._{i}_._bias"""       ,			)
								self.out_layers.append((weight, bias)     )
						else:
							for i in range(len(self.cutoffs     )     ):
								A__  ,  A__				:       Optional[int]	  =						self.cutoff_ends[i], self.cutoff_ends[i + 1]
								A__				:       Optional[int]	  =						self.d_embed // (self.div_val**i)

								A__				:       Optional[Any]	  =						self.add_weight(
								    shape=(d_emb_i, self.d_proj)       ,			initializer="""zeros"""       ,			trainable=A__       ,			name=F"""out_projs_._{i}"""     )
								self.out_projs.append(A__     )
								A__				:       List[str]	  =						self.add_weight(
								    shape=(r_idx - l_idx, d_emb_i)       ,			initializer="""zeros"""       ,			trainable=A__       ,			name=F"""out_layers_._{i}_._weight"""       ,			)
								A__				:       Optional[int]	  =						self.add_weight(
								    shape=(r_idx - l_idx,)       ,			initializer="""zeros"""       ,			trainable=A__       ,			name=F"""out_layers_._{i}_._bias"""       ,			)
								self.out_layers.append((weight, bias)     )
						super().build(A__     )






					@staticmethod
					def     __A     (					A__       ,			A__       ,			A__       ,			A__=None     ):
						A__				:       Tuple	  =						x
						if proj is not None:
							A__				:       Tuple	  =						tf.einsum("""ibd,ed->ibe"""       ,			A__       ,			A__     )
						return tf.einsum("""ibd,nd->ibn"""       ,			A__       ,			A__     ) + b






					@staticmethod
					def     __A     (					A__       ,			A__     ):
						A__				:       Optional[Any]	  =						shape_list(A__     )
						A__				:       Optional[Any]	  =						tf.range(lp_size[0]       ,			dtype=target.dtype     )
						A__				:       List[str]	  =						tf.stack([r, target]       ,			1     )
						return tf.gather_nd(A__       ,			A__     )






					def     __A     (					self       ,			A__       ,			A__       ,			A__=True       ,			A__=False     ):
						A__				:       str	  =						0
						if self.n_clusters == 0:
							A__				:       List[str]	  =						self._logit(A__       ,			self.out_layers[0][0]       ,			self.out_layers[0][1]       ,			self.out_projs[0]     )
							if target is not None:
								A__				:       Union[str, Any]	  =						tf.nn.sparse_softmax_cross_entropy_with_logits(labels=A__       ,			logits=A__     )
							A__				:       int	  =						tf.nn.log_softmax(A__       ,			axis=-1     )
						else:
							A__				:       Any	  =						shape_list(A__     )
							A__				:       int	  =						[]
							A__				:       Union[str, Any]	  =						tf.zeros(hidden_sizes[:2]     )
							for i in range(len(self.cutoffs     )     ):
								A__  ,  A__				:       Union[str, Any]	  =						self.cutoff_ends[i], self.cutoff_ends[i + 1]
								if target is not None:
									A__				:       Any	  =						(target >= l_idx) & (target < r_idx)
									A__				:       Optional[Any]	  =						tf.where(A__     )
									A__				:       int	  =						tf.boolean_mask(A__       ,			A__     ) - l_idx

								if self.div_val == 1:
									A__				:       Any	  =						self.out_layers[0][0][l_idx:r_idx]
									A__				:       List[Any]	  =						self.out_layers[0][1][l_idx:r_idx]
								else:
									A__				:       Optional[int]	  =						self.out_layers[i][0]
									A__				:       Tuple	  =						self.out_layers[i][1]

								if i == 0:
									A__				:       Union[str, Any]	  =						tf.concat([cur_W, self.cluster_weight]       ,			0     )
									A__				:       Optional[int]	  =						tf.concat([cur_b, self.cluster_bias]       ,			0     )

									A__				:       Any	  =						self._logit(A__       ,			A__       ,			A__       ,			self.out_projs[0]     )
									A__				:       Optional[Any]	  =						tf.nn.log_softmax(A__     )
									out.append(head_logprob[..., : self.cutoffs[0]]     )
									if target is not None:
										A__				:       Optional[Any]	  =						tf.boolean_mask(A__       ,			A__     )
										A__				:       List[str]	  =						self._gather_logprob(A__       ,			A__     )
								else:
									A__				:       str	  =						self._logit(A__       ,			A__       ,			A__       ,			self.out_projs[i]     )
									A__				:       Dict	  =						tf.nn.log_softmax(A__     )
									A__				:       List[str]	  =						self.cutoffs[0] + i - 1  # No probability for the head cluster
									A__				:       Optional[Any]	  =						head_logprob[..., cluster_prob_idx, None] + tail_logprob
									out.append(A__     )
									if target is not None:
										A__				:       Any	  =						tf.boolean_mask(A__       ,			A__     )
										A__				:       List[Any]	  =						tf.boolean_mask(A__       ,			A__     )
										A__				:       List[Any]	  =						self._gather_logprob(A__       ,			A__     )
										cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
								if target is not None:
									loss += tf.scatter_nd(A__       ,			-cur_logprob       ,			shape_list(A__     )     )
							A__				:       List[str]	  =						tf.concat(A__       ,			axis=-1     )

						if target is not None:
							if return_mean:
								A__				:       List[Any]	  =						tf.reduce_mean(A__     )
							# Add the training-time loss value to the layer using `self.add_loss()`.
							self.add_loss(A__     )

							# Log the loss as a metric (we could log arbitrary metrics,
							# including different metrics for training and inference.
							self.add_metric(A__       ,			name=self.name       ,			aggregation="""mean""" if return_mean else """"""     )

						return out



