





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				:       Optional[int]	   =				16
_UpperCAmelCase				:       int	   =				32


def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase						,	_UpperCAmelCase = 16 )			->     Dict:
    lowerCamelCase__    :      Dict					 =		AutoTokenizer.from_pretrained('bert-base-cased' )
    lowerCamelCase__    :      List[Any]					 =		load_dataset('glue'						,	'mrpc' )

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

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

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

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

    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				:       str	   =				mocked_dataloaders  # noqa: F811


def        SCREAMING_SNAKE_CASE      (       _UpperCAmelCase						,	_UpperCAmelCase )			->     Tuple:
    # For testing only
    if os.environ.get('TESTING_MOCKED_DATALOADERS'						,	_UpperCAmelCase ) == "1":
        lowerCamelCase__    :      Dict					 =		2
    # New Code #
    lowerCamelCase__    :      str					 =		int(args.gradient_accumulation_steps )
    lowerCamelCase__    :      int					 =		int(args.local_sgd_steps )
    # Initialize accelerator
    lowerCamelCase__    :      str					 =		Accelerator(
        cpu=args.cpu						,	mixed_precision=args.mixed_precision						,	gradient_accumulation_steps=_UpperCAmelCase )
    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
    lowerCamelCase__    :      Any					 =		config['lr']
    lowerCamelCase__    :      int					 =		int(config['num_epochs'] )
    lowerCamelCase__    :      List[str]					 =		int(config['seed'] )
    lowerCamelCase__    :      Any					 =		int(config['batch_size'] )

    lowerCamelCase__    :      Dict					 =		evaluate.load('glue'						,	'mrpc' )

    set_seed(_UpperCAmelCase )
    lowerCamelCase__ ,							lowerCamelCase__    :      List[Any]					 =		get_dataloaders(_UpperCAmelCase						,	_UpperCAmelCase )
    # Instantiate the model (we build the model here so that the seed also control new weights initialization)
    lowerCamelCase__    :      Tuple					 =		AutoModelForSequenceClassification.from_pretrained('bert-base-cased'						,	return_dict=_UpperCAmelCase )

    # 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).
    lowerCamelCase__    :      Optional[int]					 =		model.to(accelerator.device )

    # Instantiate optimizer
    lowerCamelCase__    :      Optional[int]					 =		AdamW(params=model.parameters()						,	lr=_UpperCAmelCase )

    # Instantiate scheduler
    lowerCamelCase__    :      Tuple					 =		get_linear_schedule_with_warmup(
        optimizer=_UpperCAmelCase						,	num_warmup_steps=100						,	num_training_steps=(len(_UpperCAmelCase ) * 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.
    lowerCamelCase__ ,							lowerCamelCase__ ,							lowerCamelCase__ ,							lowerCamelCase__ ,							lowerCamelCase__    :      int					 =		accelerator.prepare(
        _UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase )

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

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

        lowerCamelCase__    :      Dict					 =		metric.compute()
        # Use accelerator.print to print only on the main process.
        accelerator.print(F"""epoch {epoch}:"""						,	_UpperCAmelCase )


def        SCREAMING_SNAKE_CASE      (       )			->     Dict:
    lowerCamelCase__    :      Optional[Any]					 =		argparse.ArgumentParser(description='Simple example of training script.' )
    parser.add_argument(
        '--mixed_precision'						,	type=_UpperCAmelCase						,	default=_UpperCAmelCase						,	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=_UpperCAmelCase						,	default=1						,	help='The number of minibatches to be ran before gradients are accumulated.'						,	)
    parser.add_argument(
        '--local_sgd_steps'						,	type=_UpperCAmelCase						,	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.' )
    lowerCamelCase__    :      Optional[Any]					 =		parser.parse_args()
    lowerCamelCase__    :      Optional[Any]					 =		{'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
    training_function(_UpperCAmelCase						,	_UpperCAmelCase )


if __name__ == "__main__":
    main()












import unittest

from transformers import BertGenerationTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


_UpperCAmelCase				:       Optional[Any]	   =				"""▁"""

_UpperCAmelCase				:       Optional[Any]	   =				get_tests_dir("""fixtures/test_sentencepiece.model""")

@require_sentencepiece
class    lowerCAmelCase							(					__UpperCamelCase,  unittest.TestCase			):
 UpperCAmelCase__													=		BertGenerationTokenizer
 UpperCAmelCase__													=		False
 UpperCAmelCase__													=		True
 def      A_	(      self  :      List[Any]	)			->	List[str]:
     super().setUp()

     lowerCamelCase__    :      Dict					 =		BertGenerationTokenizer(UpperCAmelCase			,     keep_accents=UpperCAmelCase	)
     tokenizer.save_pretrained(self.tmpdirname	)
 def      A_	(      self  :      Optional[Any]	)			->	Dict:
     lowerCamelCase__    :      List[str]					 =		'<s>'
     lowerCamelCase__    :      Optional[int]					 =		1

     self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase	)			,     UpperCAmelCase	)
     self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase	)			,     UpperCAmelCase	)
 def      A_	(      self  :      List[str]	)			->	Optional[int]:
     lowerCamelCase__    :      Optional[Any]					 =		list(self.get_tokenizer().get_vocab().keys()	)

     self.assertEqual(vocab_keys[0]			,     '<unk>'	)
     self.assertEqual(vocab_keys[1]			,     '<s>'	)
     self.assertEqual(vocab_keys[-1]			,     '<pad>'	)
     self.assertEqual(len(UpperCAmelCase	)			,     1002	)
 def      A_	(      self  :      List[Any]	)			->	Optional[Any]:
     self.assertEqual(self.get_tokenizer().vocab_size			,     1000	)
 def      A_	(      self  :      Union[str, Any]	)			->	List[Any]:
     lowerCamelCase__    :      Union[str, Any]					 =		BertGenerationTokenizer(UpperCAmelCase			,     keep_accents=UpperCAmelCase	)

     lowerCamelCase__    :      List[str]					 =		tokenizer.tokenize('This is a test'	)
     self.assertListEqual(UpperCAmelCase			,     ['▁This', '▁is', '▁a', '▁t', 'est']	)

     self.assertListEqual(
         tokenizer.convert_tokens_to_ids(UpperCAmelCase	)			,     [285, 46, 10, 170, 382]			,     )

     lowerCamelCase__    :      List[str]					 =		tokenizer.tokenize('I was born in 92000, and this is falsé.'	)
     self.assertListEqual(
         UpperCAmelCase			,     [
             SPIECE_UNDERLINE + 'I',
             SPIECE_UNDERLINE + 'was',
             SPIECE_UNDERLINE + 'b',
             'or',
             'n',
             SPIECE_UNDERLINE + 'in',
             SPIECE_UNDERLINE + '',
             '9',
             '2',
             '0',
             '0',
             '0',
             ',',
             SPIECE_UNDERLINE + 'and',
             SPIECE_UNDERLINE + 'this',
             SPIECE_UNDERLINE + 'is',
             SPIECE_UNDERLINE + 'f',
             'al',
             's',
             'é',
             '.',
         ]			,     )
     lowerCamelCase__    :      Optional[int]					 =		tokenizer.convert_tokens_to_ids(UpperCAmelCase	)
     self.assertListEqual(
         UpperCAmelCase			,     [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]			,     )

     lowerCamelCase__    :      Optional[Any]					 =		tokenizer.convert_ids_to_tokens(UpperCAmelCase	)
     self.assertListEqual(
         UpperCAmelCase			,     [
             SPIECE_UNDERLINE + 'I',
             SPIECE_UNDERLINE + 'was',
             SPIECE_UNDERLINE + 'b',
             'or',
             'n',
             SPIECE_UNDERLINE + 'in',
             SPIECE_UNDERLINE + '',
             '<unk>',
             '2',
             '0',
             '0',
             '0',
             ',',
             SPIECE_UNDERLINE + 'and',
             SPIECE_UNDERLINE + 'this',
             SPIECE_UNDERLINE + 'is',
             SPIECE_UNDERLINE + 'f',
             'al',
             's',
             '<unk>',
             '.',
         ]			,     )
 @cached_property
 def      A_	(      self  :      Dict	)			->	Tuple:
     return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder'	)
 @slow
 def      A_	(      self  :      Optional[int]	)			->	List[str]:
     lowerCamelCase__    :      Union[str, Any]					 =		'Hello World!'
     lowerCamelCase__    :      Dict					 =		[18536, 2260, 101]

     self.assertListEqual(UpperCAmelCase			,     self.big_tokenizer.encode(UpperCAmelCase	)	)
 @slow
 def      A_	(      self  :      Optional[Any]	)			->	str:
     lowerCamelCase__    :      List[Any]					 =		(
         'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'
         ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth'
     )
     lowerCamelCase__    :      Any					 =		[
         871,
         419,
         358,
         946,
         991,
         2521,
         452,
         358,
         1357,
         387,
         7751,
         3536,
         112,
         985,
         456,
         126,
         865,
         938,
         5400,
         5734,
         458,
         1368,
         467,
         786,
         2462,
         5246,
         1159,
         633,
         865,
         4519,
         457,
         582,
         852,
         2557,
         427,
         916,
         508,
         405,
         34324,
         497,
         391,
         408,
         11342,
         1244,
         385,
         100,
         938,
         985,
         456,
         574,
         362,
         12597,
         3200,
         3129,
         1172,
     ]

     self.assertListEqual(UpperCAmelCase			,     self.big_tokenizer.encode(UpperCAmelCase	)	)
 @require_torch
 @slow
 def      A_	(      self  :      int	)			->	Optional[Any]:
     import torch

     from transformers import BertGenerationConfig, BertGenerationEncoder

     # Build sequence
     lowerCamelCase__    :      str					 =		list(self.big_tokenizer.get_vocab().keys()	)[:10]
     lowerCamelCase__    :      int					 =		' '.join(UpperCAmelCase	)
     lowerCamelCase__    :      Union[str, Any]					 =		self.big_tokenizer.encode_plus(UpperCAmelCase			,     return_tensors='pt'			,     return_token_type_ids=UpperCAmelCase	)
     lowerCamelCase__    :      Optional[Any]					 =		self.big_tokenizer.batch_encode_plus(
         [sequence + ' ' + sequence]			,     return_tensors='pt'			,     return_token_type_ids=UpperCAmelCase	)

     lowerCamelCase__    :      Tuple					 =		BertGenerationConfig()
     lowerCamelCase__    :      Optional[Any]					 =		BertGenerationEncoder(UpperCAmelCase	)

     assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size

     with torch.no_grad():
         model(**UpperCAmelCase	)
         model(**UpperCAmelCase	)







 @slow
 def      A_	(      self  :      Optional[int]	)			->	List[Any]:
     # fmt: off
     lowerCamelCase__    :      Any					 =		{'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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tokenizer_integration_test_util(
         expected_encoding=UpperCAmelCase			,     model_name='google/bert_for_seq_generation_L-24_bbc_encoder'			,     revision='c817d1fd1be2ffa69431227a1fe320544943d4db'			,     )





