





import argparse
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType
from accelerate.local_sgd import LocalSGD


########################################################################
# This is a fully working simple example to use Accelerate
# with LocalSGD, which is a method to synchronize model
# parameters every K batches. It is different, but complementary
# to gradient accumulation.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


lowercase_		:					Union[str, Any]      						=    16
lowercase_		:					Union[str, Any]      						=    32

def    A__(		__lowerCAmelCase						,      __lowerCAmelCase = 16			):
				_snake_case			:      Dict	    = AutoTokenizer.from_pretrained('bert-base-cased'			)
				_snake_case			:      Optional[int]	    = load_dataset('glue'						,      'mrpc'			)

				def tokenize_function(__lowerCAmelCase			):
								# max_length=None => use the model max length (it's actually the default)
								_snake_case			:      Optional[Any]	    = tokenizer(examples['sentence1']						,      examples['sentence2']						,      truncation=_lowerCAmelCase						,      max_length=_lowerCAmelCase			)
								return outputs

				# Apply the method we just defined to all the examples in all the splits of the dataset
				# starting with the main process first:
				with accelerator.main_process_first():
								_snake_case			:      Optional[Any]	    = datasets.map(
								    _lowerCAmelCase						,      batched=_lowerCAmelCase						,      remove_columns=['idx', 'sentence1', 'sentence2']						,      )

				# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
				# transformers library
				_snake_case			:      int	    = tokenized_datasets.rename_column('label'						,      'labels'			)

				def collate_fn(__lowerCAmelCase			):
								# On TPU it's best to pad everything to the same length or training will be very slow.
								_snake_case			:      Union[str, Any]	    = 1_28 if accelerator.distributed_type == DistributedType.TPU else None
								# When using mixed precision we want round multiples of 8/16
								if accelerator.mixed_precision == "fp8":
												_snake_case			:      Optional[int]	    = 16
								elif accelerator.mixed_precision != "no":
												_snake_case			:      Optional[int]	    = 8
								else:
												_snake_case			:      List[str]	    = None

								return tokenizer.pad(
								    _lowerCAmelCase						,      padding='longest'						,      max_length=_lowerCAmelCase						,      pad_to_multiple_of=_lowerCAmelCase						,      return_tensors='pt'						,      )

				# Instantiate dataloaders.
				_snake_case			:      Union[str, Any]	    = DataLoader(
				    tokenized_datasets['train']						,      shuffle=_lowerCAmelCase						,      collate_fn=_lowerCAmelCase						,      batch_size=_lowerCAmelCase			)
				_snake_case			:      Any	    = DataLoader(
				    tokenized_datasets['validation']						,      shuffle=_lowerCAmelCase						,      collate_fn=_lowerCAmelCase						,      batch_size=_lowerCAmelCase			)

				return train_dataloader, eval_dataloader


# For testing only
if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1":
		from accelerate.test_utils.training import mocked_dataloaders

		lowercase_		:					List[str]      						=    mocked_dataloaders  # noqa: F811

