



import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
						import jax.numpy as jnp

						from transformers.models.distilbert.modeling_flax_distilbert import (
						    FlaxDistilBertForMaskedLM,
						    FlaxDistilBertForMultipleChoice,
						    FlaxDistilBertForQuestionAnswering,
						    FlaxDistilBertForSequenceClassification,
						    FlaxDistilBertForTokenClassification,
						    FlaxDistilBertModel,
						)



class   UpperCAmelCase_    (       unittest.TestCase):







							def __init__(   self,			__a,			__a=13,			__a=7,			__a=True,			__a=True,			__a=True,			__a=True,			__a=99,			__a=32,			__a=5,			__a=4,			__a=37,			__a="gelu",			__a=0.1,			__a=0.1,			__a=512,			__a=16,			__a=2,			__a=0.02,			__a=4,			):

														'''simple docstring'''

														_lowerCAmelCase     :							List[Any]    =    parent
														_lowerCAmelCase     :							Tuple    =    batch_size
														_lowerCAmelCase     :							Any    =    seq_length
														_lowerCAmelCase     :							int    =    is_training
														_lowerCAmelCase     :							List[str]    =    use_attention_mask
														_lowerCAmelCase     :							str    =    use_token_type_ids
														_lowerCAmelCase     :							List[str]    =    use_labels
														_lowerCAmelCase     :							Dict    =    vocab_size
														_lowerCAmelCase     :							Any    =    hidden_size
														_lowerCAmelCase     :							Optional[int]    =    num_hidden_layers
														_lowerCAmelCase     :							Optional[int]    =    num_attention_heads
														_lowerCAmelCase     :							Tuple    =    intermediate_size
														_lowerCAmelCase     :							Optional[int]    =    hidden_act
														_lowerCAmelCase     :							int    =    hidden_dropout_prob
														_lowerCAmelCase     :							List[Any]    =    attention_probs_dropout_prob
														_lowerCAmelCase     :							int    =    max_position_embeddings
														_lowerCAmelCase     :							Optional[Any]    =    type_vocab_size
														_lowerCAmelCase     :							Tuple    =    type_sequence_label_size
														_lowerCAmelCase     :							List[str]    =    initializer_range
														_lowerCAmelCase     :							Dict    =    num_choices







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    ids_tensor([self.batch_size, self.seq_length],			self.vocab_size)

														_lowerCAmelCase     :							str    =    None
														if self.use_attention_mask:
																					_lowerCAmelCase     :							Optional[Any]    =    random_attention_mask([self.batch_size, self.seq_length])

														_lowerCAmelCase     :							Union[str, Any]    =    DistilBertConfig(
														    vocab_size=self.vocab_size,			dim=self.hidden_size,			n_layers=self.num_hidden_layers,			n_heads=self.num_attention_heads,			hidden_dim=self.intermediate_size,			hidden_act=self.hidden_act,			dropout=self.hidden_dropout_prob,			attention_dropout=self.attention_probs_dropout_prob,			max_position_embeddings=self.max_position_embeddings,			initializer_range=self.initializer_range,			tie_weights_=__a,			)

														return config, input_ids, attention_mask







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							int    =    self.prepare_config_and_inputs()
														_lowerCAmelCase   ,    _lowerCAmelCase   ,    _lowerCAmelCase     :							str    =    config_and_inputs
														_lowerCAmelCase     :							Tuple    =    {"input_ids": input_ids, "attention_mask": attention_mask}
														return config, inputs_dict



@require_flax
class   UpperCAmelCase_    (       a   ,					unittest.TestCase):
							lowerCamelCase__   			=		(
							    (
							        FlaxDistilBertModel,
							        FlaxDistilBertForMaskedLM,
							        FlaxDistilBertForMultipleChoice,
							        FlaxDistilBertForQuestionAnswering,
							        FlaxDistilBertForSequenceClassification,
							        FlaxDistilBertForTokenClassification,
							        FlaxDistilBertForQuestionAnswering,
							    )
							    if is_flax_available()
							    else ()
							)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    FlaxDistilBertModelTester(self)







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														for model_class_name in self.all_model_classes:
																					_lowerCAmelCase     :							List[Any]    =    model_class_name.from_pretrained("distilbert-base-uncased")
																					_lowerCAmelCase     :							str    =    model(np.ones((1, 1)))
																					self.assertIsNotNone(__a)



@require_flax
class   UpperCAmelCase_    (       unittest.TestCase):







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							List[str]    =    FlaxDistilBertModel.from_pretrained("distilbert-base-uncased")
														_lowerCAmelCase     :							str    =    np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
														_lowerCAmelCase     :							Dict    =    np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
														_lowerCAmelCase     :							Dict    =    model(__a,			attention_mask=__a)[0]
														_lowerCAmelCase     :							List[Any]    =    (1, 11, 768)
														self.assertEqual(output.shape,			__a)
														_lowerCAmelCase     :							Optional[Any]    =    np.array([[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]])

														self.assertTrue(jnp.allclose(output[:, 1:4, 1:4],			__a,			atol=1E-4))





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


