
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


__magic_name__            =  logging.getLogger(__name__)





def 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase=2    ,		__lowerCAmelCase=3    ,		__lowerCAmelCase=16    ,		__lowerCAmelCase = 10    ,		__lowerCAmelCase = 2							):

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

    snake_case__						=				get_dataset(__lowerCAmelCase							)
    snake_case__						=				get_dataset(__lowerCAmelCase							)
    snake_case__						=				DataLoader(__lowerCAmelCase    ,		shuffle=__lowerCAmelCase    ,		batch_size=__lowerCAmelCase    ,		num_workers=4							)
    snake_case__						=				DataLoader(__lowerCAmelCase    ,		shuffle=__lowerCAmelCase    ,		batch_size=__lowerCAmelCase    ,		num_workers=4							)
    return (train_dataloader, valid_dataloader)





def 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase    ,		__lowerCAmelCase    ,		__lowerCAmelCase    ,		__lowerCAmelCase    ,		__lowerCAmelCase    ,		__lowerCAmelCase=None							):
    snake_case__						=				[]
    for epoch in range(__lowerCAmelCase							):
        # Train quickly
        model.train()
        for batch in dataloader:
            snake_case__						,					snake_case__						=				batch
            snake_case__						=				model(__lowerCAmelCase							)
            snake_case__						=				torch.nn.functional.mse_loss(__lowerCAmelCase    ,		__lowerCAmelCase							)
            accelerator.backward(__lowerCAmelCase							)
            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 ):
          super().__init__()
          snake_case__						=				nn.Parameter(torch.randn(1 ) )
          snake_case__						=				nn.Parameter(torch.randn(1 ) )



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





class 					_SCREAMING_SNAKE_CASE  (      unittest.TestCase ):
      def A_			(			self ):
          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 A_			(			self ):
          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 A_			(			self ):
          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 A_			(			self ):
          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 A_			(			self ):
          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.9_9 )
              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 A_			(			self ):
          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 A_			(			self ):
          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__":
     __magic_name__            =  '''/tmp/accelerate/state_checkpointing'''
     __magic_name__            =  DummyModel()
     __magic_name__            =  torch.optim.Adam(params=model.parameters(), lr=1e-3)
     __magic_name__            =  torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9_9)
     __magic_name__       ,      __magic_name__            =  dummy_dataloaders()
     __magic_name__            =  ProjectConfiguration(automatic_checkpoint_naming=True)
     # Train baseline
     __magic_name__            =  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)
     __magic_name__       ,      __magic_name__       ,      __magic_name__       ,      __magic_name__       ,      __magic_name__            =  accelerator.prepare(
         model, optimizer, train_dataloader, valid_dataloader, scheduler
     )
     __magic_name__       ,      __magic_name__            =  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:
          __magic_name__            =  group['''params'''][0].device
          break
     assert param_device.type == accelerator.device.type
     __magic_name__            =  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:
          __magic_name__            =  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:
          __magic_name__            =  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 __future__ import annotations

from fractions import Fraction





def 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase    ,		__lowerCAmelCase							):
    return (
        num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
    )





def 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase							):
    snake_case__						=				[]
    snake_case__						=				11
    snake_case__						=				int("1" + "0" * digit_len							)
    for num in range(__lowerCAmelCase    ,		__lowerCAmelCase							):
        while den <= 99:
            if (num != den) and (num % 10 == den // 10) and (den % 10 != 0):
                if is_digit_cancelling(__lowerCAmelCase    ,		__lowerCAmelCase							):
                    solutions.append(F"""{num}/{den}"""							)
            den += 1
        num += 1
        snake_case__						=				10
    return solutions





def 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase = 2							):
    snake_case__						=				1.0
    for fraction in fraction_list(__lowerCAmelCase							):
        snake_case__						=				Fraction(__lowerCAmelCase							)
        result *= frac.denominator / frac.numerator
    return int(__lowerCAmelCase							)


if __name__ == "__main__":
     print(solution())



