
import argparse
import time

import torch
import transformers
from measures_util import end_measure, log_measures, start_measure
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoTokenizer

from accelerate.utils import compute_module_sizes


_UpperCamelCase:					Union[str, Any]     ={
    'gpt-j-6b': {'is_causal': True, 'model': 'sgugger/sharded-gpt-j-6B', 'tokenizer': 'EleutherAI/gpt-j-6B'},
    'gpt-neox': {'is_causal': True, 'model': 'EleutherAI/gpt-neox-20b'},
    'opt': {'is_causal': True, 'model': 'facebook/opt-30b'},
    'T0pp': {'is_causal': False, 'model': 'bigscience/T0pp', 'model_revision': 'sharded'},
}

_UpperCamelCase:					Union[str, Any]     =[
    'Hello, my name is',
    'Are unicorns real? Unicorns are',
    'For the first time in several years,',
    'My name is Julien and I am',
    'The goal of life is',
    'Whenever I\'m sad, I like to',
]



def 	_a  (					):






  """simple docstring"""




  _lowerCAmelCase						=		argparse.ArgumentParser(description='Run and time generations on a big model using Accelerate.'    )
  parser.add_argument('model_name'		,				type=__SCREAMING_SNAKE_CASE		,				default=__SCREAMING_SNAKE_CASE		,				help='The name of the model to try.'    )
  parser.add_argument(
      '--tokenizer_name'		,				type=__SCREAMING_SNAKE_CASE		,				default=__SCREAMING_SNAKE_CASE		,				help='The name of the tokenizer (if different from the model.'    )
  parser.add_argument('--is_causal'		,				type=__SCREAMING_SNAKE_CASE		,				default=__SCREAMING_SNAKE_CASE		,				help='Whether or not the model is causal.'    )
  parser.add_argument(
      '--model_revision'		,				type=__SCREAMING_SNAKE_CASE		,				default=__SCREAMING_SNAKE_CASE		,				help='The revision to use for the model checkpoint.'    )
  parser.add_argument('--torch_dtype'		,				type=__SCREAMING_SNAKE_CASE		,				default=__SCREAMING_SNAKE_CASE		,				help='The dtype for the model.'    )
  parser.add_argument('--disk_offload'		,				action='store_true'    )

  _lowerCAmelCase						=		parser.parse_args()

  # Sanitize args
  if args.model_name in DEFAULT_MODELS:
    _lowerCAmelCase						=		DEFAULT_MODELS[args.model_name]
    _lowerCAmelCase						=		defaults['model']
    if args.tokenizer_name is None:
      _lowerCAmelCase						=		defaults.get('tokenizer'		,				args.model_name    )
    if args.is_causal is None:
      _lowerCAmelCase						=		defaults['is_causal']
    if args.model_revision is None:
      _lowerCAmelCase						=		defaults.get('model_revision'		,				'main'    )

  if args.is_causal is None:
    raise ValueError('Could not infer the default for `--is_causal`, pass either True or False for it.'    )
  if args.tokenizer_name is None:
    _lowerCAmelCase						=		args.model_name
  if args.model_revision is None:
    _lowerCAmelCase						=		'main'

  return args