_lowerCAmelCase    :Tuple     =					logging.getLogger(__name__)





def  lowerCamelCase_						(UpperCamelCase__		:		List[Any]=2     ,       UpperCamelCase__		:		List[Any]=3     ,       UpperCamelCase__		:		List[Any]=16     ,       UpperCamelCase__		:		int = 10     ,       UpperCamelCase__		:		int = 2							):

    def get_dataset(UpperCamelCase__		:		List[str]							):
        _UpperCAmelCase							:  Optional[Any]											=    torch.randn(batch_size * n_batches     ,       1							)
        return TensorDataset(UpperCamelCase__     ,       a * x + b + 0.1 * torch.randn(batch_size * n_batches     ,       1							)							)

    _UpperCAmelCase							:  Optional[Any]											=    get_dataset(UpperCamelCase__							)
    _UpperCAmelCase							:  Optional[Any]											=    get_dataset(UpperCamelCase__							)
    _UpperCAmelCase							:  List[str]											=    DataLoader(UpperCamelCase__     ,       shuffle=UpperCamelCase__     ,       batch_size=UpperCamelCase__     ,       num_workers=4							)
    _UpperCAmelCase							:  List[str]											=    DataLoader(UpperCamelCase__     ,       shuffle=UpperCamelCase__     ,       batch_size=UpperCamelCase__     ,       num_workers=4							)
    return (train_dataloader, valid_dataloader)





def  lowerCamelCase_						(UpperCamelCase__		:		Optional[int]     ,       UpperCamelCase__		:		List[Any]     ,       UpperCamelCase__		:		int     ,       UpperCamelCase__		:		Any     ,       UpperCamelCase__		:		Optional[Any]     ,       UpperCamelCase__		:		Tuple=None							):
    _UpperCAmelCase							:  Tuple											=    []
    for epoch in range(UpperCamelCase__							):
        # Train quickly
        model.train()
        for batch in dataloader:
            _UpperCAmelCase							,				_UpperCAmelCase							:  Dict											=    batch
            _UpperCAmelCase							:  int											=    model(UpperCamelCase__							)
            _UpperCAmelCase							:  Dict											=    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 							_UpperCAmelCase							( nn.Module      ):





     '''simple docstring'''



     def __init__(					self		)							->					List[Any]:
         super().__init__()
         _UpperCAmelCase							:  List[Any]											=    nn.Parameter(torch.randn(1		)		)
         _UpperCAmelCase							:  int											=    nn.Parameter(torch.randn(1		)		)





     def  __lowerCAmelCase	(					self       ,	A		)							->					Tuple:
         return x * self.a + self.b



