






'''simple docstring'''







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


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to properly calculate the metrics on the
# validation dataset when in a distributed system, and builds off the
# `nlp_example.py` script.
#
# 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 help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# 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     :   Any	      =		16
UpperCamelCase     :   Any	      =		32
def     A__      (					__lowerCAmelCase		:      Accelerator ,     __lowerCAmelCase		:      int = 16    ):
						lowerCamelCase__								=	AutoTokenizer.from_pretrained("""bert-base-cased"""    )
						lowerCamelCase__								=	load_dataset("""glue""" ,     """mrpc"""    )

						def tokenize_function(__lowerCAmelCase		:      Union[str, Any]    ):
												# max_length=None => use the model max length (it's actually the default)
												lowerCamelCase__								=	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():
												lowerCamelCase__								=	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
						lowerCamelCase__								=	tokenized_datasets.rename_column("""label""" ,     """labels"""    )

						def collate_fn(__lowerCAmelCase		:      Dict    ):
												# On TPU it's best to pad everything to the same length or training will be very slow.
												lowerCamelCase__								=	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__								=	16
												elif accelerator.mixed_precision != "no":
																		lowerCamelCase__								=	8
												else:
																		lowerCamelCase__								=	None

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

						# Instantiate dataloaders.
						lowerCamelCase__								=	DataLoader(
						    tokenized_datasets["""train"""] ,     shuffle=__lowerCAmelCase ,     collate_fn=__lowerCAmelCase ,     batch_size=__lowerCAmelCase    )
						lowerCamelCase__								=	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

							UpperCamelCase     :   int	      =		mocked_dataloaders  # noqa: F811
def     A__      (					__lowerCAmelCase		:      Dict ,     __lowerCAmelCase		:      List[str]    ):
						# For testing only
						if os.environ.get("""TESTING_MOCKED_DATALOADERS""" ,     __lowerCAmelCase    ) == "1":
												lowerCamelCase__								=	2
						# Initialize accelerator
						lowerCamelCase__								=	Accelerator(cpu=args.cpu ,     mixed_precision=args.mixed_precision    )
						# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
						lowerCamelCase__								=	config["""lr"""]
						lowerCamelCase__								=	int(config["""num_epochs"""]    )
						lowerCamelCase__								=	int(config["""seed"""]    )
						lowerCamelCase__								=	int(config["""batch_size"""]    )

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

						# If the batch size is too big we use gradient accumulation
						lowerCamelCase__								=	1
						if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
												lowerCamelCase__								=	batch_size // MAX_GPU_BATCH_SIZE
												lowerCamelCase__								=	MAX_GPU_BATCH_SIZE

						set_seed(__lowerCAmelCase    )
						lowerCamelCase__							,      lowerCamelCase__								=	get_dataloaders(__lowerCAmelCase ,     __lowerCAmelCase    )
						# Instantiate the model (we build the model here so that the seed also control new weights initialization)
						lowerCamelCase__								=	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).
						lowerCamelCase__								=	model.to(accelerator.device    )

						# Instantiate optimizer
						lowerCamelCase__								=	AdamW(params=model.parameters() ,     lr=__lowerCAmelCase    )

						# Instantiate scheduler
						lowerCamelCase__								=	get_linear_schedule_with_warmup(
						    optimizer=__lowerCAmelCase ,     num_warmup_steps=100 ,     num_training_steps=(len(__lowerCAmelCase    ) * num_epochs) // gradient_accumulation_steps ,     )

						# 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__								=	accelerator.prepare(
						    __lowerCAmelCase ,     __lowerCAmelCase ,     __lowerCAmelCase ,     __lowerCAmelCase ,     __lowerCAmelCase    )

						# Now we train the model
						for epoch in range(__lowerCAmelCase    ):
												model.train()
												for step, batch in enumerate(__lowerCAmelCase    ):
																		# We could avoid this line since we set the accelerator with `device_placement=True`.
																		batch.to(accelerator.device    )
																		lowerCamelCase__								=	model(**__lowerCAmelCase    )
																		lowerCamelCase__								=	outputs.loss
																		lowerCamelCase__								=	loss / gradient_accumulation_steps
																		accelerator.backward(__lowerCAmelCase    )
																		if step % gradient_accumulation_steps == 0:
																								optimizer.step()
																								lr_scheduler.step()
																								optimizer.zero_grad()

												model.eval()
												lowerCamelCase__								=	0
												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():
																								lowerCamelCase__								=	model(**__lowerCAmelCase    )
																		lowerCamelCase__								=	outputs.logits.argmax(dim=-1    )
																		lowerCamelCase__							,      lowerCamelCase__								=	accelerator.gather((predictions, batch["""labels"""])    )
																		# New Code #
																		# First we check if it's a distributed system
																		if accelerator.use_distributed:
																								# Then see if we're on the last batch of our eval dataloader
																								if step == len(__lowerCAmelCase    ) - 1:
																														# Last batch needs to be truncated on distributed systems as it contains additional samples
																														lowerCamelCase__								=	predictions[: len(eval_dataloader.dataset    ) - samples_seen]
																														lowerCamelCase__								=	references[: len(eval_dataloader.dataset    ) - samples_seen]
																								else:
																														# Otherwise we add the number of samples seen
																														samples_seen += references.shape[0]
            # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
            # accelerator.gather_for_metrics((predictions, batch["labels"]))
																		metric.add_batch(
																		    predictions=__lowerCAmelCase ,     references=__lowerCAmelCase ,     )

												lowerCamelCase__								=	metric.compute()
												# Use accelerator.print to print only on the main process.
												accelerator.print(F'''epoch {epoch}:''' ,     __lowerCAmelCase    )
