





import json
import os
import tempfile
from unittest.mock import patch

import torch
from torch.utils.data import DataLoader, TensorDataset

from accelerate import DistributedType, infer_auto_device_map, init_empty_weights
from accelerate.accelerator import Accelerator
from accelerate.state import GradientState, PartialState
from accelerate.test_utils import require_bnb, require_multi_gpu, slow
from accelerate.test_utils.testing import AccelerateTestCase, require_cuda
from accelerate.utils import patch_environment




def 		lowerCAmelCase_    (  )      ->	Tuple:
    UpperCamelCase__							:				Tuple          =      torch.nn.Linear(2		,   4      )
    UpperCamelCase__							:				int          =      torch.optim.AdamW(model.parameters()		,   lr=1.0      )
    UpperCamelCase__							:				Optional[Any]          =      torch.optim.lr_scheduler.OneCycleLR(__UpperCAmelCase		,   max_lr=0.01		,   steps_per_epoch=2		,   epochs=1      )
    UpperCamelCase__							:				List[str]          =      DataLoader(TensorDataset(torch.tensor([1, 2, 3]      )      )      )
    UpperCamelCase__							:				Tuple          =      DataLoader(TensorDataset(torch.tensor([4, 5, 6]      )      )      )

    return model, optimizer, scheduler, train_dl, valid_dl




def 		lowerCAmelCase_    (  __UpperCAmelCase:			List[str]      )      ->	Tuple:
    return (model.weight.abs().sum() + model.bias.abs().sum()).item()




def 		lowerCAmelCase_    (  __UpperCAmelCase:			Optional[Any]      )      ->	List[str]:
    UpperCamelCase__							:				Tuple          =      torch.nn.Linear(*tuple(model.weight.T.shape      )      ).state_dict()
    model.load_state_dict(__UpperCAmelCase      )