def 	_a  (					):






  """simple docstring"""




  transformers.utils.logging.set_verbosity_error()
  _lowerCAmelCase						=		parse_args()

  if args.torch_dtype is None:
    _lowerCAmelCase						=		AutoConfig.from_pretrained(args.model_name    )
    _lowerCAmelCase						=		getattr(__SCREAMING_SNAKE_CASE		,				'torch_dtype'		,				torch.floataa    )
  else:
    _lowerCAmelCase						=		getattr(__SCREAMING_SNAKE_CASE		,				args.torch_dtype    )
  _lowerCAmelCase						=		AutoModelForCausalLM if args.is_causal else AutoModelForSeqaSeqLM
  _lowerCAmelCase						=		{
      'torch_dtype': torch_dtype,
      'revision': args.model_revision,
  }
  if args.disk_offload:
    _lowerCAmelCase						=		'tmp_offload'
    _lowerCAmelCase						=		True

  _lowerCAmelCase						=		start_measure()
  _lowerCAmelCase						=		model_cls.from_pretrained(args.model_name		,				device_map='auto'		,				**__SCREAMING_SNAKE_CASE    )
  _lowerCAmelCase						=		end_measure(__SCREAMING_SNAKE_CASE    )
  log_measures(__SCREAMING_SNAKE_CASE		,				'Model loading'    )

  _lowerCAmelCase						=		compute_module_sizes(__SCREAMING_SNAKE_CASE    )
  _lowerCAmelCase						=		{v: 0 for v in model.hf_device_map.values()}
  for module, device in model.hf_device_map.items():
    device_size[device] += module_sizes[module]
  _lowerCAmelCase						=		'\n'.join([f'''- {device}: {size // 2**20}MiB''' for device, size in device_size.items()]    )
  print(f'''\nTheoretical use:\n{message}'''    )

  _lowerCAmelCase						=		AutoTokenizer.from_pretrained(args.tokenizer_name    )

  _lowerCAmelCase						=		start_measure()
  _lowerCAmelCase						=		[]
  _lowerCAmelCase						=		[]
  _lowerCAmelCase						=		[]
  for prompt in PROMPTS:
    _lowerCAmelCase						=		tokenizer(__SCREAMING_SNAKE_CASE		,				return_tensors='pt'    ).to(0    )
    _lowerCAmelCase						=		inputs['input_ids'][0].tolist()
    _lowerCAmelCase						=		time.time()
    _lowerCAmelCase						=		model.generate(inputs['input_ids']    )
    _lowerCAmelCase						=		time.time()
    _lowerCAmelCase						=		outputs[0].tolist()
    _lowerCAmelCase						=		len(__SCREAMING_SNAKE_CASE    ) if outputs[: len(__SCREAMING_SNAKE_CASE    )] != tokens else len(__SCREAMING_SNAKE_CASE    ) - len(__SCREAMING_SNAKE_CASE    )
    _lowerCAmelCase						=		after_generate - before_generate

    _lowerCAmelCase						=		tokenizer.decode(__SCREAMING_SNAKE_CASE		,				skip_special_tokens=__SCREAMING_SNAKE_CASE    )
    texts_outs.append(__SCREAMING_SNAKE_CASE    )
    generation_times.append(__SCREAMING_SNAKE_CASE    )
    gen_tokens.append(__SCREAMING_SNAKE_CASE    )
    print(f'''Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n'''    )

  _lowerCAmelCase						=		end_measure(__SCREAMING_SNAKE_CASE    )
  log_measures(__SCREAMING_SNAKE_CASE		,				'Model generation'    )

  _lowerCAmelCase						=		[gen / tok for gen, tok in zip(__SCREAMING_SNAKE_CASE		,				__SCREAMING_SNAKE_CASE    )]
  _lowerCAmelCase						=		sum(__SCREAMING_SNAKE_CASE    ) / len(__SCREAMING_SNAKE_CASE    )
  print(f'''Average time of generation per token: {avg_gen:.2f}s'''    )
  print(f'''First generation (avg time per token): {generation_times_per_token[0]:.2f}s'''    )
  _lowerCAmelCase						=		sum(generation_times_per_token[1:]    ) / (len(__SCREAMING_SNAKE_CASE    ) - 1)
  print(f'''Average time of generation per token (excluding the first): {avg_gen:.2f}s'''    )


if __name__ == "__main__":
       main()


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

import faiss
import numpy as np
from datasets import Dataset

from transformers import BartConfig, BartTokenizer, DPRConfig, DPRQuestionEncoderTokenizer, RagConfig
from transformers.file_utils import is_datasets_available, is_faiss_available, is_psutil_available, is_torch_available
from transformers.integrations import is_ray_available
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_ray


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # noqa: E402 # isort:skip

if is_torch_available():
       from distributed_pytorch_retriever import RagPyTorchDistributedRetriever  # noqa: E402 # isort:skip