def     A__      (					):
						lowerCamelCase__								=	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.""" ,     )
						parser.add_argument("""--cpu""" ,     action="""store_true""" ,     help="""If passed, will train on the CPU."""    )
						lowerCamelCase__								=	parser.parse_args()
						lowerCamelCase__								=	{"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
						training_function(__lowerCAmelCase ,     __lowerCAmelCase    )


if __name__ == "__main__":
							main()





'''simple docstring'''







import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							tempfile.mkdtemp()
            _lowerCAmelCase     :				List[str]       =							5

            # Realm tok
            _lowerCAmelCase     :				str       =							[
                '[UNK]',
                '[CLS]',
                '[SEP]',
                '[PAD]',
                '[MASK]',
                'test',
                'question',
                'this',
                'is',
                'the',
                'first',
                'second',
                'third',
                'fourth',
                'fifth',
                'record',
                'want',
                '##want',
                '##ed',
                'wa',
                'un',
                'runn',
                '##ing',
                ',',
                'low',
                'lowest',
            ]
            _lowerCAmelCase     :				Union[str, Any]       =							os.path.join(self.tmpdirname   ,						'realm_tokenizer' )
            os.makedirs(snake_case__   ,						exist_ok=snake_case__ )
            _lowerCAmelCase     :				Dict       =							os.path.join(snake_case__   ,						VOCAB_FILES_NAMES['vocab_file'] )
            with open(self.vocab_file   ,						'w'   ,						encoding='utf-8' ) as vocab_writer:
                   vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )

            _lowerCAmelCase     :				List[str]       =							os.path.join(self.tmpdirname   ,						'realm_block_records' )
            os.makedirs(snake_case__   ,						exist_ok=snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname   ,						'realm_tokenizer' ) )







     def a						(			self ):

            '''simple docstring'''

            shutil.rmtree(self.tmpdirname )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							RealmConfig(num_block_records=self.num_block_records )
            return config







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							Dataset.from_dict(
                {
                    'id': ['0', '1'],
                    'question': ['foo', 'bar'],
                    'answers': [['Foo', 'Bar'], ['Bar']],
                } )
            return dataset







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				str       =							np.array(
                [
                    b'This is the first record',
                    b'This is the second record',
                    b'This is the third record',
                    b'This is the fourth record',
                    b'This is the fifth record',
                    b'This is a longer longer longer record',
                ]   ,						dtype=snake_case__   ,						)
            return block_records







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Tuple       =							RealmRetriever(
                block_records=self.get_dummy_block_records()   ,						tokenizer=self.get_tokenizer()   ,						)
            return retriever







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[int]       =							self.get_config()
            _lowerCAmelCase     :				List[Any]       =							self.get_dummy_retriever()
            _lowerCAmelCase     :				Any       =							retriever.tokenizer

            _lowerCAmelCase     :				Tuple       =							np.array([0, 3]   ,						dtype='long' )
            _lowerCAmelCase     :				Dict       =							tokenizer(['Test question'] ).input_ids
            _lowerCAmelCase     :				int       =							tokenizer(
                ['the fourth']   ,						add_special_tokens=snake_case__   ,						return_token_type_ids=snake_case__   ,						return_attention_mask=snake_case__   ,						).input_ids
            _lowerCAmelCase     :				Tuple       =							config.reader_seq_len

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Union[str, Any]       =							retriever(
                snake_case__   ,						snake_case__   ,						answer_ids=snake_case__   ,						max_length=snake_case__   ,						return_tensors='np' )

            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(concat_inputs.input_ids.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.attention_mask.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.token_type_ids.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.special_tokens_mask.shape   ,						(2, 10) )
            self.assertEqual(
                tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] )   ,						['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]']   ,						)
            self.assertEqual(
                tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] )   ,						['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]']   ,						)







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							self.get_config()
            _lowerCAmelCase     :				int       =							self.get_dummy_retriever()
            _lowerCAmelCase     :				List[str]       =							retriever.tokenizer

            _lowerCAmelCase     :				List[Any]       =							np.array([0, 3, 5]   ,						dtype='long' )
            _lowerCAmelCase     :				str       =							tokenizer(['Test question'] ).input_ids
            _lowerCAmelCase     :				Union[str, Any]       =							tokenizer(
                ['the fourth', 'longer longer']   ,						add_special_tokens=snake_case__   ,						return_token_type_ids=snake_case__   ,						return_attention_mask=snake_case__   ,						).input_ids
            _lowerCAmelCase     :				Optional[int]       =							config.reader_seq_len

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				List[str]       =							retriever(
                snake_case__   ,						snake_case__   ,						answer_ids=snake_case__   ,						max_length=snake_case__   ,						return_tensors='np' )

            self.assertEqual([False, True, True]   ,						snake_case__ )
            self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]   ,						snake_case__ )
            self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]   ,						snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self.get_dummy_retriever()
            retriever.save_pretrained(os.path.join(self.tmpdirname   ,						'realm_block_records' ) )

            # Test local path
            _lowerCAmelCase     :				Union[str, Any]       =							retriever.from_pretrained(os.path.join(self.tmpdirname   ,						'realm_block_records' ) )
            self.assertEqual(retriever.block_records[0]   ,						b'This is the first record' )

            # Test mocked remote path
            with patch('transformers.models.realm.retrieval_realm.hf_hub_download' ) as mock_hf_hub_download:
                   _lowerCAmelCase     :				Any       =							os.path.join(
                       os.path.join(self.tmpdirname   ,						'realm_block_records' )   ,						_REALM_BLOCK_RECORDS_FILENAME )
                   _lowerCAmelCase     :				str       =							RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa' )

            self.assertEqual(retriever.block_records[0]   ,						b'This is the first record' )