class     lowercase__       (	__lowerCamelCase				):

   '''simple docstring'''


   @require_cuda
   def       UpperCamelCase__  (    self							) ->      List[str]:






       """simple docstring"""
       UpperCamelCase__							:				List[Any]          =      Accelerator()
       assert PartialState._shared_state["_cpu"] is False
       assert PartialState._shared_state["device"].type == "cuda"
       with self.assertRaises(__magic_name__							):
           UpperCamelCase__							:				Any          =      Accelerator(cpu=__magic_name__							)




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






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      Accelerator()
       UpperCamelCase__							:				List[Any]          =      GradientState()
       assert state.num_steps == 1
       UpperCamelCase__							:				Union[str, Any]          =      4
       assert state.num_steps == 4

       assert state.sync_gradients is True
       UpperCamelCase__							:				Optional[int]          =      False
       assert state.sync_gradients is False
       GradientState._reset_state()




   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      Accelerator()
       UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				List[str]          =      create_components()

       (
           (
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,
       )							:				List[str]          =      accelerator.prepare(__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							)

       self.assertTrue(prepared_model in accelerator._models							)
       self.assertTrue(prepared_optimizer in accelerator._optimizers							)
       self.assertTrue(prepared_scheduler in accelerator._schedulers							)
       self.assertTrue(prepared_train_dl in accelerator._dataloaders							)
       self.assertTrue(prepared_valid_dl in accelerator._dataloaders							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      Accelerator()
       UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				str          =      create_components()
       accelerator.prepare(__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							)
       accelerator.free_memory()

       self.assertTrue(len(accelerator._models							) == 0							)
       self.assertTrue(len(accelerator._optimizers							) == 0							)
       self.assertTrue(len(accelerator._schedulers							) == 0							)
       self.assertTrue(len(accelerator._dataloaders							) == 0							)




   def       UpperCamelCase__  (    self							) ->      Optional[int]:






       """simple docstring"""
       PartialState._reset_state()

       # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist
       def noop(*__magic_name__,		**__magic_name__							):
           pass

       with patch('''torch.cuda.set_device''',		__magic_name__							), patch_environment(ACCELERATE_TORCH_DEVICE='''cuda:64'''							):
           UpperCamelCase__							:				Union[str, Any]          =      Accelerator()
           self.assertEqual(str(accelerator.state.device							),		'''cuda:64'''							)




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






       """simple docstring"""
       UpperCamelCase__							:				Dict          =      Accelerator()
       UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				Optional[Any]          =      create_components()
       accelerator.prepare(__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							)

       UpperCamelCase__							:				Optional[Any]          =      get_signature(__magic_name__							)

       with tempfile.TemporaryDirectory() as tmpdirname:
           accelerator.save_state(__magic_name__							)

           # make sure random weights don't match
           load_random_weights(__magic_name__							)
           self.assertTrue(abs(model_signature - get_signature(__magic_name__							)							) > 1E-3							)

           # make sure loaded weights match
           accelerator.load_state(__magic_name__							)
           self.assertTrue(abs(model_signature - get_signature(__magic_name__							)							) < 1E-3							)




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






       """simple docstring"""
       UpperCamelCase__							:				str          =      Accelerator()
       UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				int          =      create_components()
       accelerator.prepare(__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							)

       UpperCamelCase__							:				Optional[Any]          =      get_signature(__magic_name__							)

       # saving hook
       def save_config(__magic_name__,		__magic_name__,		__magic_name__							):
           UpperCamelCase__							:				List[Any]          =      {'''class_name''': models[0].__class__.__name__}

           with open(os.path.join(__magic_name__,		'''data.json'''							),		'''w'''							) as f:
               json.dump(__magic_name__,		__magic_name__							)

        # loading hook
       def load_config(__magic_name__,		__magic_name__							):
           with open(os.path.join(__magic_name__,		'''data.json'''							),		'''r'''							) as f:
               UpperCamelCase__							:				Tuple          =      json.load(__magic_name__							)

           UpperCamelCase__							:				List[Any]          =      config['''class_name''']

       UpperCamelCase__							:				Any          =      accelerator.register_save_state_pre_hook(__magic_name__							)
       UpperCamelCase__							:				List[Any]          =      accelerator.register_load_state_pre_hook(__magic_name__							)

       with tempfile.TemporaryDirectory() as tmpdirname:
           accelerator.save_state(__magic_name__							)

           # make sure random weights don't match with hooks
           load_random_weights(__magic_name__							)
           self.assertTrue(abs(model_signature - get_signature(__magic_name__							)							) > 1E-3							)

           # random class name to verify correct one is loaded
           UpperCamelCase__							:				int          =      '''random'''

           # make sure loaded weights match with hooks
           accelerator.load_state(__magic_name__							)
           self.assertTrue(abs(model_signature - get_signature(__magic_name__							)							) < 1E-3							)

           # mode.class_name is loaded from config
           self.assertTrue(model.class_name == model.__class__.__name__							)

       # remove hooks
       save_hook.remove()
       load_hook.remove()

       with tempfile.TemporaryDirectory() as tmpdirname:
           accelerator.save_state(__magic_name__							)

           # make sure random weights don't match with hooks removed
           load_random_weights(__magic_name__							)
           self.assertTrue(abs(model_signature - get_signature(__magic_name__							)							) > 1E-3							)

           # random class name to verify correct one is loaded
           UpperCamelCase__							:				Optional[Any]          =      '''random'''

           # make sure loaded weights match with hooks removed
           accelerator.load_state(__magic_name__							)
           self.assertTrue(abs(model_signature - get_signature(__magic_name__							)							) < 1E-3							)

           # mode.class_name is NOT loaded from config
           self.assertTrue(model.class_name != model.__class__.__name__							)




   def       UpperCamelCase__  (    self							) ->      Optional[int]:






       """simple docstring"""
       UpperCamelCase__							:				Dict          =      Accelerator()
       UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				List[Any]          =      create_components()
       UpperCamelCase__							:				List[Any]          =      None

       # This should work
       UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				Optional[int]          =      accelerator.prepare(
           __magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							)
       self.assertTrue(dummy_obj is None							)




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      Accelerator()
       UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				str          =      create_components()
       UpperCamelCase__							:				Optional[int]          =      [1, 2, 3]

       # This should work
       UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				Any          =      accelerator.prepare(
           __magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							)
       self.assertEqual(
           getattr(__magic_name__,		'''_is_accelerate_prepared''',		__magic_name__							),		__magic_name__,		'''Dummy object should have `_is_accelerate_prepared` set to `True`''',		)
       self.assertEqual(
           getattr(__magic_name__,		'''_is_accelerate_prepared''',		__magic_name__							),		__magic_name__,		'''Model is missing `_is_accelerator_prepared` or is set to `False`''',		)
       self.assertEqual(
           getattr(__magic_name__,		'''_is_accelerate_prepared''',		__magic_name__							),		__magic_name__,		'''Optimizer is missing `_is_accelerator_prepared` or is set to `False`''',		)
       self.assertEqual(
           getattr(__magic_name__,		'''_is_accelerate_prepared''',		__magic_name__							),		__magic_name__,		'''Scheduler is missing `_is_accelerator_prepared` or is set to `False`''',		)
       self.assertEqual(
           getattr(__magic_name__,		'''_is_accelerate_prepared''',		__magic_name__							),		__magic_name__,		'''Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`''',		)
       self.assertEqual(
           getattr(__magic_name__,		'''_is_accelerate_prepared''',		__magic_name__							),		__magic_name__,		'''Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`''',		)




   @slow
   @require_bnb
   def       UpperCamelCase__  (    self							) ->      Optional[int]:






       """simple docstring"""
       from transformers import AutoModelForCausalLM

       UpperCamelCase__							:				Optional[Any]          =      AutoModelForCausalLM.from_pretrained(
           '''EleutherAI/gpt-neo-125m''',		load_in_abit=__magic_name__,		device_map={'''''': 0},		)
       UpperCamelCase__							:				Tuple          =      Accelerator()

       # This should work
       UpperCamelCase__							:				Union[str, Any]          =      accelerator.prepare(__magic_name__							)




   @slow
   @require_bnb
   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       from transformers import AutoModelForCausalLM

       UpperCamelCase__							:				Union[str, Any]          =      Accelerator()

       with init_empty_weights():
           UpperCamelCase__							:				int          =      AutoModelForCausalLM.from_pretrained(
               '''EleutherAI/gpt-neo-125m''',		)
           model.tie_weights()
           UpperCamelCase__							:				Optional[int]          =      infer_auto_device_map(__magic_name__							)
           UpperCamelCase__							:				List[str]          =      '''cpu'''

       UpperCamelCase__							:				List[str]          =      AutoModelForCausalLM.from_pretrained(
           '''EleutherAI/gpt-neo-125m''',		device_map=__magic_name__,		load_in_abit=__magic_name__,		llm_inta_enable_fpaa_cpu_offload=__magic_name__							)

       # This should not work and get value error
       with self.assertRaises(__magic_name__							):
           UpperCamelCase__							:				Tuple          =      accelerator.prepare(__magic_name__							)




   @slow
   @require_bnb
   @require_multi_gpu
   def       UpperCamelCase__  (    self							) ->      Optional[Any]:






       """simple docstring"""
       from transformers import AutoModelForCausalLM

       UpperCamelCase__							:				Optional[int]          =      {'''distributed_type''': DistributedType.MULTI_GPU}

       with init_empty_weights():
           UpperCamelCase__							:				int          =      AutoModelForCausalLM.from_pretrained(
               '''EleutherAI/gpt-neo-125m''',		)
           model.tie_weights()
           UpperCamelCase__							:				str          =      infer_auto_device_map(__magic_name__							)
           UpperCamelCase__							:				int          =      1

       UpperCamelCase__							:				int          =      AutoModelForCausalLM.from_pretrained(
           '''EleutherAI/gpt-neo-125m''',		load_in_abit=__magic_name__,		device_map=__magic_name__,		)
       UpperCamelCase__							:				Optional[Any]          =      Accelerator()

       # This should not work and get value error
       with self.assertRaises(__magic_name__							):
           UpperCamelCase__							:				Union[str, Any]          =      accelerator.prepare(__magic_name__							)

       PartialState._reset_state()




   @slow
   @require_bnb
   @require_multi_gpu
   def       UpperCamelCase__  (    self							) ->      Union[str, Any]:






       """simple docstring"""
       from transformers import AutoModelForCausalLM

       with init_empty_weights():
           UpperCamelCase__							:				Tuple          =      AutoModelForCausalLM.from_pretrained(
               '''EleutherAI/gpt-neo-125m''',		)
           UpperCamelCase__							:				List[Any]          =      infer_auto_device_map(__magic_name__							)
           UpperCamelCase__							:				List[Any]          =      1

       UpperCamelCase__							:				Any          =      AutoModelForCausalLM.from_pretrained(
           '''EleutherAI/gpt-neo-125m''',		load_in_abit=__magic_name__,		device_map=__magic_name__,		)
       UpperCamelCase__							:				Dict          =      Accelerator()

       # This should work
       UpperCamelCase__							:				Dict          =      accelerator.prepare(__magic_name__							)




   @require_cuda
   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				Dict          =      torch.nn.Linear(10,		10							)
       UpperCamelCase__							:				Any          =      torch.optim.SGD(model.parameters(),		lr=0.01							)
       UpperCamelCase__							:				int          =      Accelerator(cpu=__magic_name__							)
       UpperCamelCase__							:				str          =      accelerator.prepare(__magic_name__							)








from __future__ import annotations




def 		lowerCAmelCase_    (  __UpperCAmelCase:			int		,   __UpperCAmelCase:			int      )      ->	list[list[int]]:
    UpperCamelCase__							:				list[list[int]]          =      []
    create_all_state(1		,   __UpperCAmelCase		,   __UpperCAmelCase		,   []		,   __UpperCAmelCase      )
    return result




def 		lowerCAmelCase_    (  __UpperCAmelCase:			int		,   __UpperCAmelCase:			int		,   __UpperCAmelCase:			int		,   __UpperCAmelCase:			list[int]		,   __UpperCAmelCase:			list[list[int]]		,   )      ->	None:
    if level == 0:
        total_list.append(current_list[:]      )
        return

    for i in range(__UpperCAmelCase		,   total_number - level + 2      ):
        current_list.append(__UpperCAmelCase      )
        create_all_state(i + 1		,   __UpperCAmelCase		,   level - 1		,   __UpperCAmelCase		,   __UpperCAmelCase      )
        current_list.pop()




def 		lowerCAmelCase_    (  __UpperCAmelCase:			list[list[int]]      )      ->	None:
    for i in total_list:
        print(*__UpperCAmelCase      )


if __name__ == "__main__":
  UpperCAmelCase_     							= 4
  UpperCAmelCase_     							= 2
  UpperCAmelCase_     							= generate_all_combinations(n, k)
  print_all_state(total_list)