def    A__(		__lowerCAmelCase						,      __lowerCAmelCase			):
				# For testing only
				if os.environ.get('TESTING_MOCKED_DATALOADERS'						,      _lowerCAmelCase			) == "1":
								_snake_case			:      Tuple	    = 2
				# New Code #
				_snake_case			:      Any	    = int(args.gradient_accumulation_steps			)
				_snake_case			:      Optional[Any]	    = int(args.local_sgd_steps			)
				# Initialize accelerator
				_snake_case			:      List[str]	    = Accelerator(
				    cpu=args.cpu						,      mixed_precision=args.mixed_precision						,      gradient_accumulation_steps=_lowerCAmelCase			)
				if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]:
								raise NotImplementedError('LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)'			)
				# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
				_snake_case			:      Any	    = config["lr"]
				_snake_case			:      str	    = int(config['num_epochs']			)
				_snake_case			:      str	    = int(config['seed']			)
				_snake_case			:      Tuple	    = int(config['batch_size']			)

				_snake_case			:      str	    = evaluate.load('glue'						,      'mrpc'			)

				set_seed(_lowerCAmelCase			)
				_snake_case			:      str	    = get_dataloaders(_lowerCAmelCase						,      _lowerCAmelCase			)
				# Instantiate the model (we build the model here so that the seed also control new weights initialization)
				_snake_case			:      Optional[int]	    = AutoModelForSequenceClassification.from_pretrained('bert-base-cased'						,      return_dict=_lowerCAmelCase			)

				# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
				# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
				# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
				_snake_case			:      Dict	    = model.to(accelerator.device			)

				# Instantiate optimizer
				_snake_case			:      Optional[Any]	    = AdamW(params=model.parameters()						,      lr=_lowerCAmelCase			)

				# Instantiate scheduler
				_snake_case			:      List[Any]	    = get_linear_schedule_with_warmup(
				    optimizer=_lowerCAmelCase						,      num_warmup_steps=1_00						,      num_training_steps=(len(_lowerCAmelCase			) * num_epochs)						,      )

				# Prepare everything
				# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
				# prepare method.
				_snake_case			:      Any	    = accelerator.prepare(
				    _lowerCAmelCase						,      _lowerCAmelCase						,      _lowerCAmelCase						,      _lowerCAmelCase						,      _lowerCAmelCase			)

				# Now we train the model
				for epoch in range(_lowerCAmelCase			):
								model.train()
								with LocalSGD(
								    accelerator=_lowerCAmelCase						,      model=_lowerCAmelCase						,      local_sgd_steps=_lowerCAmelCase						,      enabled=local_sgd_steps is not None			) as local_sgd:
												for step, batch in enumerate(_lowerCAmelCase			):
																# We could avoid this line since we set the accelerator with `device_placement=True`.
																batch.to(accelerator.device			)
																# New code #
																# We use the new `accumulate` context manager to perform gradient accumulation
																# We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
																with accelerator.accumulate(_lowerCAmelCase			):
																				_snake_case			:      List[str]	    = model(**_lowerCAmelCase			)
																				_snake_case			:      Tuple	    = output.loss
																				accelerator.backward(_lowerCAmelCase			)
																				optimizer.step()
																				lr_scheduler.step()
																				optimizer.zero_grad()
																				# LocalSGD-specific line
																				local_sgd.step()

								model.eval()
								for step, batch in enumerate(_lowerCAmelCase			):
												# We could avoid this line since we set the accelerator with `device_placement=True`.
												batch.to(accelerator.device			)
												with torch.no_grad():
																_snake_case			:      str	    = model(**_lowerCAmelCase			)
												_snake_case			:      List[str]	    = outputs.logits.argmax(dim=-1			)
												_snake_case			:      Any	    = accelerator.gather_for_metrics((predictions, batch['labels'])			)
												metric.add_batch(
												    predictions=_lowerCAmelCase						,      references=_lowerCAmelCase						,      )

								_snake_case			:      int	    = metric.compute()
								# Use accelerator.print to print only on the main process.
								accelerator.print(F'''epoch {epoch}:'''						,      _lowerCAmelCase			)

def    A__(		):
				_snake_case			:      List[str]	    = argparse.ArgumentParser(description='Simple example of training script.'			)
				parser.add_argument(
				    '--mixed_precision'						,      type=_lowerCAmelCase						,      default=_lowerCAmelCase						,      choices=['no', 'fp16', 'bf16', 'fp8']						,      help='Whether to use mixed precision. Choose'
				    'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'
				    'and an Nvidia Ampere GPU.'						,      )
				# New Code #
				parser.add_argument(
				    '--gradient_accumulation_steps'						,      type=_lowerCAmelCase						,      default=1						,      help='The number of minibatches to be ran before gradients are accumulated.'						,      )
				parser.add_argument(
				    '--local_sgd_steps'						,      type=_lowerCAmelCase						,      default=8						,      help='Number of local SGD steps or None to disable local SGD'			)
				parser.add_argument('--cpu'						,      action='store_true'						,      help='If passed, will train on the CPU.'			)
				_snake_case			:      List[Any]	    = parser.parse_args()
				_snake_case			:      List[str]	    = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
				training_function(_lowerCAmelCase						,      _lowerCAmelCase			)


