


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


UpperCamelCase														=      logging.getLogger(__name__)


def     _SCREAMING_SNAKE_CASE      (					SCREAMING_SNAKE_CASE=2					,     SCREAMING_SNAKE_CASE=3					,     SCREAMING_SNAKE_CASE=16					,     SCREAMING_SNAKE_CASE = 10					,     SCREAMING_SNAKE_CASE = 2			):

  def get_dataset(SCREAMING_SNAKE_CASE			):
    A_ :							Optional[int]							=   torch.randn(batch_size * n_batches					,     1			)
    return TensorDataset(UpperCAmelCase__					,     a * x + b + 0.1 * torch.randn(batch_size * n_batches					,     1			)			)

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


def     _SCREAMING_SNAKE_CASE      (					SCREAMING_SNAKE_CASE					,     SCREAMING_SNAKE_CASE					,     SCREAMING_SNAKE_CASE					,     SCREAMING_SNAKE_CASE					,     SCREAMING_SNAKE_CASE					,     SCREAMING_SNAKE_CASE=None			):
  A_ :							int							=   []
  for epoch in range(UpperCAmelCase__			):
    # Train quickly
    model.train()
    for batch in dataloader:
      A_	,			A_ :							int							=   batch
      A_ :							Optional[Any]							=   model(UpperCAmelCase__			)
      A_ :							Any							=   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     _lowerCamelCase					(   nn.Module     ):




       """simple docstring"""



       def __init__( self						)->str:




         '''simple docstring'''





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







       def 			_snake_case			( self							,			_SCREAMING_SNAKE_CASE						)->Optional[int]:




         '''simple docstring'''





         return x * self.a + self.b






class     _lowerCamelCase					(   unittest.TestCase     ):




       """simple docstring"""



       def 			_snake_case			( self						)->List[Any]:




         '''simple docstring'''





         with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42						)
           A_ :							List[str]							=   DummyModel()
           A_ :							Optional[int]							=   torch.optim.Adam(params=model.parameters()							,			lr=1e-3						)
           A_	,			A_ :							Dict							=   dummy_dataloaders()
           A_ :							int							=   ProjectConfiguration(total_limit=1							,			project_dir=__UpperCamelCase							,			automatic_checkpoint_naming=__UpperCamelCase						)
           # Train baseline
           A_ :							Optional[Any]							=   Accelerator(project_config=__UpperCamelCase						)
           A_	,			A_	,			A_	,			A_ :							List[Any]							=   accelerator.prepare(
               __UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase						)
           # Save initial
           accelerator.save_state()

           # Save second state
           accelerator.save_state()
           self.assertEqual(len(os.listdir(accelerator.project_dir						)						)							,			1						)



       def 			_snake_case			( self						)->str:




         '''simple docstring'''





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

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

           A_ :							Optional[Any]							=   train(2							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase						)
           # Save everything
           A_ :							Optional[int]							=   os.path.join(__UpperCamelCase							,			'''checkpoint'''						)
           accelerator.save_state(__UpperCamelCase						)

           # Load everything back in and make sure all states work
           accelerator.load_state(__UpperCamelCase						)
           test_rands += train(1							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase						)
           ((A_)	,			(A_)) :							Tuple							=   model.a.item(), model.b.item()
           A_ :							Tuple							=   optimizer.state_dict()
           self.assertEqual(__UpperCamelCase							,			__UpperCamelCase						)
           self.assertEqual(__UpperCamelCase							,			__UpperCamelCase						)
           self.assertEqual(__UpperCamelCase							,			__UpperCamelCase						)
           self.assertEqual(__UpperCamelCase							,			__UpperCamelCase						)



       def 			_snake_case			( self						)->int:




         '''simple docstring'''





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

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

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

           A_ :							Optional[int]							=   train(2							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase						)
           # Save everything
           accelerator.save_state()

           # Load everything back in and make sure all states work
           accelerator.load_state(os.path.join(__UpperCamelCase							,			'''checkpoints'''							,			'''checkpoint_1'''						)						)
           test_rands += train(1							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase						)
           ((A_)	,			(A_)) :							Any							=   model.a.item(), model.b.item()
           A_ :							List[Any]							=   optimizer.state_dict()
           self.assertEqual(__UpperCamelCase							,			__UpperCamelCase						)
           self.assertEqual(__UpperCamelCase							,			__UpperCamelCase						)
           self.assertEqual(__UpperCamelCase							,			__UpperCamelCase						)
           self.assertEqual(__UpperCamelCase							,			__UpperCamelCase						)



       def 			_snake_case			( self						)->Optional[Any]:




         '''simple docstring'''





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




         '''simple docstring'''





         with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42						)
           A_ :							Tuple							=   DummyModel()
           A_ :							Tuple							=   torch.optim.Adam(params=model.parameters()							,			lr=1e-3						)
           A_ :							Optional[Any]							=   torch.optim.lr_scheduler.StepLR(__UpperCamelCase							,			step_size=1							,			gamma=0.9_9						)
           A_	,			A_ :							int							=   dummy_dataloaders()
           A_ :							Any							=   ProjectConfiguration(automatic_checkpoint_naming=__UpperCamelCase						)
           # Train baseline
           A_ :							Union[str, Any]							=   Accelerator(project_dir=__UpperCamelCase							,			project_config=__UpperCamelCase						)
           A_	,			A_	,			A_	,			A_	,			A_ :							int							=   accelerator.prepare(
               __UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase						)
           # Save initial
           accelerator.save_state()
           A_ :							Union[str, Any]							=   scheduler.state_dict()
           train(3							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase							,			__UpperCamelCase						)
           self.assertNotEqual(__UpperCamelCase							,			scheduler.state_dict()						)

           # Load everything back in and make sure all states work
           accelerator.load_state(os.path.join(__UpperCamelCase							,			'''checkpoints'''							,			'''checkpoint_0'''						)						)
           self.assertEqual(__UpperCamelCase							,			scheduler.state_dict()						)



       def 			_snake_case			( self						)->List[str]:




         '''simple docstring'''





         with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42						)
           A_ :							List[Any]							=   DummyModel()
           A_ :							List[Any]							=   ProjectConfiguration(automatic_checkpoint_naming=__UpperCamelCase							,			total_limit=2						)
           # Train baseline
           A_ :							Tuple							=   Accelerator(project_dir=__UpperCamelCase							,			project_config=__UpperCamelCase						)
           A_ :							str							=   accelerator.prepare(__UpperCamelCase						)
           # Save 3 states:
           for _ in range(11						):
             accelerator.save_state()
           self.assertTrue(not os.path.exists(os.path.join(__UpperCamelCase							,			'''checkpoints'''							,			'''checkpoint_0'''						)						)						)
           self.assertTrue(os.path.exists(os.path.join(__UpperCamelCase							,			'''checkpoints'''							,			'''checkpoint_9'''						)						)						)
           self.assertTrue(os.path.exists(os.path.join(__UpperCamelCase							,			'''checkpoints'''							,			'''checkpoint_10'''						)						)						)







       @require_cuda
       def 			_snake_case			( self						)->Optional[Any]:




         '''simple docstring'''





         A_ :							List[str]							=   ['''torchrun''', F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__						)]
         execute_subprocess_async(__UpperCamelCase							,			env=os.environ.copy()						)


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

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

