




import unittest
from dataclasses import dataclass
from typing import Optional

from transformers.utils import ModelOutput

@dataclass
class 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE ):

      """simple docstring"""

      lowerCAmelCase__      :			float
      lowerCAmelCase__      :			Optional[float]     =       None
      lowerCAmelCase__      :			Optional[float]     =       None







class 			_lowerCamelCase    (      unittest.TestCase ):

      """simple docstring"""

      def    snake_case						(  self       :			str					):
          __UpperCamelCase			=    ModelOutputTest(a=30					)
          self.assertEqual(x.a			,							30					)
          self.assertIsNone(x.b					)
          self.assertIsNone(x.c					)
          with self.assertRaises(snake_case					):
              __UpperCamelCase			=    x.d







      def    snake_case						(  self       :			Tuple					):
          __UpperCamelCase			=    ModelOutputTest(a=30			,							b=10					)
          self.assertEqual(x[0]			,							30					)
          self.assertEqual(x[1]			,							10					)
          self.assertEqual(x[:2]			,							(30, 10)					)
          self.assertEqual(x[:]			,							(30, 10)					)

          __UpperCamelCase			=    ModelOutputTest(a=30			,							c=10					)
          self.assertEqual(x[0]			,							30					)
          self.assertEqual(x[1]			,							10					)
          self.assertEqual(x[:2]			,							(30, 10)					)
          self.assertEqual(x[:]			,							(30, 10)					)







      def    snake_case						(  self       :			List[str]					):
          __UpperCamelCase			=    ModelOutputTest(a=30			,							b=10					)
          self.assertEqual(x['''a''']			,							30					)
          self.assertEqual(x['''b''']			,							10					)
          with self.assertRaises(snake_case					):
              __UpperCamelCase			=    x['''c''']

          __UpperCamelCase			=    ModelOutputTest(a=30			,							c=10					)
          self.assertEqual(x['''a''']			,							30					)
          self.assertEqual(x['''c''']			,							10					)
          with self.assertRaises(snake_case					):
              __UpperCamelCase			=    x['''b''']







      def    snake_case						(  self       :			Tuple					):
          __UpperCamelCase			=    ModelOutputTest(a=30					)
          self.assertEqual(list(x.keys()					)			,							['''a''']					)
          self.assertEqual(list(x.values()					)			,							[30]					)
          self.assertEqual(list(x.items()					)			,							[('''a''', 30)]					)
          self.assertEqual(list(snake_case					)			,							['''a''']					)

          __UpperCamelCase			=    ModelOutputTest(a=30			,							b=10					)
          self.assertEqual(list(x.keys()					)			,							['''a''', '''b''']					)
          self.assertEqual(list(x.values()					)			,							[30, 10]					)
          self.assertEqual(list(x.items()					)			,							[('''a''', 30), ('''b''', 10)]					)
          self.assertEqual(list(snake_case					)			,							['''a''', '''b''']					)

          __UpperCamelCase			=    ModelOutputTest(a=30			,							c=10					)
          self.assertEqual(list(x.keys()					)			,							['''a''', '''c''']					)
          self.assertEqual(list(x.values()					)			,							[30, 10]					)
          self.assertEqual(list(x.items()					)			,							[('''a''', 30), ('''c''', 10)]					)
          self.assertEqual(list(snake_case					)			,							['''a''', '''c''']					)

          with self.assertRaises(snake_case					):
              __UpperCamelCase			=    x.update({'''d''': 20}					)
          with self.assertRaises(snake_case					):
              del x["a"]
          with self.assertRaises(snake_case					):
              __UpperCamelCase			=    x.pop('''a'''					)
          with self.assertRaises(snake_case					):
              __UpperCamelCase			=    x.setdefault('''d'''			,							32					)







      def    snake_case						(  self       :			Optional[Any]					):
          __UpperCamelCase			=    ModelOutputTest(a=30					)
          __UpperCamelCase			=    10
          self.assertEqual(x.a			,							10					)
          self.assertEqual(x['''a''']			,							10					)







      def    snake_case						(  self       :			Optional[int]					):
          __UpperCamelCase			=    ModelOutputTest(a=30					)
          __UpperCamelCase			=    10
          self.assertEqual(x.a			,							10					)
          self.assertEqual(x['''a''']			,							10					)







      def    snake_case						(  self       :			Optional[Any]					):
          __UpperCamelCase			=    ModelOutputTest({'''a''': 30, '''b''': 10}					)
          self.assertEqual(list(x.keys()					)			,							['''a''', '''b''']					)
          self.assertEqual(x.a			,							30					)
          self.assertEqual(x.b			,							10					)







      def    snake_case						(  self       :			Any					):
          __UpperCamelCase			=    ModelOutputTest([('''a''', 30), ('''b''', 10)]					)
          self.assertEqual(list(x.keys()					)			,							['''a''', '''b''']					)
          self.assertEqual(x.a			,							30					)
          self.assertEqual(x.b			,							10					)

          with self.assertRaises(snake_case					):
              __UpperCamelCase			=    ModelOutputTest([('''a''', 30), (10, 10)]					)

          __UpperCamelCase			=    ModelOutputTest(a=(30, 30)					)
          self.assertEqual(list(x.keys()					)			,							['''a''']					)
          self.assertEqual(x.a			,							(30, 30)					)