else:
       _UpperCamelCase:					List[Any]     =None

if is_ray_available():
       import ray  # noqa: E402 # isort:skip
       from distributed_ray_retriever import RagRayDistributedRetriever, RayRetriever  # noqa: E402 # isort:skip
else:
       _UpperCamelCase:					List[str]     =None
       _UpperCamelCase:					Tuple     =None
       _UpperCamelCase:					Any     =None



def 	_a  (					__SCREAMING_SNAKE_CASE					:  Optional[int]    ):






  """simple docstring"""




  if not (is_datasets_available() and is_faiss_available() and is_psutil_available()):
    _lowerCAmelCase						=		unittest.skip('test requires Datasets, Faiss, psutil'    )(__SCREAMING_SNAKE_CASE    )
  return test_case





@require_distributed_retrieval
class 						__lowercase(     SCREAMING_SNAKE_CASE   ):


       """simple docstring"""







       def SCREAMING_SNAKE_CASE_				(     self					:			List[str]       )					->   Optional[Any]:
         _lowerCAmelCase						=		tempfile.mkdtemp()
         _lowerCAmelCase						=		8

         # DPR tok
         _lowerCAmelCase						=		[
             '[UNK]',
             '[CLS]',
             '[SEP]',
             '[PAD]',
             '[MASK]',
             'want',
             '##want',
             '##ed',
             'wa',
             'un',
             'runn',
             '##ing',
             ',',
             'low',
             'lowest',
         ]
         _lowerCAmelCase						=		os.path.join(self.tmpdirname  ,      'dpr_tokenizer'       )
         os.makedirs(_lowerCAmelCase  ,      exist_ok=_lowerCAmelCase       )
         _lowerCAmelCase						=		os.path.join(_lowerCAmelCase  ,      DPR_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]       )       )

         # BART tok
         _lowerCAmelCase						=		[
             'l',
             'o',
             'w',
             'e',
             'r',
             's',
             't',
             'i',
             'd',
             'n',
             '\u0120',
             '\u0120l',
             '\u0120n',
             '\u0120lo',
             '\u0120low',
             'er',
             '\u0120lowest',
             '\u0120newer',
             '\u0120wider',
             '<unk>',
         ]
         _lowerCAmelCase						=		dict(zip(_lowerCAmelCase  ,      range(len(_lowerCAmelCase       )       )       )       )
         _lowerCAmelCase						=		['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
         _lowerCAmelCase						=		{'unk_token': '<unk>'}

         _lowerCAmelCase						=		os.path.join(self.tmpdirname  ,      'bart_tokenizer'       )
         os.makedirs(_lowerCAmelCase  ,      exist_ok=_lowerCAmelCase       )
         _lowerCAmelCase						=		os.path.join(_lowerCAmelCase  ,      BART_VOCAB_FILES_NAMES['vocab_file']       )
         _lowerCAmelCase						=		os.path.join(_lowerCAmelCase  ,      BART_VOCAB_FILES_NAMES['merges_file']       )
         with open(self.vocab_file  ,      'w'  ,      encoding='utf-8'       ) as fp:
           fp.write(json.dumps(_lowerCAmelCase       ) + '\n'       )
         with open(self.merges_file  ,      'w'  ,      encoding='utf-8'       ) as fp:
           fp.write('\n'.join(_lowerCAmelCase       )       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Tuple       )					->   DPRQuestionEncoderTokenizer:
         return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname  ,      'dpr_tokenizer'       )       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Any       )					->   BartTokenizer:
         return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname  ,      'bart_tokenizer'       )       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Dict       )					->   int:
         shutil.rmtree(self.tmpdirname       )



       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   str:
         _lowerCAmelCase						=		Dataset.from_dict(
             {
                 'id': ['0', '1'],
                 'text': ['foo', 'bar'],
                 'title': ['Foo', 'Bar'],
                 'embeddings': [np.ones(self.retrieval_vector_size       ), 2 * np.ones(self.retrieval_vector_size       )],
             }       )
         dataset.add_faiss_index('embeddings'  ,      string_factory='Flat'  ,      metric_type=faiss.METRIC_INNER_PRODUCT       )
         return dataset



       def SCREAMING_SNAKE_CASE_				(     self					:			int  ,      _lowerCAmelCase					:			bool  ,      _lowerCAmelCase					:			Tuple=1_2345       )					->   RagPyTorchDistributedRetriever:
         _lowerCAmelCase						=		self.get_dummy_dataset()
         _lowerCAmelCase						=		RagConfig(
             retrieval_vector_size=self.retrieval_vector_size  ,      question_encoder=DPRConfig().to_dict()  ,      generator=BartConfig().to_dict()  ,      )
         with patch('transformers.models.rag.retrieval_rag.load_dataset'       ) as mock_load_dataset:
           _lowerCAmelCase						=		dataset
           _lowerCAmelCase						=		RagPyTorchDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      )
           if init_retrieval:
             retriever.init_retrieval(_lowerCAmelCase       )
         return retriever



       def SCREAMING_SNAKE_CASE_				(     self					:			Any  ,      _lowerCAmelCase					:			bool       )					->   RagRayDistributedRetriever:
         # Have to run in local mode because sys.path modifications at top of
         # file are not propogated to remote workers.
         # https://stackoverflow.com/questions/54338013/parallel-import-a-python-file-from-sibling-folder
         ray.init(local_mode=_lowerCAmelCase       )
         _lowerCAmelCase						=		RagConfig(
             retrieval_vector_size=self.retrieval_vector_size  ,      question_encoder=DPRConfig().to_dict()  ,      generator=BartConfig().to_dict()  ,      )
         _lowerCAmelCase						=		ray.remote(_lowerCAmelCase       )
         _lowerCAmelCase						=		[remote_cls.remote() for _ in range(1       )]
         with patch('transformers.models.rag.retrieval_rag.load_dataset'       ) as mock_load_dataset:
           _lowerCAmelCase						=		self.get_dummy_dataset()
           _lowerCAmelCase						=		RagRayDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      retrieval_workers=_lowerCAmelCase  ,      )
           if init_retrieval:
             retriever.init_retrieval()
         return retriever



       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[Any]  ,      _lowerCAmelCase					:			bool  ,      _lowerCAmelCase					:			bool  ,      _lowerCAmelCase					:			List[Any]=1_2345       )					->   List[Any]:
         _lowerCAmelCase						=		self.get_dummy_dataset()
         _lowerCAmelCase						=		RagConfig(
             retrieval_vector_size=self.retrieval_vector_size  ,      question_encoder=DPRConfig().to_dict()  ,      generator=BartConfig().to_dict()  ,      index_name='custom'  ,      )
         if from_disk:
           _lowerCAmelCase						=		os.path.join(self.tmpdirname  ,      'dataset'       )
           _lowerCAmelCase						=		os.path.join(self.tmpdirname  ,      'index.faiss'       )
           dataset.get_index('embeddings'       ).save(os.path.join(self.tmpdirname  ,      'index.faiss'       )       )
           dataset.drop_index('embeddings'       )
           dataset.save_to_disk(os.path.join(self.tmpdirname  ,      'dataset'       )       )
           del dataset
           _lowerCAmelCase						=		RagPyTorchDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      )
         else:
           _lowerCAmelCase						=		RagPyTorchDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      index=CustomHFIndex(config.retrieval_vector_size  ,      _lowerCAmelCase       )  ,      )
         if init_retrieval:
           retriever.init_retrieval(_lowerCAmelCase       )
         return retriever



       def SCREAMING_SNAKE_CASE_				(     self					:			Union[str, Any]  ,      _lowerCAmelCase					:			bool  ,      _lowerCAmelCase					:			bool       )					->   int:
         # Have to run in local mode because sys.path modifications at top of
         # file are not propogated to remote workers.
         # https://stackoverflow.com/questions/54338013/parallel-import-a-python-file-from-sibling-folder
         ray.init(local_mode=_lowerCAmelCase       )
         _lowerCAmelCase						=		self.get_dummy_dataset()
         _lowerCAmelCase						=		RagConfig(
             retrieval_vector_size=self.retrieval_vector_size  ,      question_encoder=DPRConfig().to_dict()  ,      generator=BartConfig().to_dict()  ,      index_name='custom'  ,      )
         _lowerCAmelCase						=		ray.remote(_lowerCAmelCase       )
         _lowerCAmelCase						=		[remote_cls.remote() for _ in range(1       )]
         if from_disk:
           _lowerCAmelCase						=		os.path.join(self.tmpdirname  ,      'dataset'       )
           _lowerCAmelCase						=		os.path.join(self.tmpdirname  ,      'index.faiss'       )
           dataset.get_index('embeddings'       ).save(os.path.join(self.tmpdirname  ,      'index.faiss'       )       )
           dataset.drop_index('embeddings'       )
           dataset.save_to_disk(os.path.join(self.tmpdirname  ,      'dataset'       )       )
           del dataset
           _lowerCAmelCase						=		RagRayDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      retrieval_workers=_lowerCAmelCase  ,      index=CustomHFIndex.load_from_disk(
                   vector_size=config.retrieval_vector_size  ,      dataset_path=config.passages_path  ,      index_path=config.index_path  ,      )  ,      )
         else:
           _lowerCAmelCase						=		RagRayDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      retrieval_workers=_lowerCAmelCase  ,      index=CustomHFIndex(config.retrieval_vector_size  ,      _lowerCAmelCase       )  ,      )
         if init_retrieval:
           retriever.init_retrieval()
         return retriever



       def SCREAMING_SNAKE_CASE_				(     self					:			str  ,      _lowerCAmelCase					:			RagRetriever  ,      _lowerCAmelCase					:			np.array  ,      _lowerCAmelCase					:			int       )					->   None:
         _lowerCAmelCase	,       _lowerCAmelCase	,       _lowerCAmelCase						=		retriever.retrieve(_lowerCAmelCase  ,      n_docs=_lowerCAmelCase       )
         self.assertEqual(retrieved_doc_embeds.shape  ,      (2, n_docs, self.retrieval_vector_size)       )
         self.assertEqual(len(_lowerCAmelCase       )  ,      2       )
         self.assertEqual(sorted(doc_dicts[0]       )  ,      ['embeddings', 'id', 'text', 'title']       )
         self.assertEqual(len(doc_dicts[0]['id']       )  ,      _lowerCAmelCase       )
         self.assertEqual(doc_dicts[0]['id'][0]  ,      '1'       )  # max inner product is reached with second doc
         self.assertEqual(doc_dicts[1]['id'][0]  ,      '0'       )  # max inner product is reached with first doc
         self.assertListEqual(doc_ids.tolist()  ,      [[1], [0]]       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Any       )					->   Optional[int]:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_pytorch_distributed_retriever(init_retrieval=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Tuple       )					->   Any:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_custom_hf_index_pytorch_retriever(init_retrieval=_lowerCAmelCase  ,      from_disk=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase  ,      )



       def SCREAMING_SNAKE_CASE_				(     self					:			int       )					->   Optional[Any]:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_custom_hf_index_pytorch_retriever(init_retrieval=_lowerCAmelCase  ,      from_disk=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase  ,      )



       @require_ray
       def SCREAMING_SNAKE_CASE_				(     self					:			Dict       )					->   Any:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_ray_distributed_retriever(init_retrieval=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )
         ray.shutdown()



       @require_ray
       def SCREAMING_SNAKE_CASE_				(     self					:			List[str]       )					->   Optional[Any]:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )
         with self.assertRaises(_lowerCAmelCase       ):
           self.distributed_retriever_check(
               self.get_dummy_custom_hf_index_ray_retriever(init_retrieval=_lowerCAmelCase  ,      from_disk=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase  ,      )
         ray.shutdown()






       @require_ray
       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   List[Any]:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_custom_hf_index_ray_retriever(init_retrieval=_lowerCAmelCase  ,      from_disk=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )
         ray.shutdown()
