

import itertools
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa

import datasets
from datasets.table import table_cast


__UpperCAmelCase     					=  datasets.utils.logging.get_logger(__name__)





@dataclass
class A__     (			datasets.BuilderConfig			):



 """simple docstring"""







 _lowercase  :       Optional[datasets.Features]  			=    None





class A__     (			datasets.ArrowBasedBuilder			):



 """simple docstring"""







 _lowercase  :       str  			=    ArrowConfig

 def  __magic_name__							(		self			:						Optional[Any]							):






      '''simple docstring'''




      return datasets.DatasetInfo(features=self.config.features							)

 def  __magic_name__							(		self			:						Dict  ,    A_			:						List[str]							):






      '''simple docstring'''




      if not self.config.data_files:
           raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}'''							)
      _lowerCAmelCase :       Union[str, Any]	   =     dl_manager.download_and_extract(self.config.data_files							)
      if isinstance(A_  ,    (str, list, tuple)							):
           _lowerCAmelCase :       Tuple	   =     data_files
           if isinstance(A_  ,    A_							):
                _lowerCAmelCase :       str	   =     [files]
           # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
           _lowerCAmelCase :       List[str]	   =     [dl_manager.iter_files(A_							) for file in files]
           return [datasets.SplitGenerator(name=datasets.Split.TRAIN  ,    gen_kwargs={"files": files}							)]
      _lowerCAmelCase :       str	   =     []
      for split_name, files in data_files.items():
           if isinstance(A_  ,    A_							):
                _lowerCAmelCase :       int	   =     [files]
           # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
           _lowerCAmelCase :       Union[str, Any]	   =     [dl_manager.iter_files(A_							) for file in files]
           # Infer features is they are stoed in the arrow schema
           if self.info.features is None:
                for file in itertools.chain.from_iterable(A_							):
                     with open(A_  ,    "rb"							) as f:
                          _lowerCAmelCase :       Union[str, Any]	   =     datasets.Features.from_arrow_schema(pa.ipc.open_stream(A_							).schema							)
                     break
           splits.append(datasets.SplitGenerator(name=A_  ,    gen_kwargs={"files": files}							)							)
      return splits

 def  __magic_name__							(		self			:						Tuple  ,    A_			:						pa.Table							):






      '''simple docstring'''




      if self.info.features is not None:
           # more expensive cast to support nested features with keys in a different order
           # allows str <-> int/float or str to Audio for example
           _lowerCAmelCase :       List[Any]	   =     table_cast(A_  ,    self.info.features.arrow_schema							)
      return pa_table


 def  __magic_name__							(		self			:						Dict  ,    A_			:						Any							):






      '''simple docstring'''




      for file_idx, file in enumerate(itertools.chain.from_iterable(A_							)							):
           with open(A_  ,    "rb"							) as f:
                try:
                     for batch_idx, record_batch in enumerate(pa.ipc.open_stream(A_							)							):
                          _lowerCAmelCase :       Tuple	   =     pa.Table.from_batches([record_batch]							)
                          # Uncomment for debugging (will print the Arrow table size and elements)
                          # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                          # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                          yield F'''{file_idx}_{batch_idx}''', self._cast_table(A_							)
                except ValueError as e:
                     logger.error(F'''Failed to read file \'{file}\' with error {type(A_							)}: {e}'''							)
                     raise









import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
    datefmt='%m/%d/%Y %H:%M:%S',
    level=logging.INFO,
)
__UpperCAmelCase     					=  logging.getLogger(__name__)

__UpperCAmelCase     					=  int(1_0_0_0_0)  # Hardcoded max length to avoid infinite loop

