

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


UpperCamelCase__		 =     16
UpperCamelCase__		 =     32







def 						lowerCamelCase__      ( __A    :Accelerator	,__A    :int = 1_6		):


       """simple docstring"""




       __snake_case       	=							AutoTokenizer.from_pretrained("""bert-base-cased"""		)
       __snake_case       	=							load_dataset("""glue"""	,"""mrpc"""		)

       def tokenize_function(__A    :Any		):
              # max_length=None => use the model max length (it's actually the default)
              __snake_case       	=							tokenizer(examples["""sentence1"""]	,examples["""sentence2"""]	,truncation=__A	,max_length=__A		)
              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       	=							datasets.map(
                  __A	,batched=__A	,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       	=							tokenized_datasets.rename_column("""label"""	,"""labels"""		)

       def collate_fn(__A    :int		):
              # On TPU it's best to pad everything to the same length or training will be very slow.
              __snake_case       	=							1_2_8 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       	=							1_6
              elif accelerator.mixed_precision != "no":
                     __snake_case       	=							8
              else:
                     __snake_case       	=							None

              return tokenizer.pad(
                  __A	,padding="""longest"""	,max_length=__A	,pad_to_multiple_of=__A	,return_tensors="""pt"""	,)

       # Instantiate dataloaders.
       __snake_case       	=							DataLoader(
           tokenized_datasets["""train"""]	,shuffle=__A	,collate_fn=__A	,batch_size=__A		)
       __snake_case       	=							DataLoader(
           tokenized_datasets["""validation"""]	,shuffle=__A	,collate_fn=__A	,batch_size=__A		)

       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

    UpperCamelCase__		 =     mocked_dataloaders  # noqa: F811







def 						lowerCamelCase__      ( __A    :Union[str, Any]	,__A    :Any		):


       """simple docstring"""




       if os.environ.get("""TESTING_MOCKED_DATALOADERS"""	,__A		) == "1":
              __snake_case       	=							2
       # New Code #
       __snake_case       	=							int(args.gradient_accumulation_steps		)
       __snake_case       	=							int(args.local_sgd_steps		)
       # Initialize accelerator
       __snake_case       	=							Accelerator(
           cpu=args.cpu	,mixed_precision=args.mixed_precision	,gradient_accumulation_steps=__A		)
       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       	=							config["""lr"""]
       __snake_case       	=							int(config["""num_epochs"""]		)
       __snake_case       	=							int(config["""seed"""]		)
       __snake_case       	=							int(config["""batch_size"""]		)

       __snake_case       	=							evaluate.load("""glue"""	,"""mrpc"""		)

       set_seed(__A		)
       __snake_case	,    __snake_case       	=							get_dataloaders(__A	,__A		)
       # Instantiate the model (we build the model here so that the seed also control new weights initialization)
       __snake_case       	=							AutoModelForSequenceClassification.from_pretrained("""bert-base-cased"""	,return_dict=__A		)

       # 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       	=							model.to(accelerator.device		)

       # Instantiate optimizer
       __snake_case       	=							AdamW(params=model.parameters()	,lr=__A		)

       # Instantiate scheduler
       __snake_case       	=							get_linear_schedule_with_warmup(
           optimizer=__A	,num_warmup_steps=1_0_0	,num_training_steps=(len(__A		) * 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	,    __snake_case	,    __snake_case	,    __snake_case	,    __snake_case       	=							accelerator.prepare(
           __A	,__A	,__A	,__A	,__A		)

       # Now we train the model
       for epoch in range(__A		):
              model.train()
              with LocalSGD(
                  accelerator=__A	,model=__A	,local_sgd_steps=__A	,enabled=local_sgd_steps is not None		) as local_sgd:
                     for step, batch in enumerate(__A		):
                            # 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(__A		):
                                   __snake_case       	=							model(**__A		)
                                   __snake_case       	=							output.loss
                                   accelerator.backward(__A		)
                                   optimizer.step()
                                   lr_scheduler.step()
                                   optimizer.zero_grad()
                                   # LocalSGD-specific line
                                   local_sgd.step()

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

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







def 						lowerCamelCase__      ( ):


       """simple docstring"""




       __snake_case       	=							argparse.ArgumentParser(description="""Simple example of training script."""		)
       parser.add_argument(
           """--mixed_precision"""	,type=__A	,default=__A	,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=__A	,default=1	,help="""The number of minibatches to be ran before gradients are accumulated."""	,)
       parser.add_argument(
           """--local_sgd_steps"""	,type=__A	,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       	=							parser.parse_args()
       __snake_case       	=							{"""lr""": 2e-5, """num_epochs""": 3, """seed""": 4_2, """batch_size""": 1_6}
       training_function(__A	,__A		)


if __name__ == "__main__":
    main()




import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
    from PIL import Image

    from transformers import CLIPImageProcessor, CLIPProcessor

@require_vision
class     __snake_case    (				unittest.TestCase  ):
       """simple docstring"""







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






              """simple docstring"""


              __snake_case       	=							tempfile.mkdtemp()

              # fmt: off
              __snake_case       	=							["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""]
              # fmt: on
              __snake_case       	=							dict(zip(_UpperCamelCase      , range(len(_UpperCamelCase   )   )   )   )
              __snake_case       	=							["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""]
              __snake_case       	=							{"""unk_token""": """<unk>"""}

              __snake_case       	=							os.path.join(self.tmpdirname      , VOCAB_FILES_NAMES["""vocab_file"""]   )
              __snake_case       	=							os.path.join(self.tmpdirname      , VOCAB_FILES_NAMES["""merges_file"""]   )
              with open(self.vocab_file      , """w"""      , encoding="""utf-8"""   ) as fp:
                     fp.write(json.dumps(_UpperCamelCase   ) + """\n"""   )
              with open(self.merges_file      , """w"""      , encoding="""utf-8"""   ) as fp:
                     fp.write("""\n""".join(_UpperCamelCase   )   )

              __snake_case       	=							{
                  """do_resize""": True,
                  """size""": 20,
                  """do_center_crop""": True,
                  """crop_size""": 18,
                  """do_normalize""": True,
                  """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073],
                  """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711],
              }
              __snake_case       	=							os.path.join(self.tmpdirname      , _UpperCamelCase   )
              with open(self.image_processor_file      , """w"""      , encoding="""utf-8"""   ) as fp:
                     json.dump(_UpperCamelCase      , _UpperCamelCase   )


       def 			a		(		self      , **_UpperCamelCase   )      ->							Optional[int]:






              """simple docstring"""


              return CLIPTokenizer.from_pretrained(self.tmpdirname      , **_UpperCamelCase   )


       def 			a		(		self      , **_UpperCamelCase   )      ->							Union[str, Any]:






              """simple docstring"""


              return CLIPTokenizerFast.from_pretrained(self.tmpdirname      , **_UpperCamelCase   )


       def 			a		(		self      , **_UpperCamelCase   )      ->							List[str]:






              """simple docstring"""


              return CLIPImageProcessor.from_pretrained(self.tmpdirname      , **_UpperCamelCase   )


       def 			a		(		self   )      ->							int:






              """simple docstring"""


              shutil.rmtree(self.tmpdirname   )


       def 			a		(		self   )      ->							Optional[Any]:






              """simple docstring"""


              __snake_case       	=							[np.random.randint(2_55      , size=(3, 30, 4_00)      , dtype=np.uinta   )]

              __snake_case       	=							[Image.fromarray(np.moveaxis(_UpperCamelCase      , 0      , -1   )   ) for x in image_inputs]

              return image_inputs


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






              """simple docstring"""


              __snake_case       	=							self.get_tokenizer()
              __snake_case       	=							self.get_rust_tokenizer()
              __snake_case       	=							self.get_image_processor()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )
              processor_slow.save_pretrained(self.tmpdirname   )
              __snake_case       	=							CLIPProcessor.from_pretrained(self.tmpdirname      , use_fast=_UpperCamelCase   )

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )
              processor_fast.save_pretrained(self.tmpdirname   )
              __snake_case       	=							CLIPProcessor.from_pretrained(self.tmpdirname   )

              self.assertEqual(processor_slow.tokenizer.get_vocab()      , tokenizer_slow.get_vocab()   )
              self.assertEqual(processor_fast.tokenizer.get_vocab()      , tokenizer_fast.get_vocab()   )
              self.assertEqual(tokenizer_slow.get_vocab()      , tokenizer_fast.get_vocab()   )
              self.assertIsInstance(processor_slow.tokenizer      , _UpperCamelCase   )
              self.assertIsInstance(processor_fast.tokenizer      , _UpperCamelCase   )

              self.assertEqual(processor_slow.image_processor.to_json_string()      , image_processor.to_json_string()   )
              self.assertEqual(processor_fast.image_processor.to_json_string()      , image_processor.to_json_string()   )
              self.assertIsInstance(processor_slow.image_processor      , _UpperCamelCase   )
              self.assertIsInstance(processor_fast.image_processor      , _UpperCamelCase   )


       def 			a		(		self   )      ->							List[str]:






              """simple docstring"""


              __snake_case       	=							CLIPProcessor(tokenizer=self.get_tokenizer()      , image_processor=self.get_image_processor()   )
              processor.save_pretrained(self.tmpdirname   )

              __snake_case       	=							self.get_tokenizer(bos_token="""(BOS)"""      , eos_token="""(EOS)"""   )
              __snake_case       	=							self.get_image_processor(do_normalize=_UpperCamelCase      , padding_value=1.0   )

              __snake_case       	=							CLIPProcessor.from_pretrained(
                  self.tmpdirname      , bos_token="""(BOS)"""      , eos_token="""(EOS)"""      , do_normalize=_UpperCamelCase      , padding_value=1.0   )

              self.assertEqual(processor.tokenizer.get_vocab()      , tokenizer_add_kwargs.get_vocab()   )
              self.assertIsInstance(processor.tokenizer      , _UpperCamelCase   )

              self.assertEqual(processor.image_processor.to_json_string()      , image_processor_add_kwargs.to_json_string()   )
              self.assertIsInstance(processor.image_processor      , _UpperCamelCase   )


       def 			a		(		self   )      ->							Any:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							self.prepare_image_inputs()

              __snake_case       	=							image_processor(_UpperCamelCase      , return_tensors="""np"""   )
              __snake_case       	=							processor(images=_UpperCamelCase      , return_tensors="""np"""   )

              for key in input_image_proc.keys():
                     self.assertAlmostEqual(input_image_proc[key].sum()      , input_processor[key].sum()      , delta=1E-2   )


       def 			a		(		self   )      ->							str:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							"""lower newer"""

              __snake_case       	=							processor(text=_UpperCamelCase   )

              __snake_case       	=							tokenizer(_UpperCamelCase   )

              for key in encoded_tok.keys():
                     self.assertListEqual(encoded_tok[key]      , encoded_processor[key]   )


       def 			a		(		self   )      ->							str:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							"""lower newer"""
              __snake_case       	=							self.prepare_image_inputs()

              __snake_case       	=							processor(text=_UpperCamelCase      , images=_UpperCamelCase   )

              self.assertListEqual(list(inputs.keys()   )      , ["""input_ids""", """attention_mask""", """pixel_values"""]   )

              # test if it raises when no input is passed
              with pytest.raises(_UpperCamelCase   ):
                     processor()


       def 			a		(		self   )      ->							Any:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

              __snake_case       	=							processor.batch_decode(_UpperCamelCase   )
              __snake_case       	=							tokenizer.batch_decode(_UpperCamelCase   )

              self.assertListEqual(_UpperCamelCase      , _UpperCamelCase   )






       def 			a		(		self   )      ->							int:






              """simple docstring"""


              __snake_case       	=							self.get_image_processor()
              __snake_case       	=							self.get_tokenizer()

              __snake_case       	=							CLIPProcessor(tokenizer=_UpperCamelCase      , image_processor=_UpperCamelCase   )

              __snake_case       	=							"""lower newer"""
              __snake_case       	=							self.prepare_image_inputs()

              __snake_case       	=							processor(text=_UpperCamelCase      , images=_UpperCamelCase   )

              self.assertListEqual(list(inputs.keys()   )      , processor.model_input_names   )

