



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


_UpperCAmelCase     =			logging.getLogger(__name__)





def      __magic_name__				(							lowercase=2							,			lowercase=3							,			lowercase=16							,			lowercase = 10							,			lowercase = 2 ):

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

   SCREAMING_SNAKE_CASE_: Dict     			=get_dataset(lowercase )
   SCREAMING_SNAKE_CASE_: Optional[Any]     			=get_dataset(lowercase )
   SCREAMING_SNAKE_CASE_: Optional[Any]     			=DataLoader(lowercase							,			shuffle=lowercase							,			batch_size=lowercase							,			num_workers=4 )
   SCREAMING_SNAKE_CASE_: Optional[Any]     			=DataLoader(lowercase							,			shuffle=lowercase							,			batch_size=lowercase							,			num_workers=4 )
   return (train_dataloader, valid_dataloader)





def      __magic_name__				(							lowercase							,			lowercase							,			lowercase							,			lowercase							,			lowercase							,			lowercase=None ):
   SCREAMING_SNAKE_CASE_: int     			=[]
   for epoch in range(lowercase ):
      # Train quickly
      model.train()
      for batch in dataloader:
         SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: Any     			=batch
         SCREAMING_SNAKE_CASE_: Dict     			=model(lowercase )
         SCREAMING_SNAKE_CASE_: Optional[Any]     			=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 					a	(  nn.Module       ):



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


     '''simple docstring'''




     super().__init__()
     SCREAMING_SNAKE_CASE_: List[Any]     			=nn.Parameter(torch.randn(1		)		)
     SCREAMING_SNAKE_CASE_: Tuple     			=nn.Parameter(torch.randn(1		)		)





  def 	lowerCamelCase__       (						self :					Dict       ,		lowerCAmelCase :					Any		)     ->					Tuple:


     '''simple docstring'''




     return x * self.a + self.b







class 					a	(  unittest.TestCase       ):



  def 	lowerCamelCase__       (						self :					Dict		)     ->					Union[str, Any]:


     '''simple docstring'''




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


     '''simple docstring'''




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

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

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



  def 	lowerCamelCase__       (						self :					Dict		)     ->					Optional[Any]:


     '''simple docstring'''




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

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

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

        SCREAMING_SNAKE_CASE_: Optional[int]     			=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		)
        ((SCREAMING_SNAKE_CASE_)			,		(SCREAMING_SNAKE_CASE_)): Optional[Any]     			=model.a.item(), model.b.item()
        SCREAMING_SNAKE_CASE_: int     			=optimizer.state_dict()
        self.assertEqual(lowerCAmelCase       ,		lowerCAmelCase		)
        self.assertEqual(lowerCAmelCase       ,		lowerCAmelCase		)
        self.assertEqual(lowerCAmelCase       ,		lowerCAmelCase		)
        self.assertEqual(lowerCAmelCase       ,		lowerCAmelCase		)



  def 	lowerCamelCase__       (						self :					Optional[Any]		)     ->					Optional[int]:


     '''simple docstring'''




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


     '''simple docstring'''




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


     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdir:
        set_seed(42		)
        SCREAMING_SNAKE_CASE_: Any     			=DummyModel()
        SCREAMING_SNAKE_CASE_: Optional[int]     			=ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase       ,		total_limit=2		)
        # Train baseline
        SCREAMING_SNAKE_CASE_: Union[str, Any]     			=Accelerator(project_dir=lowerCAmelCase       ,		project_config=lowerCAmelCase		)
        SCREAMING_SNAKE_CASE_: Union[str, Any]     			=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 	lowerCamelCase__       (						self :					List[str]		)     ->					Union[str, Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__		)]
     execute_subprocess_async(lowerCAmelCase       ,		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.9_9)
   _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()








"""simple docstring"""
import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier





def      __magic_name__				(							lowercase ):
   return (data["data"], data["target"])





def      __magic_name__				(							lowercase							,			lowercase ):
   SCREAMING_SNAKE_CASE_: Dict     			=XGBClassifier()
   classifier.fit(lowercase							,			lowercase )
   return classifier





def      __magic_name__				(							):
   SCREAMING_SNAKE_CASE_: Optional[Any]     			=load_iris()
   SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: Tuple     			=data_handling(lowercase )
   SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: List[Any]     			=train_test_split(
       lowercase							,			lowercase							,			test_size=0.25 )

   SCREAMING_SNAKE_CASE_: Tuple     			=iris["""target_names"""]

   # Create an XGBoost Classifier from the training data
   SCREAMING_SNAKE_CASE_: Optional[int]     			=xgboost(lowercase							,			lowercase )

   # Display the confusion matrix of the classifier with both training and test sets
   ConfusionMatrixDisplay.from_estimator(
       lowercase							,			lowercase							,			lowercase							,			display_labels=lowercase							,			cmap="""Blues"""							,			normalize="""true"""							,			)
   plt.title("""Normalized Confusion Matrix - IRIS Dataset""" )
   plt.show()


if __name__ == "__main__":
   import doctest

   doctest.testmod(verbose=True)
   main()