__UpperCAmelCase     					=  {
    'gpt2': (GPTaLMHeadModel, GPTaTokenizer),
    'ctrl': (CTRLLMHeadModel, CTRLTokenizer),
    'openai-gpt': (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    'xlnet': (XLNetLMHeadModel, XLNetTokenizer),
    'transfo-xl': (TransfoXLLMHeadModel, TransfoXLTokenizer),
    'xlm': (XLMWithLMHeadModel, XLMTokenizer),
    'gptj': (GPTJForCausalLM, AutoTokenizer),
    'bloom': (BloomForCausalLM, BloomTokenizerFast),
    'llama': (LlamaForCausalLM, LlamaTokenizer),
    'opt': (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
__UpperCAmelCase     					=  'In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>'







def 						_snake_case		(     SCREAMING_SNAKE_CASE					)							->   Any:

     """simple docstring"""







     np.random.seed(args.seed					)
     torch.manual_seed(args.seed					)
     if args.n_gpu > 0:
          torch.cuda.manual_seed_all(args.seed					)







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   str:

     """simple docstring"""







     if args.temperature > 0.7:
          logger.info("CTRL typically works better with lower temperatures (and lower top_k)."					)

     _lowerCAmelCase :       Optional[int]	   =     tokenizer.encode(SCREAMING_SNAKE_CASE		,				add_special_tokens=SCREAMING_SNAKE_CASE					)
     if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()					):
          logger.info("WARNING! You are not starting your generation from a control code so you won't get good results"					)
     return prompt_text







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   Optional[Any]:

     """simple docstring"""







     _lowerCAmelCase :       List[str]	   =     hasattr(model.config		,				"use_lang_emb"					) and model.config.use_lang_emb
     if hasattr(model.config		,				"lang2id"					) and use_lang_emb:
          _lowerCAmelCase :       List[Any]	   =     model.config.langaid.keys()
          if args.xlm_language in available_languages:
               _lowerCAmelCase :       Optional[int]	   =     args.xlm_language
          else:
               _lowerCAmelCase :       Dict	   =     None
               while language not in available_languages:
                    _lowerCAmelCase :       Dict	   =     input("Using XLM. Select language in " + str(list(SCREAMING_SNAKE_CASE					)					) + " >>> "					)

          _lowerCAmelCase :       Any	   =     model.config.langaid[language]
          # kwargs["language"] = tokenizer.lang2id[language]

     # TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
     # XLM masked-language modeling (MLM) models need masked token
     # is_xlm_mlm = "mlm" in args.model_name_or_path
     # if is_xlm_mlm:
     #     kwargs["mask_token_id"] = tokenizer.mask_token_id

     return prompt_text







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   Tuple:

     """simple docstring"""







     _lowerCAmelCase :       List[Any]	   =     args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
     _lowerCAmelCase :       Union[str, Any]	   =     prefix + prompt_text
     return prompt_text







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   Union[str, Any]:

     """simple docstring"""







     _lowerCAmelCase :       List[str]	   =     args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
     _lowerCAmelCase :       Any	   =     prefix + prompt_text
     return prompt_text


__UpperCAmelCase     					=  {
    'ctrl': prepare_ctrl_input,
    'xlm': prepare_xlm_input,
    'xlnet': prepare_xlnet_input,
    'transfo-xl': prepare_transfoxl_input,
}







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   Union[str, Any]:

     """simple docstring"""







     if length < 0 and max_sequence_length > 0:
          _lowerCAmelCase :       int	   =     max_sequence_length
     elif 0 < max_sequence_length < length:
          _lowerCAmelCase :       Optional[int]	   =     max_sequence_length  # No generation bigger than model size
     elif length < 0:
          _lowerCAmelCase :       Optional[Any]	   =     MAX_LENGTH  # avoid infinite loop
     return length







def 						_snake_case		(     SCREAMING_SNAKE_CASE					)							->   int:

     """simple docstring"""







     _lowerCAmelCase :       int	   =     None
     if hasattr(SCREAMING_SNAKE_CASE		,				"hidden_size"					):
          _lowerCAmelCase :       str	   =     model_config.hidden_size
     elif hasattr(SCREAMING_SNAKE_CASE		,				"n_embed"					):
          _lowerCAmelCase :       Optional[int]	   =     model_config.n_embed
     elif hasattr(SCREAMING_SNAKE_CASE		,				"n_embd"					):
          _lowerCAmelCase :       Dict	   =     model_config.n_embd

     _lowerCAmelCase :       Union[str, Any]	   =     None
     if hasattr(SCREAMING_SNAKE_CASE		,				"num_attention_heads"					):
          _lowerCAmelCase :       List[Any]	   =     model_config.num_attention_heads
     elif hasattr(SCREAMING_SNAKE_CASE		,				"n_head"					):
          _lowerCAmelCase :       List[Any]	   =     model_config.n_head

     if embedding_size is None or num_head is None or num_head == 0:
          raise ValueError("Check the model config"					)

     _lowerCAmelCase :       Union[str, Any]	   =     int(embedding_size / num_head					)
     if hasattr(SCREAMING_SNAKE_CASE		,				"n_layer"					):
          _lowerCAmelCase :       Any	   =     model_config.n_layer
     elif hasattr(SCREAMING_SNAKE_CASE		,				"num_hidden_layers"					):
          _lowerCAmelCase :       Any	   =     model_config.num_hidden_layers
     else:
          raise ValueError("Number of hidden layers couldn't be determined from the model config"					)

     return num_layer, num_head, num_embedding_size_per_head







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   Optional[Any]:

     """simple docstring"""







     _lowerCAmelCase   ,      _lowerCAmelCase   ,      _lowerCAmelCase :       Any	   =     sparse_model_config(model.config					)
     if model.config.model_type == "bloom":
          _lowerCAmelCase :       str	   =     tuple(
              (
                  torch.empty(int(num_attention_heads * batch_size					)		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)
                  .to(model.dtype					)
                  .to(model.device					),
                  torch.empty(int(num_attention_heads * batch_size					)		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)
                  .to(model.dtype					)
                  .to(model.device					),
              )
              for _ in range(SCREAMING_SNAKE_CASE					)					)
     else:
          _lowerCAmelCase :       Any	   =     tuple(
              (
                  torch.empty(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)
                  .to(model.dtype					)
                  .to(model.device					),
                  torch.empty(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)
                  .to(model.dtype					)
                  .to(model.device					),
              )
              for _ in range(SCREAMING_SNAKE_CASE					)					)
     return past_key_values







def 						_snake_case		(     SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)							->   str:

     """simple docstring"""







     _lowerCAmelCase :       Tuple	   =     len(SCREAMING_SNAKE_CASE					)
     _lowerCAmelCase :       Tuple	   =     tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE		,				return_tensors="pt"					)
     _lowerCAmelCase :       List[Any]	   =     dummy_input.to(model.device					)
     if model.config.use_cache:
          _lowerCAmelCase :       int	   =     generate_past_key_values(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				1					)
     _lowerCAmelCase :       Optional[int]	   =     torch.cat(
         [
             torch.zeros(dummy_input["attention_mask"].shape[0]		,				1					)
             .to(dummy_input["attention_mask"].dtype					)
             .to(model.device					),
             dummy_input["attention_mask"],
         ]		,				-1		,				)
     return dummy_input





class A__     (			A			):



 """simple docstring"""







 _lowercase  :       List[Any]  			=    ('''_optimized''', '''_default''')

 def __init__(		self			:						Optional[int]  ,    A_			:						List[str]  ,    A_			:						List[str]							):






      '''simple docstring'''




      _lowerCAmelCase :       Optional[int]	   =     optimized
      _lowerCAmelCase :       List[str]	   =     default

 def __call__(		self			:						Any  ,    *A_			:						Optional[Any]  ,    **A_			:						Tuple							):






      '''simple docstring'''




      if kwargs["past_key_values"] is None and self._default.config.use_cache:
           _lowerCAmelCase :       List[Any]	   =     generate_past_key_values(self._default  ,    kwargs["input_ids"].shape[0]  ,    0							)
      kwargs.pop("position_ids"  ,    A_							)
      for k in list(kwargs.keys()							):
           if kwargs[k] is None or isinstance(kwargs[k]  ,    A_							):
                kwargs.pop(A_							)
      _lowerCAmelCase :       Any	   =     self._optimized(**A_							)
      _lowerCAmelCase :       str	   =     outputs[0]
      _lowerCAmelCase :       Optional[int]	   =     outputs[1]
      _lowerCAmelCase :       Tuple	   =     CausalLMOutputWithPast(
          loss=A_  ,    logits=A_  ,    past_key_values=A_  ,    hidden_states=A_  ,    attentions=A_  ,    )
      return fixed_output

 def __getattr__(		self			:						List[Any]  ,    A_			:						int							):






      '''simple docstring'''




      return getattr(self._default  ,    A_							)

 def  __magic_name__							(		self			:						Any  ,    A_			:						int  ,    A_			:						List[Any]=None  ,    A_			:						int=None  ,    A_			:						int=None  ,    **A_			:						Optional[int]							):






      '''simple docstring'''




      return self._default.prepare_inputs_for_generation(
          A_  ,    past_key_values=A_  ,    inputs_embeds=A_  ,    use_cache=A_  ,    **A_							)


 def  __magic_name__							(		self			:						Dict  ,    A_			:						Tuple[Tuple[torch.Tensor]]  ,    A_			:						torch.Tensor							):






      '''simple docstring'''




      return self._default._reorder_cache(A_  ,    A_							)







def 						_snake_case		(     )							->   List[Any]:

     """simple docstring"""







     _lowerCAmelCase :       Any	   =     argparse.ArgumentParser()
     parser.add_argument(
         "--model_type"		,				default=SCREAMING_SNAKE_CASE		,				type=SCREAMING_SNAKE_CASE		,				required=SCREAMING_SNAKE_CASE		,				help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()					)		,				)
     parser.add_argument(
         "--model_name_or_path"		,				default=SCREAMING_SNAKE_CASE		,				type=SCREAMING_SNAKE_CASE		,				required=SCREAMING_SNAKE_CASE		,				help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(MODEL_CLASSES.keys()					)		,				)

     parser.add_argument("--prompt"		,				type=SCREAMING_SNAKE_CASE		,				default=""					)
     parser.add_argument("--length"		,				type=SCREAMING_SNAKE_CASE		,				default=20					)
     parser.add_argument("--stop_token"		,				type=SCREAMING_SNAKE_CASE		,				default=SCREAMING_SNAKE_CASE		,				help="Token at which text generation is stopped"					)

     parser.add_argument(
         "--temperature"		,				type=SCREAMING_SNAKE_CASE		,				default=1.0		,				help="temperature of 1.0 has no effect, lower tend toward greedy sampling"		,				)
     parser.add_argument(
         "--repetition_penalty"		,				type=SCREAMING_SNAKE_CASE		,				default=1.0		,				help="primarily useful for CTRL model; in that case, use 1.2"					)
     parser.add_argument("--k"		,				type=SCREAMING_SNAKE_CASE		,				default=0					)
     parser.add_argument("--p"		,				type=SCREAMING_SNAKE_CASE		,				default=0.9					)

     parser.add_argument("--prefix"		,				type=SCREAMING_SNAKE_CASE		,				default=""		,				help="Text added prior to input."					)
     parser.add_argument("--padding_text"		,				type=SCREAMING_SNAKE_CASE		,				default=""		,				help="Deprecated, the use of `--prefix` is preferred."					)
     parser.add_argument("--xlm_language"		,				type=SCREAMING_SNAKE_CASE		,				default=""		,				help="Optional language when used with the XLM model."					)

     parser.add_argument("--seed"		,				type=SCREAMING_SNAKE_CASE		,				default=42		,				help="random seed for initialization"					)
     parser.add_argument("--no_cuda"		,				action="store_true"		,				help="Avoid using CUDA when available"					)
     parser.add_argument("--num_return_sequences"		,				type=SCREAMING_SNAKE_CASE		,				default=1		,				help="The number of samples to generate."					)
     parser.add_argument(
         "--fp16"		,				action="store_true"		,				help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit"		,				)
     parser.add_argument("--jit"		,				action="store_true"		,				help="Whether or not to use jit trace to accelerate inference"					)
     _lowerCAmelCase :       List[Any]	   =     parser.parse_args()

     _lowerCAmelCase :       Optional[Any]	   =     torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"					)
     _lowerCAmelCase :       Optional[int]	   =     0 if args.no_cuda else torch.cuda.device_count()

     logger.warning(f'''device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}'''					)

     set_seed(SCREAMING_SNAKE_CASE					)

     # Initialize the model and tokenizer
     try:
          _lowerCAmelCase :       Tuple	   =     args.model_type.lower()
          _lowerCAmelCase   ,      _lowerCAmelCase :       List[Any]	   =     MODEL_CLASSES[args.model_type]
     except KeyError:
          raise KeyError("the model {} you specified is not supported. You are welcome to add it and open a PR :)"					)

     _lowerCAmelCase :       Optional[Any]	   =     tokenizer_class.from_pretrained(args.model_name_or_path					)
     if tokenizer.pad_token is None:
          _lowerCAmelCase :       Optional[int]	   =     tokenizer.eos_token
     _lowerCAmelCase :       Optional[Any]	   =     model_class.from_pretrained(args.model_name_or_path					)
     model.to(args.device					)

     if args.fpaa:
          model.half()
     _lowerCAmelCase :       Optional[Any]	   =     getattr(model.config		,				"max_position_embeddings"		,				0					)
     _lowerCAmelCase :       str	   =     adjust_length_to_model(args.length		,				max_sequence_length=SCREAMING_SNAKE_CASE					)
     logger.info(SCREAMING_SNAKE_CASE					)

     _lowerCAmelCase :       Optional[int]	   =     args.prompt if args.prompt else input("Model prompt >>> "					)

     # Different models need different input formatting and/or extra arguments
     _lowerCAmelCase :       Tuple	   =     args.model_type in PREPROCESSING_FUNCTIONS.keys()
     if requires_preprocessing:
          _lowerCAmelCase :       Any	   =     PREPROCESSING_FUNCTIONS.get(args.model_type					)
          _lowerCAmelCase :       Any	   =     prepare_input(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)

          if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
               _lowerCAmelCase :       Optional[Any]	   =     {"add_space_before_punct_symbol": True}
          else:
               _lowerCAmelCase :       List[Any]	   =     {}

          _lowerCAmelCase :       int	   =     tokenizer.encode(
              SCREAMING_SNAKE_CASE		,				add_special_tokens=SCREAMING_SNAKE_CASE		,				return_tensors="pt"		,				**SCREAMING_SNAKE_CASE					)
     else:
          _lowerCAmelCase :       Union[str, Any]	   =     args.prefix if args.prefix else args.padding_text
          _lowerCAmelCase :       Dict	   =     tokenizer.encode(prefix + prompt_text		,				add_special_tokens=SCREAMING_SNAKE_CASE		,				return_tensors="pt"					)
     _lowerCAmelCase :       Union[str, Any]	   =     encoded_prompt.to(args.device					)

     if encoded_prompt.size()[-1] == 0:
          _lowerCAmelCase :       Dict	   =     None
     else:
          _lowerCAmelCase :       Any	   =     encoded_prompt

     if args.jit:
          _lowerCAmelCase :       int	   =     ["enable jit"]
          _lowerCAmelCase :       Union[str, Any]	   =     prepare_jit_inputs(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)
          torch._C._jit_set_texpr_fuser_enabled(SCREAMING_SNAKE_CASE					)
          _lowerCAmelCase :       Optional[int]	   =     False
          if hasattr(SCREAMING_SNAKE_CASE		,				"forward"					):
               _lowerCAmelCase :       int	   =     inspect.signature(model.forward					)
          else:
               _lowerCAmelCase :       Union[str, Any]	   =     inspect.signature(model.__call__					)
          _lowerCAmelCase :       List[str]	   =     tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					) is not None					)
          _lowerCAmelCase :       Optional[Any]	   =     torch.jit.trace(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				strict=SCREAMING_SNAKE_CASE					)
          _lowerCAmelCase :       str	   =     torch.jit.freeze(traced_model.eval()					)
          traced_model(*SCREAMING_SNAKE_CASE					)
          traced_model(*SCREAMING_SNAKE_CASE					)

          _lowerCAmelCase :       str	   =     _ModelFallbackWrapper(SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE					)

     _lowerCAmelCase :       List[str]	   =     model.generate(
         input_ids=SCREAMING_SNAKE_CASE		,				max_length=args.length + len(encoded_prompt[0]					)		,				temperature=args.temperature		,				top_k=args.k		,				top_p=args.p		,				repetition_penalty=args.repetition_penalty		,				do_sample=SCREAMING_SNAKE_CASE		,				num_return_sequences=args.num_return_sequences		,				)

     # Remove the batch dimension when returning multiple sequences
     if len(output_sequences.shape					) > 2:
          output_sequences.squeeze_()

     _lowerCAmelCase :       Union[str, Any]	   =     []

     for generated_sequence_idx, generated_sequence in enumerate(SCREAMING_SNAKE_CASE					):
          print(f'''=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==='''					)
          _lowerCAmelCase :       int	   =     generated_sequence.tolist()

          # Decode text
          _lowerCAmelCase :       Optional[Any]	   =     tokenizer.decode(SCREAMING_SNAKE_CASE		,				clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE					)

          # Remove all text after the stop token
          _lowerCAmelCase :       List[Any]	   =     text[: text.find(args.stop_token					) if args.stop_token else None]

          # Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
          _lowerCAmelCase :       Any	   =     (
              prompt_text + text[len(tokenizer.decode(encoded_prompt[0]		,				clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE					)					) :]
          )

          generated_sequences.append(SCREAMING_SNAKE_CASE					)
          print(SCREAMING_SNAKE_CASE					)

     return generated_sequences


if __name__ == "__main__":
  main()