class 							_UpperCAmelCase							( unittest.TestCase      ):





     '''simple docstring'''



     def  __lowerCAmelCase	(					self		)							->					Any:
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2		)
             _UpperCAmelCase							:  int											=    DummyModel()
             _UpperCAmelCase							:  str											=    torch.optim.Adam(params=model.parameters()       ,	lr=1E-3		)
             _UpperCAmelCase							,				_UpperCAmelCase							:  List[Any]											=    dummy_dataloaders()
             _UpperCAmelCase							:  Any											=    ProjectConfiguration(total_limit=1       ,	project_dir=A       ,	automatic_checkpoint_naming=A		)
             # Train baseline
             _UpperCAmelCase							:  Union[str, Any]											=    Accelerator(project_config=A		)
             _UpperCAmelCase							,				_UpperCAmelCase							,				_UpperCAmelCase							,				_UpperCAmelCase							:  int											=    accelerator.prepare(
                 A       ,	A       ,	A       ,	A		)
             # 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]:
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2		)
             _UpperCAmelCase							:  Optional[Any]											=    DummyModel()
             _UpperCAmelCase							:  int											=    torch.optim.Adam(params=model.parameters()       ,	lr=1E-3		)
             _UpperCAmelCase							,				_UpperCAmelCase							:  Dict											=    dummy_dataloaders()
             # Train baseline
             _UpperCAmelCase							:  Optional[int]											=    Accelerator()
             _UpperCAmelCase							,				_UpperCAmelCase							,				_UpperCAmelCase							,				_UpperCAmelCase							:  List[str]											=    accelerator.prepare(
                 A       ,	A       ,	A       ,	A		)
             # Save initial
             _UpperCAmelCase							:  Union[str, Any]											=    os.path.join(A       ,	'''initial'''		)
             accelerator.save_state(A		)
             ((_UpperCAmelCase)							,				(_UpperCAmelCase))							:  Optional[Any]											=    model.a.item(), model.b.item()
             _UpperCAmelCase							:  str											=    optimizer.state_dict()
             _UpperCAmelCase							:  Tuple											=    train(3       ,	A       ,	A       ,	A       ,	A		)
             ((_UpperCAmelCase)							,				(_UpperCAmelCase))							:  Dict											=    model.a.item(), model.b.item()
             _UpperCAmelCase							:  List[Any]											=    optimizer.state_dict()

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

             _UpperCAmelCase							:  Union[str, Any]											=    train(2       ,	A       ,	A       ,	A       ,	A		)
             # Save everything
             _UpperCAmelCase							:  List[str]											=    os.path.join(A       ,	'''checkpoint'''		)
             accelerator.save_state(A		)

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





     def  __lowerCAmelCase	(					self		)							->					int:
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2		)
             _UpperCAmelCase							:  List[Any]											=    DummyModel()
             _UpperCAmelCase							:  List[str]											=    torch.optim.Adam(params=model.parameters()       ,	lr=1E-3		)
             _UpperCAmelCase							,				_UpperCAmelCase							:  List[Any]											=    dummy_dataloaders()
             _UpperCAmelCase							:  List[str]											=    ProjectConfiguration(automatic_checkpoint_naming=A		)

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

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

             _UpperCAmelCase							:  List[str]											=    train(2       ,	A       ,	A       ,	A       ,	A		)
             # Save everything
             accelerator.save_state()

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





     def  __lowerCAmelCase	(					self		)							->					Dict:
         _UpperCAmelCase							:  List[Any]											=    torch.tensor([1, 2, 3]		)
         _UpperCAmelCase							:  List[str]											=    torch.tensor([2, 3, 4]		)
         _UpperCAmelCase							:  Optional[int]											=    DummyModel()
         _UpperCAmelCase							:  Dict											=    torch.optim.Adam(net.parameters()		)
         _UpperCAmelCase							:  Optional[int]											=    Accelerator()
         with self.assertRaises(A		) as ve:
             accelerator.register_for_checkpointing(A       ,	A       ,	A       ,	A		)
         _UpperCAmelCase							:  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		)							->					Tuple:
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2		)
             _UpperCAmelCase							:  Tuple											=    DummyModel()
             _UpperCAmelCase							:  List[Any]											=    torch.optim.Adam(params=model.parameters()       ,	lr=1E-3		)
             _UpperCAmelCase							:  Optional[int]											=    torch.optim.lr_scheduler.StepLR(A       ,	step_size=1       ,	gamma=0.99		)
             _UpperCAmelCase							,				_UpperCAmelCase							:  str											=    dummy_dataloaders()
             _UpperCAmelCase							:  List[str]											=    ProjectConfiguration(automatic_checkpoint_naming=A		)
             # Train baseline
             _UpperCAmelCase							:  int											=    Accelerator(project_dir=A       ,	project_config=A		)
             _UpperCAmelCase							,				_UpperCAmelCase							,				_UpperCAmelCase							,				_UpperCAmelCase							,				_UpperCAmelCase							:  str											=    accelerator.prepare(
                 A       ,	A       ,	A       ,	A       ,	A		)
             # Save initial
             accelerator.save_state()
             _UpperCAmelCase							:  List[str]											=    scheduler.state_dict()
             train(3       ,	A       ,	A       ,	A       ,	A       ,	A		)
             self.assertNotEqual(A       ,	scheduler.state_dict()		)

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





     def  __lowerCAmelCase	(					self		)							->					Optional[Any]:
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2		)
             _UpperCAmelCase							:  int											=    DummyModel()
             _UpperCAmelCase							:  str											=    ProjectConfiguration(automatic_checkpoint_naming=A       ,	total_limit=2		)
             # Train baseline
             _UpperCAmelCase							:  Union[str, Any]											=    Accelerator(project_dir=A       ,	project_config=A		)
             _UpperCAmelCase							:  Optional[Any]											=    accelerator.prepare(A		)
             # Save 3 states:
             for _ in range(1_1		):
                 accelerator.save_state()
             self.assertTrue(not os.path.exists(os.path.join(A       ,	'''checkpoints'''       ,	'''checkpoint_0'''		)		)		)
             self.assertTrue(os.path.exists(os.path.join(A       ,	'''checkpoints'''       ,	'''checkpoint_9'''		)		)		)
             self.assertTrue(os.path.exists(os.path.join(A       ,	'''checkpoints'''       ,	'''checkpoint_10'''		)		)		)





     @require_cuda
     def  __lowerCAmelCase	(					self		)							->					Dict:
         _UpperCAmelCase							:  str											=    ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__		)]
         execute_subprocess_async(A       ,	env=os.environ.copy()		)


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