import os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
							import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


lowercase__						:Optional[Any]					    =       get_logger(__name__)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = None					,     ):
					'''simple docstring'''
					# Model states
					for i, state in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Model weights saved in {output_model_file}'						)
					# Optimizer states
					for i, opt in enumerate(lowerCAmelCase__						):
										lowercase		      =		opt.state_dict()
										lowercase		      =		f'{OPTIMIZER_NAME}.bin' if i == 0 else f'{OPTIMIZER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Optimizer state saved in {output_optimizer_file}'						)
					# Scheduler states
					for i, scheduler in enumerate(lowerCAmelCase__						):
										lowercase		      =		scheduler.state_dict()
										lowercase		      =		f'{SCHEDULER_NAME}.bin' if i == 0 else f'{SCHEDULER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Scheduler state saved in {output_scheduler_file}'						)
					# GradScaler state
					if scaler is not None:
										lowercase		      =		scaler.state_dict()
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										torch.save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Gradient scaler state saved in {output_scaler_file}'						)
					# Random number generator states
					lowercase		      =		{}
					lowercase		      =		f'{RNG_STATE_NAME}_{process_index}.pkl'
					lowercase		      =		random.getstate()
					lowercase		      =		np.random.get_state()
					lowercase		      =		torch.get_rng_state()
					if is_xpu_available():
										lowercase		      =		torch.xpu.get_rng_state_all()
					else:
										lowercase		      =		torch.cuda.get_rng_state_all()
					if is_tpu_available():
										lowercase		      =		xm.get_rng_state()
					lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
					torch.save(lowerCAmelCase__					,     lowerCAmelCase__						)
					logger.info(f'Random states saved in {output_states_file}'						)
					return output_dir



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__=None					,     lowerCAmelCase__=None					,     **lowerCAmelCase__					,     ):
					'''simple docstring'''
					if map_location not in [None, "cpu", "on_device"]:
										raise TypeError(
										    '''Unsupported optimizer map location passed, please choose one of `None`, `\'cpu\'`, or `\'on_device\'`'''						)
					if map_location is None:
										lowercase		      =		'''cpu'''
					elif map_location == "on_device":
										lowercase		      =		PartialState().device
					# Model states
					for i, model in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										models[i].load_state_dict(torch.load(lowerCAmelCase__					,     map_location=lowerCAmelCase__						)					,     **lowerCAmelCase__						)
					logger.info('''All model weights loaded successfully'''						)

					# Optimizer states
					for i, opt in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{OPTIMIZER_NAME}.bin' if i == 0 else f'{OPTIMIZER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										lowercase		      =		torch.load(lowerCAmelCase__					,     map_location=lowerCAmelCase__						)
										optimizers[i].load_state_dict(lowerCAmelCase__						)
					logger.info('''All optimizer states loaded successfully'''						)

					# Scheduler states
					for i, scheduler in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{SCHEDULER_NAME}.bin' if i == 0 else f'{SCHEDULER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										scheduler.load_state_dict(torch.load(lowerCAmelCase__						)						)
					logger.info('''All scheduler states loaded successfully'''						)

					# GradScaler state
					if scaler is not None:
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										scaler.load_state_dict(torch.load(lowerCAmelCase__						)						)
										logger.info('''GradScaler state loaded successfully'''						)

					# Random states
					try:
										lowercase		      =		torch.load(os.path.join(lowerCAmelCase__					,     f'{RNG_STATE_NAME}_{process_index}.pkl'						)						)
										random.setstate(states['''random_state''']						)
										np.random.set_state(states['''numpy_random_seed''']						)
										torch.set_rng_state(states['''torch_manual_seed''']						)
										if is_xpu_available():
															torch.xpu.set_rng_state_all(states['''torch_xpu_manual_seed''']						)
										else:
															torch.cuda.set_rng_state_all(states['''torch_cuda_manual_seed''']						)
										if is_tpu_available():
															xm.set_rng_state(states['''xm_seed''']						)
										logger.info('''All random states loaded successfully'''						)
					except Exception:
										logger.info('''Could not load random states'''						)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = 0						):
					'''simple docstring'''
					lowercase		      =		Path(lowerCAmelCase__						) / f'custom_checkpoint_{index}.pkl'
					logger.info(f'Saving the state of {get_pretty_name(lowerCAmelCase__						)} to {save_location}'						)
					torch.save(obj.state_dict()					,     lowerCAmelCase__						)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = 0						):
					'''simple docstring'''
					lowercase		      =		f'{path}/custom_checkpoint_{index}.pkl'
					logger.info(f'Loading the state of {get_pretty_name(lowerCAmelCase__						)} from {load_location}'						)
					obj.load_state_dict(torch.load(lowerCAmelCase__					,     map_location='''cpu'''						)						)




