'''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 __lowerCAmelCase			(							UpperCamelCase__=2    ,  UpperCamelCase__=3    ,  UpperCamelCase__=16    ,  UpperCamelCase__ = 10    ,  UpperCamelCase__ = 2    )     ->   Union[str, Any]:

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

    __lowerCamelCase          =  get_dataset(UpperCamelCase__    )
    __lowerCamelCase          =  get_dataset(UpperCamelCase__    )
    __lowerCamelCase          =  DataLoader(UpperCamelCase__    ,  shuffle=UpperCamelCase__    ,  batch_size=UpperCamelCase__    ,  num_workers=4    )
    __lowerCamelCase          =  DataLoader(UpperCamelCase__    ,  shuffle=UpperCamelCase__    ,  batch_size=UpperCamelCase__    ,  num_workers=4    )
    return (train_dataloader, valid_dataloader)






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__=None    )     ->   Any:
    __lowerCamelCase          =  []
    for epoch in range(UpperCamelCase__    ):
        # Train quickly
        model.train()
        for batch in dataloader:
            __lowerCamelCase     ,  __lowerCamelCase          =  batch
            __lowerCamelCase          =  model(UpperCamelCase__    )
            __lowerCamelCase          =  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    a__				(       nn.Module			):






     def __init__(			self		:		str   ):





         """simple docstring"""



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






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]  ,    a		:		Dict   ):





         """simple docstring"""



         return x * self.a + self.b




class    a__				(       unittest.TestCase			):






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any   ):





         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(42   )
             __lowerCamelCase          =  DummyModel()
             __lowerCamelCase          =  torch.optim.Adam(params=model.parameters()  ,    lr=1e-3   )
             __lowerCamelCase     ,  __lowerCamelCase          =  dummy_dataloaders()
             __lowerCamelCase          =  ProjectConfiguration(total_limit=1  ,    project_dir=a  ,    automatic_checkpoint_naming=a   )
             # Train baseline
             __lowerCamelCase          =  Accelerator(project_config=a   )
             __lowerCamelCase     ,  __lowerCamelCase     ,  __lowerCamelCase     ,  __lowerCamelCase          =  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        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



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

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

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






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple   ):





         """simple docstring"""



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

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

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

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






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any   ):





         """simple docstring"""



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





         """simple docstring"""



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





         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(42   )
             __lowerCamelCase          =  DummyModel()
             __lowerCamelCase          =  ProjectConfiguration(automatic_checkpoint_naming=a  ,    total_limit=2   )
             # Train baseline
             __lowerCamelCase          =  Accelerator(project_dir=a  ,    project_config=a   )
             __lowerCamelCase          =  accelerator.prepare(a   )
             # Save 3 states:
             for _ in range(11   ):
                 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        SCREAMING_SNAKE_CASE__       (			self		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  ['''torchrun''', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__   )]
         execute_subprocess_async(a  ,    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.99)
  __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 torch
from torch import nn

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin




class    a__				(       UpperCAmelCase__							,       UpperCAmelCase__			):






     @register_to_config
     def __init__(			self		:		Any  ,    *,
         a		:		int = 4  ,    a		:		int = 7_68  ,    a		:		int  ,    a		:		Optional[int]  ,    ):





         """simple docstring"""



         super().__init__()

         __lowerCamelCase          =  nn.Parameter(torch.zeros(a   )   )

         # parameters for additional clip time embeddings
         __lowerCamelCase          =  nn.Linear(a  ,    a   )
         __lowerCamelCase          =  nn.Linear(a  ,    a   )

         # parameters for encoder hidden states
         __lowerCamelCase          =  clip_extra_context_tokens
         __lowerCamelCase          =  nn.Linear(
             a  ,    self.clip_extra_context_tokens * cross_attention_dim   )
         __lowerCamelCase          =  nn.Linear(a  ,    a   )
         __lowerCamelCase          =  nn.LayerNorm(a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		int  ,    *, a		:		Union[str, Any]  ,    a		:		Any  ,    a		:		str  ,    a		:		Any   ):





         """simple docstring"""



         if do_classifier_free_guidance:
             # Add the classifier free guidance embeddings to the image embeddings
             __lowerCamelCase          =  image_embeddings.shape[0]
             __lowerCamelCase          =  self.learned_classifier_free_guidance_embeddings.unsqueeze(0   )
             __lowerCamelCase          =  classifier_free_guidance_embeddings.expand(
                 a  ,    -1   )
             __lowerCamelCase          =  torch.cat([classifier_free_guidance_embeddings, image_embeddings]  ,    dim=0   )

         # The image embeddings batch size and the text embeddings batch size are equal
         assert image_embeddings.shape[0] == prompt_embeds.shape[0]

         __lowerCamelCase          =  prompt_embeds.shape[0]

         # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and
         # adding CLIP embeddings to the existing timestep embedding, ...
         __lowerCamelCase          =  self.embedding_proj(a   )
         __lowerCamelCase          =  self.clip_image_embeddings_project_to_time_embeddings(a   )
         __lowerCamelCase          =  time_projected_image_embeddings + time_projected_prompt_embeds

         # ... and by projecting CLIP embeddings into four
         # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder"
         __lowerCamelCase          =  self.clip_extra_context_tokens_proj(a   )
         __lowerCamelCase          =  clip_extra_context_tokens.reshape(a  ,    -1  ,    self.clip_extra_context_tokens   )
         __lowerCamelCase          =  clip_extra_context_tokens.permute(0  ,    2  ,    1   )

         __lowerCamelCase          =  self.encoder_hidden_states_proj(a   )
         __lowerCamelCase          =  self.text_encoder_hidden_states_norm(a   )
         __lowerCamelCase          =  torch.cat([clip_extra_context_tokens, text_encoder_hidden_states]  ,    dim=1   )

         return text_encoder_hidden_states, additive_clip_time_embeddings