lowercase   =	{'''UserAgent''': UserAgent().random}



def   __lowerCAmelCase    (				UpperCAmelCase__					:   Optional[int]							)	->     dict:
							lowerCamelCase_					=       script.contents[0]
							lowerCamelCase_					=       json.loads(data[data.find("""{\"config\""""							) : -1]							)
							return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]





class    __A:

					def __init__(						self       :  int ,       __UpperCamelCase       :  List[str] ):
												lowerCamelCase_					=       F'''https://www.instagram.com/{username}/'''
												lowerCamelCase_					=       self.get_json()

					def  lowercase__   (						self       :  List[str] ):
												lowerCamelCase_					=       requests.get(self.url ,       headers=__UpperCamelCase ).text
												lowerCamelCase_					=       BeautifulSoup(__UpperCamelCase ,       """html.parser""" ).find_all("""script""" )
												try:
																			return extract_user_profile(scripts[4] )
												except (json.decoder.JSONDecodeError, KeyError):
																			return extract_user_profile(scripts[3] )

					def __repr__(						self       :  Dict ):
												return F'''{self.__class__.__name__}(\'{self.username}\')'''

					def __str__(						self       :  Optional[Any] ):
												return F'''{self.fullname} ({self.username}) is {self.biography}'''

					@property
					def  lowercase__   (						self       :  Dict ):
												return self.user_data["username"]

					@property
					def  lowercase__   (						self       :  List[Any] ):
												return self.user_data["full_name"]

					@property
					def  lowercase__   (						self       :  Any ):
												return self.user_data["biography"]

					@property
					def  lowercase__   (						self       :  int ):
												return self.user_data["business_email"]

					@property
					def  lowercase__   (						self       :  List[str] ):
												return self.user_data["external_url"]

					@property
					def  lowercase__   (						self       :  List[Any] ):
												return self.user_data["edge_followed_by"]["count"]

					@property
					def  lowercase__   (						self       :  str ):
												return self.user_data["edge_follow"]["count"]

					@property
					def  lowercase__   (						self       :  List[str] ):
												return self.user_data["edge_owner_to_timeline_media"]["count"]

					@property
					def  lowercase__   (						self       :  List[str] ):
												return self.user_data["profile_pic_url_hd"]

					@property
					def  lowercase__   (						self       :  Optional[Any] ):
												return self.user_data["is_verified"]



					@property
					def  lowercase__   (						self       :  int ):
												return self.user_data["is_private"]



def   __lowerCAmelCase    (				UpperCAmelCase__					:   str = "github"							)	->     None:
							import os

							if os.environ.get("""CI"""							):
														return  # test failing on GitHub Actions
							lowerCamelCase_					=       InstagramUser(UpperCAmelCase__							)
							assert instagram_user.user_data
							assert isinstance(instagram_user.user_data      ,					UpperCAmelCase__							)
							assert instagram_user.username == username
							if username != "github":
														return
							assert instagram_user.fullname == "GitHub"
							assert instagram_user.biography == "Built for developers."
							assert instagram_user.number_of_posts > 1_5_0
							assert instagram_user.number_of_followers > 1_2_0_0_0_0
							assert instagram_user.number_of_followings > 1_5
							assert instagram_user.email == "support@github.com"
							assert instagram_user.website == "https://github.com/readme"
							assert instagram_user.profile_picture_url.startswith("""https://instagram."""							)
							assert instagram_user.is_verified is True
							assert instagram_user.is_private is False


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		lowercase   =	InstagramUser('''github''')
		print(instagram_user)
		print(F"""{instagram_user.number_of_posts = }""")
		print(F"""{instagram_user.number_of_followers = }""")
		print(F"""{instagram_user.number_of_followings = }""")
		print(F"""{instagram_user.email = }""")
		print(F"""{instagram_user.website = }""")
		print(F"""{instagram_user.profile_picture_url = }""")
		print(F"""{instagram_user.is_verified = }""")
		print(F"""{instagram_user.is_private = }""")





