





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    :       Optional[int]		       =    logging.getLogger(__name__)

def     a_       (					lowerCAmelCase_ :     List[Any]=2,      lowerCAmelCase_ :     List[str]=3,      lowerCAmelCase_ :     List[Any]=16,      lowerCAmelCase_ :     int = 10,      lowerCAmelCase_ :     int = 2      ):

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

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

def     a_       (					lowerCAmelCase_ :     Optional[int],      lowerCAmelCase_ :     Any,      lowerCAmelCase_ :     Union[str, Any],      lowerCAmelCase_ :     int,      lowerCAmelCase_ :     Union[str, Any],      lowerCAmelCase_ :     List[str]=None      ):
   __lowerCAmelCase				      =      []
   for epoch in range(lowerCAmelCase_      ):
      # Train quickly
      model.train()
      for batch in dataloader:
         __lowerCAmelCase      ,      __lowerCAmelCase				      =      batch
         __lowerCAmelCase				      =      model(lowerCAmelCase_      )
         __lowerCAmelCase				      =      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 							_UpperCAmelCase       (       nn.Module       ):

  """simple docstring"""


  def __init__(							self					:						List[str]	)				->		Any:
     super().__init__()
     __lowerCAmelCase				      =      nn.Parameter(torch.randn(1	)	)
     __lowerCAmelCase				      =      nn.Parameter(torch.randn(1	)	)






  def 							lowercase						(							self					:						int   ,    lowerCAmelCase_					:						Tuple	)				->		List[str]:
     return x * self.a + self.b





class 							_UpperCAmelCase       (       unittest.TestCase       ):

  """simple docstring"""


  def 							lowercase						(							self					:						str	)				->		Any:
     with tempfile.TemporaryDirectory() as tmpdir:
        set_seed(4_2	)
        __lowerCAmelCase				      =      DummyModel()
        __lowerCAmelCase				      =      torch.optim.Adam(params=model.parameters()   ,    lr=1e-3	)
        __lowerCAmelCase      ,      __lowerCAmelCase				      =      dummy_dataloaders()
        __lowerCAmelCase				      =      ProjectConfiguration(total_limit=1   ,    project_dir=lowerCAmelCase_   ,    automatic_checkpoint_naming=lowerCAmelCase_	)
        # Train baseline
        __lowerCAmelCase				      =      Accelerator(project_config=lowerCAmelCase_	)
        __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase				      =      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 							lowercase						(							self					:						Dict	)				->		Dict:
     with tempfile.TemporaryDirectory() as tmpdir:
        set_seed(4_2	)
        __lowerCAmelCase				      =      DummyModel()
        __lowerCAmelCase				      =      torch.optim.Adam(params=model.parameters()   ,    lr=1e-3	)
        __lowerCAmelCase      ,      __lowerCAmelCase				      =      dummy_dataloaders()
        # Train baseline
        __lowerCAmelCase				      =      Accelerator()
        __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase      ,      __lowerCAmelCase				      =      accelerator.prepare(
            lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_	)
        # Save initial
        __lowerCAmelCase				      =      os.path.join(lowerCAmelCase_   ,    'initial'	)
        accelerator.save_state(lowerCAmelCase_	)
        ((__lowerCAmelCase)      ,      (__lowerCAmelCase))				      =      model.a.item(), model.b.item()
        __lowerCAmelCase				      =      optimizer.state_dict()
        __lowerCAmelCase				      =      train(3   ,    lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_	)
        ((__lowerCAmelCase)      ,      (__lowerCAmelCase))				      =      model.a.item(), model.b.item()
        __lowerCAmelCase				      =      optimizer.state_dict()

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

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






  def 							lowercase						(							self					:						Tuple	)				->		Tuple:
     with tempfile.TemporaryDirectory() as tmpdir:
        set_seed(4_2	)
        __lowerCAmelCase				      =      DummyModel()
        __lowerCAmelCase				      =      torch.optim.Adam(params=model.parameters()   ,    lr=1e-3	)
        __lowerCAmelCase      ,      __lowerCAmelCase				      =      dummy_dataloaders()
        __lowerCAmelCase				      =      ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase_	)

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

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

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






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


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

def 				snake_case       (  a_				:			int						)							->					int:





      """simple docstring"""

      if n == 1 or not isinstance(a_     , a_						):
            return 0
      elif n == 2:
            return 1
      else:
            UpperCamelCase_					: Dict            =				[0, 1]
            for i in range(2     , n + 1						):
                  sequence.append(sequence[i - 1] + sequence[i - 2]						)

            return sequence[n]



def 				snake_case       (  a_				:			int						)							->					int:





      """simple docstring"""

      UpperCamelCase_					: Any            =				0
      UpperCamelCase_					: Union[str, Any]            =				2

      while digits < n:
            index += 1
            UpperCamelCase_					: Any            =				len(str(fibonacci(a_						)						)						)

      return index



def 				snake_case       (  a_				:			int = 1_000						)							->					int:





      """simple docstring"""

      return fibonacci_digits_index(a_						)


if __name__ == "__main__":
      print(solution(int(str(input()).strip())))