if __name__ == "__main__":
		main()













import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()


class        __magic_name__	(				unittest.TestCase				):





     """simple docstring"""



     @property
     def     SCREAMING_SNAKE_CASE		(				self							:List[str]	):





        '''simple docstring'''




        torch.manual_seed(0	)
        A_       :					Optional[Any]        =      UNetaDModel(
            block_out_channels=(32, 64)      ,   layers_per_block=2      ,   sample_size=32      ,   in_channels=3      ,   out_channels=3      ,   down_block_types=("DownBlock2D", "AttnDownBlock2D")      ,   up_block_types=("AttnUpBlock2D", "UpBlock2D")      ,   )
        return model



     @property
     def     SCREAMING_SNAKE_CASE		(				self							:int	):





        '''simple docstring'''




        torch.manual_seed(0	)
        A_       :					Any        =      VQModel(
            block_out_channels=[32, 64]      ,   in_channels=3      ,   out_channels=3      ,   down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]      ,   up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]      ,   latent_channels=3      ,   )
        return model



     @property
     def     SCREAMING_SNAKE_CASE		(				self							:Any	):





        '''simple docstring'''




        torch.manual_seed(0	)
        A_       :					int        =      CLIPTextConfig(
            bos_token_id=0      ,   eos_token_id=2      ,   hidden_size=32      ,   intermediate_size=37      ,   layer_norm_eps=1e-05      ,   num_attention_heads=4      ,   num_hidden_layers=5      ,   pad_token_id=1      ,   vocab_size=1_000      ,   )
        return CLIPTextModel(snake_case	)





     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        A_       :					Dict        =      self.dummy_uncond_unet
        A_       :					Any        =      DDIMScheduler()
        A_       :					List[str]        =      self.dummy_vq_model

        A_       :					Union[str, Any]        =      LDMPipeline(unet=snake_case      ,   vqvae=snake_case      ,   scheduler=snake_case	)
        ldm.to(snake_case	)
        ldm.set_progress_bar_config(disable=snake_case	)

        A_       :					Any        =      torch.manual_seed(0	)
        A_       :					Optional[Any]        =      ldm(generator=snake_case      ,   num_inference_steps=2      ,   output_type="numpy"	).images

        A_       :					Dict        =      torch.manual_seed(0	)
        A_       :					Any        =      ldm(generator=snake_case      ,   num_inference_steps=2      ,   output_type="numpy"      ,   return_dict=snake_case	)[0]

        A_       :					int        =      image[0, -3:, -3:, -1]
        A_       :					Any        =      image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        A_       :					str        =      np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172]	)
        A_       :					List[str]        =      1e-2 if torch_device != "mps" else 3e-2

        assert np.abs(image_slice.flatten() - expected_slice	).max() < tolerance
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice	).max() < tolerance




@slow
@require_torch
class        __magic_name__	(				unittest.TestCase				):





     """simple docstring"""



     def     SCREAMING_SNAKE_CASE		(				self							:Tuple	):





        '''simple docstring'''




        A_       :					int        =      LDMPipeline.from_pretrained("CompVis/ldm-celebahq-256"	)
        ldm.to(snake_case	)
        ldm.set_progress_bar_config(disable=snake_case	)

        A_       :					int        =      torch.manual_seed(0	)
        A_       :					List[str]        =      ldm(generator=snake_case      ,   num_inference_steps=5      ,   output_type="numpy"	).images

        A_       :					Tuple        =      image[0, -3:, -3:, -1]

        assert image.shape == (1, 256, 256, 3)
        A_       :					Any        =      np.array([0.4399, 0.44975, 0.46825, 0.474, 0.4359, 0.4581, 0.45095, 0.4341, 0.4447]	)
        A_       :					List[Any]        =      1e-2 if torch_device != "mps" else 3e-2

        assert np.abs(image_slice.flatten() - expected_slice	).max() < tolerance
