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






def 							A						(    snake_case				:Tuple=2    , snake_case				:Any=3    , snake_case				:Dict=1_6    , snake_case				:int = 1_0    , snake_case				:int = 2		)				->     List[str]:

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

 __UpperCamelCase      =	get_dataset(snake_case		)
 __UpperCamelCase      =	get_dataset(snake_case		)
 __UpperCamelCase      =	DataLoader(snake_case    , shuffle=snake_case    , batch_size=snake_case    , num_workers=4		)
 __UpperCamelCase      =	DataLoader(snake_case    , shuffle=snake_case    , batch_size=snake_case    , num_workers=4		)
 return (train_dataloader, valid_dataloader)






def 							A						(    snake_case				:Optional[int]    , snake_case				:Union[str, Any]    , snake_case				:Union[str, Any]    , snake_case				:str    , snake_case				:Optional[Any]    , snake_case				:Union[str, Any]=None		)				->     Tuple:
 __UpperCamelCase      =	[]
 for epoch in range(snake_case		):
  # Train quickly
  model.train()
  for batch in dataloader:
   __UpperCamelCase  ,     __UpperCamelCase      =	batch
   __UpperCamelCase      =	model(snake_case		)
   __UpperCamelCase      =	torch.nn.functional.mse_loss(snake_case    , snake_case		)
   accelerator.backward(snake_case		)
   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      ):





     def __init__(     self				):

      '''simple docstring'''




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







     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      return x * self.a + self.b


class __lowerCAmelCase		(				unittest.TestCase      ):





     def 						UpperCAmelCase (     self				):

      '''simple docstring'''




      with tempfile.TemporaryDirectory() as tmpdir:
       set_seed(42				)
       __UpperCamelCase      =	DummyModel()
       __UpperCamelCase      =	torch.optim.Adam(params=model.parameters()     ,					lr=1E-3				)
       __UpperCamelCase  ,     __UpperCamelCase      =	dummy_dataloaders()
       __UpperCamelCase      =	ProjectConfiguration(total_limit=1     ,					project_dir=__UpperCAmelCase     ,					automatic_checkpoint_naming=__UpperCAmelCase				)
       # Train baseline
       __UpperCamelCase      =	Accelerator(project_config=__UpperCAmelCase				)
       __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase      =	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 						UpperCAmelCase (     self				):

      '''simple docstring'''




      with tempfile.TemporaryDirectory() as tmpdir:
       set_seed(42				)
       __UpperCamelCase      =	DummyModel()
       __UpperCamelCase      =	torch.optim.Adam(params=model.parameters()     ,					lr=1E-3				)
       __UpperCamelCase  ,     __UpperCamelCase      =	dummy_dataloaders()
       # Train baseline
       __UpperCamelCase      =	Accelerator()
       __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase      =	accelerator.prepare(
           __UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				)
       # Save initial
       __UpperCamelCase      =	os.path.join(__UpperCAmelCase     ,					'initial'				)
       accelerator.save_state(__UpperCAmelCase				)
       ((__UpperCamelCase)  ,     (__UpperCamelCase))      =	model.a.item(), model.b.item()
       __UpperCamelCase      =	optimizer.state_dict()
       __UpperCamelCase      =	train(3     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				)
       ((__UpperCamelCase)  ,     (__UpperCamelCase))      =	model.a.item(), model.b.item()
       __UpperCamelCase      =	optimizer.state_dict()

       # Train partially
       set_seed(42				)
       __UpperCamelCase      =	DummyModel()
       __UpperCamelCase      =	torch.optim.Adam(params=model.parameters()     ,					lr=1E-3				)
       __UpperCamelCase  ,     __UpperCamelCase      =	dummy_dataloaders()
       __UpperCamelCase      =	Accelerator()
       __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase      =	accelerator.prepare(
           __UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				)
       accelerator.load_state(__UpperCAmelCase				)
       ((__UpperCamelCase)  ,     (__UpperCamelCase))      =	model.a.item(), model.b.item()
       __UpperCamelCase      =	optimizer.state_dict()
       self.assertEqual(__UpperCAmelCase     ,					__UpperCAmelCase				)
       self.assertEqual(__UpperCAmelCase     ,					__UpperCAmelCase				)
       self.assertEqual(__UpperCAmelCase     ,					__UpperCAmelCase				)

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





     def 						UpperCAmelCase (     self				):

      '''simple docstring'''




      with tempfile.TemporaryDirectory() as tmpdir:
       set_seed(42				)
       __UpperCamelCase      =	DummyModel()
       __UpperCamelCase      =	torch.optim.Adam(params=model.parameters()     ,					lr=1E-3				)
       __UpperCamelCase  ,     __UpperCamelCase      =	dummy_dataloaders()
       __UpperCamelCase      =	ProjectConfiguration(automatic_checkpoint_naming=__UpperCAmelCase				)

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

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

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





     def 						UpperCAmelCase (     self				):

      '''simple docstring'''




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

      '''simple docstring'''




      with tempfile.TemporaryDirectory() as tmpdir:
       set_seed(42				)
       __UpperCamelCase      =	DummyModel()
       __UpperCamelCase      =	torch.optim.Adam(params=model.parameters()     ,					lr=1E-3				)
       __UpperCamelCase      =	torch.optim.lr_scheduler.StepLR(__UpperCAmelCase     ,					step_size=1     ,					gamma=0.9_9				)
       __UpperCamelCase  ,     __UpperCamelCase      =	dummy_dataloaders()
       __UpperCamelCase      =	ProjectConfiguration(automatic_checkpoint_naming=__UpperCAmelCase				)
       # Train baseline
       __UpperCamelCase      =	Accelerator(project_dir=__UpperCAmelCase     ,					project_config=__UpperCAmelCase				)
       __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase  ,     __UpperCamelCase      =	accelerator.prepare(
           __UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				)
       # Save initial
       accelerator.save_state()
       __UpperCamelCase      =	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 						UpperCAmelCase (     self				):

      '''simple docstring'''




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

      '''simple docstring'''




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

