




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


a       :						Any								=		logging.getLogger(__name__)


def __UpperCAmelCase	(   _UpperCAmelCase		:   Union[str, Any]=2		,				_UpperCAmelCase		:   Tuple=3		,				_UpperCAmelCase		:   List[Any]=16		,				_UpperCAmelCase		:   Optional[Any] = 10		,				_UpperCAmelCase		:   Tuple = 2						)      ->      Tuple:



			def get_dataset(_UpperCAmelCase		:   List[str]						):
						__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 __UpperCAmelCase	(   _UpperCAmelCase		:   List[Any]		,				_UpperCAmelCase		:   str		,				_UpperCAmelCase		:   Union[str, Any]		,				_UpperCAmelCase		:   Dict		,				_UpperCAmelCase		:   Dict		,				_UpperCAmelCase		:   Optional[Any]=None						)      ->      List[Any]:
			__snake_case			=		[]
			for epoch in range(_UpperCamelCase						):
						# Train quickly
						model.train()
						for batch in dataloader:
									__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 		SCREAMING_SNAKE_CASE__  (			nn.Module	):





			def __init__(      self						:    Union[str, Any]							):



						"""simple docstring"""




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






			def 							A (      self						:    Optional[int]      ,		a_						:    int							):



						"""simple docstring"""




						return x * self.a + self.b







class 		SCREAMING_SNAKE_CASE__  (			unittest.TestCase	):





			def 							A (      self						:    Any							):



						"""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			=		dummy_dataloaders()
									__snake_case			=		ProjectConfiguration(total_limit=1      ,		project_dir=A_      ,		automatic_checkpoint_naming=A_							)
									# Train baseline
									__snake_case			=		Accelerator(project_config=A_							)
									__snake_case			=		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 							A (      self						:    Any							):



						"""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			=		dummy_dataloaders()
									# Train baseline
									__snake_case			=		Accelerator()
									__snake_case			=		accelerator.prepare(
									    A_      ,		A_      ,		A_      ,		A_							)
									# Save initial
									__snake_case			=		os.path.join(A_      ,		"initial"							)
									accelerator.save_state(A_							)
									(__snake_case)			=		model.a.item(), model.b.item()
									__snake_case			=		optimizer.state_dict()
									__snake_case			=		train(3      ,		A_      ,		A_      ,		A_      ,		A_							)
									(__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			=		dummy_dataloaders()
									__snake_case			=		Accelerator()
									__snake_case			=		accelerator.prepare(
									    A_      ,		A_      ,		A_      ,		A_							)
									accelerator.load_state(A_							)
									(__snake_case)			=		model.a.item(), model.b.item()
									__snake_case			=		optimizer.state_dict()
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)

									__snake_case			=		train(2      ,		A_      ,		A_      ,		A_      ,		A_							)
									# Save everything
									__snake_case			=		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_							)
									(__snake_case)			=		model.a.item(), model.b.item()
									__snake_case			=		optimizer.state_dict()
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)





			def 							A (      self						:    Tuple							):



						"""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			=		dummy_dataloaders()
									__snake_case			=		ProjectConfiguration(automatic_checkpoint_naming=A_							)

									# Train baseline
									__snake_case			=		Accelerator(project_dir=A_      ,		project_config=A_							)
									__snake_case			=		accelerator.prepare(
									    A_      ,		A_      ,		A_      ,		A_							)
									# Save initial
									accelerator.save_state()
									(__snake_case)			=		model.a.item(), model.b.item()
									__snake_case			=		optimizer.state_dict()
									__snake_case			=		train(3      ,		A_      ,		A_      ,		A_      ,		A_							)
									(__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			=		dummy_dataloaders()
									__snake_case			=		ProjectConfiguration(iteration=1      ,		automatic_checkpoint_naming=A_							)
									__snake_case			=		Accelerator(project_dir=A_      ,		project_config=A_							)
									__snake_case			=		accelerator.prepare(
									    A_      ,		A_      ,		A_      ,		A_							)
									accelerator.load_state(os.path.join(A_      ,		"checkpoints"      ,		"checkpoint_0"							)							)
									(__snake_case)			=		model.a.item(), model.b.item()
									__snake_case			=		optimizer.state_dict()
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)

									__snake_case			=		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_							)
									(__snake_case)			=		model.a.item(), model.b.item()
									__snake_case			=		optimizer.state_dict()
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)
									self.assertEqual(A_      ,		A_							)





			def 							A (      self						:    int							):



						"""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(A_							) as ve:
									accelerator.register_for_checkpointing(A_      ,		A_      ,		A_      ,		A_							)
						__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 							A (      self						:    Optional[Any]							):



						"""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(A_      ,		step_size=1      ,		gamma=0.99							)
									__snake_case			=		dummy_dataloaders()
									__snake_case			=		ProjectConfiguration(automatic_checkpoint_naming=A_							)
									# Train baseline
									__snake_case			=		Accelerator(project_dir=A_      ,		project_config=A_							)
									__snake_case			=		accelerator.prepare(
									    A_      ,		A_      ,		A_      ,		A_      ,		A_							)
									# Save initial
									accelerator.save_state()
									__snake_case			=		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 							A (      self						:    Any							):



						"""simple docstring"""




						with tempfile.TemporaryDirectory() as tmpdir:
									set_seed(42							)
									__snake_case			=		DummyModel()
									__snake_case			=		ProjectConfiguration(automatic_checkpoint_naming=A_      ,		total_limit=2							)
									# Train baseline
									__snake_case			=		Accelerator(project_dir=A_      ,		project_config=A_							)
									__snake_case			=		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 							A (      self						:    Any							):



						"""simple docstring"""




						__snake_case			=		['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__							)]
						execute_subprocess_async(A_      ,		env=os.environ.copy()							)


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







"""simple docstring"""




from __future__ import annotations

import typing
from collections import Counter




def 			_lowerCAmelCase		(		_UpperCamelCase    ):






  """simple docstring"""



  _lowercase:      typing.Counter[int]   			=  Counter()
  for base in range(1			,					max_perimeter + 1    ):
    for perpendicular in range(_UpperCamelCase			,					max_perimeter + 1    ):
      _lowercase:      str   			=  (base * base + perpendicular * perpendicular) ** 0.5
      if hypotenuse == int(_UpperCamelCase    ):
        _lowercase:      str   			=  int(base + perpendicular + hypotenuse    )
        if perimeter > max_perimeter:
          continue
        triplets[perimeter] += 1
  return triplets




def 			_lowerCAmelCase		(		_UpperCamelCase = 1_000    ):






  """simple docstring"""



  _lowercase:      int   			=  pythagorean_triple(_UpperCamelCase    )
  return triplets.most_common(1    )[0][0]


if __name__ == "__main__":
  print(f"""Perimeter {solution()} has maximum solutions""")