UpperCamelCase     :    Union[str, Any]       =			[
    [0, 1_6, 1_3, 0, 0, 0],
    [0, 0, 1_0, 1_2, 0, 0],
    [0, 4, 0, 0, 1_4, 0],
    [0, 0, 9, 0, 0, 2_0],
    [0, 0, 0, 7, 0, 4],
    [0, 0, 0, 0, 0, 0],
]






def 							A						(    snake_case				:Dict    , snake_case				:Tuple    , snake_case				:str    , snake_case				:Optional[int]		)				->     Union[str, Any]:
 # Return True if there is node that has not iterated.
 __UpperCamelCase      =	[False] * len(snake_case		)
 __UpperCamelCase      =	[s]
 __UpperCamelCase      =	True

 while queue:
  __UpperCamelCase      =	queue.pop(0		)
  for ind in range(len(graph[u]		)		):
   if visited[ind] is False and graph[u][ind] > 0:
    queue.append(snake_case		)
    __UpperCamelCase      =	True
    __UpperCamelCase      =	u

 return visited[t]






def 							A						(    snake_case				:int    , snake_case				:Any    , snake_case				:Union[str, Any]		)				->     Optional[int]:
 __UpperCamelCase      =	[-1] * (len(snake_case		))
 __UpperCamelCase      =	0
 __UpperCamelCase      =	[]
 __UpperCamelCase      =	[i[:] for i in graph]  # Record original cut, copy.
 while bfs(snake_case    , snake_case    , snake_case    , snake_case		):
  __UpperCamelCase      =	float('Inf'		)
  __UpperCamelCase      =	sink

  while s != source:
   # Find the minimum value in select path
   __UpperCamelCase      =	min(snake_case    , graph[parent[s]][s]		)
   __UpperCamelCase      =	parent[s]

  max_flow += path_flow
  __UpperCamelCase      =	sink

  while v != source:
   __UpperCamelCase      =	parent[v]
   graph[u][v] -= path_flow
   graph[v][u] += path_flow
   __UpperCamelCase      =	parent[v]

 for i in range(len(snake_case		)		):
  for j in range(len(graph[0]		)		):
   if graph[i][j] == 0 and temp[i][j] > 0:
    res.append((i, j)		)

 return res


if __name__ == "__main__":
      print(mincut(test_graph, source=0, sink=5))



