






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,
)
__snake_case			:			Optional[Any]			   =   logging.getLogger(__name__)

__snake_case			:			Optional[int]			   =   int(1_00_00)  # Hardcoded max length to avoid infinite loop

__snake_case			:			str			   =   {
    """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
__snake_case			:			Tuple			   =   """In 1991, the remains of Russian Tsar Nicholas II and his family
(except for Alexei and Maria) are discovered.
The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the
remainder of the story. 1883 Western Siberia,
a young Grigori Rasputin is asked by his father and a group of men to perform magic.
Rasputin has a vision and denounces one of the men as a horse thief. Although his
father initially slaps him for making such an accusation, Rasputin watches as the
man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
with people, even a bishop, begging for his blessing. <eod> </s> <eos>"""







def 		_UpperCamelCase      (			UpperCamelCase_				:    List[str]						)     ->      Union[str, 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 		_UpperCamelCase      (			UpperCamelCase_				:    List[str]			,				UpperCamelCase_				:    int			,				UpperCamelCase_				:    Any			,				UpperCamelCase_				:    List[str]						)     ->      Tuple:

						"""simple docstring"""



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

						lowerCAmelCase__			  =  tokenizer.encode(UpperCamelCase_			,				add_special_tokens=UpperCamelCase_						)
						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 		_UpperCamelCase      (			UpperCamelCase_				:    int			,				UpperCamelCase_				:    str			,				UpperCamelCase_				:    List[Any]			,				UpperCamelCase_				:    Optional[Any]						)     ->      Any:

						"""simple docstring"""



						lowerCAmelCase__			  =  hasattr(model.config			,				'use_lang_emb'						) and model.config.use_lang_emb
						if hasattr(model.config			,				'lang2id'						) and use_lang_emb:
												lowerCAmelCase__			  =  model.config.langaid.keys()
												if args.xlm_language in available_languages:
																		lowerCAmelCase__			  =  args.xlm_language
												else:
																		lowerCAmelCase__			  =  None
																		while language not in available_languages:
																								lowerCAmelCase__			  =  input('Using XLM. Select language in ' + str(list(UpperCamelCase_						)						) + ' >>> '						)

												lowerCAmelCase__			  =  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 		_UpperCamelCase      (			UpperCamelCase_				:    Optional[Any]			,				UpperCamelCase_				:    List[Any]			,				UpperCamelCase_				:    Optional[Any]			,				UpperCamelCase_				:    Optional[int]						)     ->      Tuple:

						"""simple docstring"""



						lowerCAmelCase__			  =  args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
						lowerCAmelCase__			  =  prefix + prompt_text
						return prompt_text







def 		_UpperCamelCase      (			UpperCamelCase_				:    Any			,				UpperCamelCase_				:    Union[str, Any]			,				UpperCamelCase_				:    int			,				UpperCamelCase_				:    Any						)     ->      Union[str, Any]:

						"""simple docstring"""



						lowerCAmelCase__			  =  args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
						lowerCAmelCase__			  =  prefix + prompt_text
						return prompt_text


__snake_case			:			Dict			   =   {
    """ctrl""": prepare_ctrl_input,
    """xlm""": prepare_xlm_input,
    """xlnet""": prepare_xlnet_input,
    """transfo-xl""": prepare_transfoxl_input,
}







def 		_UpperCamelCase      (			UpperCamelCase_				:    int			,				UpperCamelCase_				:    Any						)     ->      Any:

						"""simple docstring"""



						if length < 0 and max_sequence_length > 0:
												lowerCAmelCase__			  =  max_sequence_length
						elif 0 < max_sequence_length < length:
												lowerCAmelCase__			  =  max_sequence_length  # No generation bigger than model size
						elif length < 0:
												lowerCAmelCase__			  =  MAX_LENGTH  # avoid infinite loop
						return length







def 		_UpperCamelCase      (			UpperCamelCase_				:    List[str]						)     ->      List[str]:

						"""simple docstring"""



						lowerCAmelCase__			  =  None
						if hasattr(UpperCamelCase_			,				'hidden_size'						):
												lowerCAmelCase__			  =  model_config.hidden_size
						elif hasattr(UpperCamelCase_			,				'n_embed'						):
												lowerCAmelCase__			  =  model_config.n_embed
						elif hasattr(UpperCamelCase_			,				'n_embd'						):
												lowerCAmelCase__			  =  model_config.n_embd

						lowerCAmelCase__			  =  None
						if hasattr(UpperCamelCase_			,				'num_attention_heads'						):
												lowerCAmelCase__			  =  model_config.num_attention_heads
						elif hasattr(UpperCamelCase_			,				'n_head'						):
												lowerCAmelCase__			  =  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__			  =  int(embedding_size / num_head						)
						if hasattr(UpperCamelCase_			,				'n_layer'						):
												lowerCAmelCase__			  =  model_config.n_layer
						elif hasattr(UpperCamelCase_			,				'num_hidden_layers'						):
												lowerCAmelCase__			  =  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 		_UpperCamelCase      (			UpperCamelCase_				:    Dict			,				UpperCamelCase_				:    str			,				UpperCamelCase_				:    int						)     ->      Optional[Any]:

						"""simple docstring"""



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







def 		_UpperCamelCase      (			UpperCamelCase_				:    Tuple			,				UpperCamelCase_				:    Tuple			,				UpperCamelCase_				:    str						)     ->      Optional[Any]:

						"""simple docstring"""



						lowerCAmelCase__			  =  len(UpperCamelCase_						)
						lowerCAmelCase__			  =  tokenizer.batch_encode_plus(UpperCamelCase_			,				return_tensors='pt'						)
						lowerCAmelCase__			  =  dummy_input.to(model.device						)
						if model.config.use_cache:
												lowerCAmelCase__			  =  generate_past_key_values(UpperCamelCase_			,				UpperCamelCase_			,				1						)
						lowerCAmelCase__			  =  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 			__SCREAMING_SNAKE_CASE    (      __lowercase):
						_SCREAMING_SNAKE_CASE		:				Optional[int]            =    ('''_optimized''', '''_default''')






						def __init__(		self   ,  _UpperCamelCase   ,  _UpperCamelCase      ):






												"""simple docstring"""
												lowerCAmelCase__			  =  optimized
												lowerCAmelCase__			  =  default






						def __call__(		self   ,  *_UpperCamelCase   ,  **_UpperCamelCase      ):






												"""simple docstring"""
												if kwargs["past_key_values"] is None and self._default.config.use_cache:
																		lowerCAmelCase__			  =  generate_past_key_values(self._default   ,  kwargs['input_ids'].shape[0]   ,  0      )
												kwargs.pop('position_ids'   ,  _UpperCamelCase      )
												for k in list(kwargs.keys()      ):
																		if kwargs[k] is None or isinstance(kwargs[k]   ,  _UpperCamelCase      ):
																								kwargs.pop(_UpperCamelCase      )
												lowerCAmelCase__			  =  self._optimized(**_UpperCamelCase      )
												lowerCAmelCase__			  =  outputs[0]
												lowerCAmelCase__			  =  outputs[1]
												lowerCAmelCase__			  =  CausalLMOutputWithPast(
												    loss=_UpperCamelCase   ,  logits=_UpperCamelCase   ,  past_key_values=_UpperCamelCase   ,  hidden_states=_UpperCamelCase   ,  attentions=_UpperCamelCase   ,  )
												return fixed_output






						def __getattr__(		self   ,  _UpperCamelCase      ):






												"""simple docstring"""
												return getattr(self._default   ,  _UpperCamelCase      )






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase=None   ,  _UpperCamelCase=None   ,  _UpperCamelCase=None   ,  **_UpperCamelCase      ):






												"""simple docstring"""
												return self._default.prepare_inputs_for_generation(
												    _UpperCamelCase   ,  past_key_values=_UpperCamelCase   ,  inputs_embeds=_UpperCamelCase   ,  use_cache=_UpperCamelCase   ,  **_UpperCamelCase      )







						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase      ):






												"""simple docstring"""
												return self._default._reorder_cache(_UpperCamelCase   ,  _UpperCamelCase      )







def 		_UpperCamelCase      (			)     ->      Optional[int]:

						"""simple docstring"""



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

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

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

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

						parser.add_argument('--seed'			,				type=UpperCamelCase_			,				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=UpperCamelCase_			,				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__			  =  parser.parse_args()

						lowerCAmelCase__			  =  torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu'						)
						lowerCAmelCase__			  =  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(UpperCamelCase_						)

						# Initialize the model and tokenizer
						try:
												lowerCAmelCase__			  =  args.model_type.lower()
												lowerCAmelCase__  ,				lowerCAmelCase__			  =  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__			  =  tokenizer_class.from_pretrained(args.model_name_or_path						)
						if tokenizer.pad_token is None:
												lowerCAmelCase__			  =  tokenizer.eos_token
						lowerCAmelCase__			  =  model_class.from_pretrained(args.model_name_or_path						)
						model.to(args.device						)

						if args.fpaa:
												model.half()
						lowerCAmelCase__			  =  getattr(model.config			,				'max_position_embeddings'			,				0						)
						lowerCAmelCase__			  =  adjust_length_to_model(args.length			,				max_sequence_length=UpperCamelCase_						)
						logger.info(UpperCamelCase_						)

						lowerCAmelCase__			  =  args.prompt if args.prompt else input('Model prompt >>> '						)

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

												if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
																		lowerCAmelCase__			  =  {'add_space_before_punct_symbol': True}
												else:
																		lowerCAmelCase__			  =  {}

												lowerCAmelCase__			  =  tokenizer.encode(
												    UpperCamelCase_			,				add_special_tokens=UpperCamelCase_			,				return_tensors='pt'			,				**UpperCamelCase_						)
						else:
												lowerCAmelCase__			  =  args.prefix if args.prefix else args.padding_text
												lowerCAmelCase__			  =  tokenizer.encode(prefix + prompt_text			,				add_special_tokens=UpperCamelCase_			,				return_tensors='pt'						)
						lowerCAmelCase__			  =  encoded_prompt.to(args.device						)

						if encoded_prompt.size()[-1] == 0:
												lowerCAmelCase__			  =  None
						else:
												lowerCAmelCase__			  =  encoded_prompt

						if args.jit:
												lowerCAmelCase__			  =  ['enable jit']
												lowerCAmelCase__			  =  prepare_jit_inputs(UpperCamelCase_			,				UpperCamelCase_			,				UpperCamelCase_						)
												torch._C._jit_set_texpr_fuser_enabled(UpperCamelCase_						)
												lowerCAmelCase__			  =  False
												if hasattr(UpperCamelCase_			,				'forward'						):
																		lowerCAmelCase__			  =  inspect.signature(model.forward						)
												else:
																		lowerCAmelCase__			  =  inspect.signature(model.__call__						)
												lowerCAmelCase__			  =  tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(UpperCamelCase_			,				UpperCamelCase_						) is not None						)
												lowerCAmelCase__			  =  torch.jit.trace(UpperCamelCase_			,				UpperCamelCase_			,				strict=UpperCamelCase_						)
												lowerCAmelCase__			  =  torch.jit.freeze(traced_model.eval()						)
												traced_model(*UpperCamelCase_						)
												traced_model(*UpperCamelCase_						)

												lowerCAmelCase__			  =  _ModelFallbackWrapper(UpperCamelCase_			,				UpperCamelCase_						)

						lowerCAmelCase__			  =  model.generate(
						    input_ids=UpperCamelCase_			,				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=UpperCamelCase_			,				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__			  =  []

						for generated_sequence_idx, generated_sequence in enumerate(UpperCamelCase_						):
												print(F"=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==="						)
												lowerCAmelCase__			  =  generated_sequence.tolist()

												# Decode text
												lowerCAmelCase__			  =  tokenizer.decode(UpperCamelCase_			,				clean_up_tokenization_spaces=UpperCamelCase_						)

												# Remove all text after the stop token
												lowerCAmelCase__			  =  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__			  =  (
												    prompt_text + text[len(tokenizer.decode(encoded_prompt[0]			,				clean_up_tokenization_spaces=UpperCamelCase_						)						) :]
												)

												generated_sequences.append(UpperCamelCase_						)
												print(UpperCamelCase_						)

						return generated_sequences


if __name__ == "__main__":
					main()













import csv
import dataclasses
import json
from dataclasses import dataclass
from typing import List, Optional, Union

from ...utils import is_tf_available, is_torch_available, logging


__snake_case			:			Union[str, Any]			   =   logging.get_logger(__name__)


@dataclass
class 			__SCREAMING_SNAKE_CASE    :
						_SCREAMING_SNAKE_CASE		:				str
						_SCREAMING_SNAKE_CASE		:				str
						_SCREAMING_SNAKE_CASE		:				Optional[str]            =    None
						_SCREAMING_SNAKE_CASE		:				Optional[str]            =    None






						def 					UpperCamelCase__					(		self      ):






												"""simple docstring"""
												return json.dumps(dataclasses.asdict(self      )   ,  indent=2      ) + "\n"




@dataclass(frozen=__lowercase)
class 			__SCREAMING_SNAKE_CASE    :
						_SCREAMING_SNAKE_CASE		:				List[int]
						_SCREAMING_SNAKE_CASE		:				Optional[List[int]]            =    None
						_SCREAMING_SNAKE_CASE		:				Optional[List[int]]            =    None
						_SCREAMING_SNAKE_CASE		:				Optional[Union[int, float]]            =    None






						def 					UpperCamelCase__					(		self      ):






												"""simple docstring"""
												return json.dumps(dataclasses.asdict(self      )      ) + "\n"




class 			__SCREAMING_SNAKE_CASE    :






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase      ):






												"""simple docstring"""
												raise NotImplementedError()






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase      ):






												"""simple docstring"""
												raise NotImplementedError()






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase      ):






												"""simple docstring"""
												raise NotImplementedError()






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase      ):






												"""simple docstring"""
												raise NotImplementedError()






						def 					UpperCamelCase__					(		self      ):






												"""simple docstring"""
												raise NotImplementedError()






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase      ):






												"""simple docstring"""
												if len(self.get_labels()      ) > 1:
																		lowerCAmelCase__			  =  self.get_labels()[int(example.label      )]
												return example







						@classmethod
						def 					UpperCamelCase__					(		cls   ,  _UpperCamelCase   ,  _UpperCamelCase=None      ):






												"""simple docstring"""
												with open(_UpperCamelCase   ,  'r'   ,  encoding='utf-8-sig'      ) as f:
																		return list(csv.reader(_UpperCamelCase   ,  delimiter='\t'   ,  quotechar=_UpperCamelCase      )      )




class 			__SCREAMING_SNAKE_CASE    (      __lowercase):






						def __init__(		self   ,  _UpperCamelCase=None   ,  _UpperCamelCase=None   ,  _UpperCamelCase="classification"   ,  _UpperCamelCase=False      ):






												"""simple docstring"""
												lowerCAmelCase__			  =  [] if labels is None else labels
												lowerCAmelCase__			  =  [] if examples is None else examples
												lowerCAmelCase__			  =  mode
												lowerCAmelCase__			  =  verbose






						def __len__(		self      ):






												"""simple docstring"""
												return len(self.examples      )






						def __getitem__(		self   ,  _UpperCamelCase      ):






												"""simple docstring"""
												if isinstance(_UpperCamelCase   ,  _UpperCamelCase      ):
																		return SingleSentenceClassificationProcessor(labels=self.labels   ,  examples=self.examples[idx]      )
												return self.examples[idx]






						@classmethod
						def 					UpperCamelCase__					(		cls   ,  _UpperCamelCase   ,  _UpperCamelCase=""   ,  _UpperCamelCase=0   ,  _UpperCamelCase=1   ,  _UpperCamelCase=None   ,  _UpperCamelCase=False   ,  **_UpperCamelCase      ):






												"""simple docstring"""
												lowerCAmelCase__			  =  cls(**_UpperCamelCase      )
												processor.add_examples_from_csv(
												    _UpperCamelCase   ,  split_name=_UpperCamelCase   ,  column_label=_UpperCamelCase   ,  column_text=_UpperCamelCase   ,  column_id=_UpperCamelCase   ,  skip_first_row=_UpperCamelCase   ,  overwrite_labels=_UpperCamelCase   ,  overwrite_examples=_UpperCamelCase   ,  )
												return processor






						@classmethod
						def 					UpperCamelCase__					(		cls   ,  _UpperCamelCase   ,  _UpperCamelCase=None   ,  **_UpperCamelCase      ):






												"""simple docstring"""
												lowerCAmelCase__			  =  cls(**_UpperCamelCase      )
												processor.add_examples(_UpperCamelCase   ,  labels=_UpperCamelCase      )
												return processor






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase=""   ,  _UpperCamelCase=0   ,  _UpperCamelCase=1   ,  _UpperCamelCase=None   ,  _UpperCamelCase=False   ,  _UpperCamelCase=False   ,  _UpperCamelCase=False   ,  ):






												"""simple docstring"""
												lowerCAmelCase__			  =  self._read_tsv(_UpperCamelCase      )
												if skip_first_row:
																		lowerCAmelCase__			  =  lines[1:]
												lowerCAmelCase__			  =  []
												lowerCAmelCase__			  =  []
												lowerCAmelCase__			  =  []
												for i, line in enumerate(_UpperCamelCase      ):
																		texts.append(line[column_text]      )
																		labels.append(line[column_label]      )
																		if column_id is not None:
																								ids.append(line[column_id]      )
																		else:
																								lowerCAmelCase__			  =  F"{split_name}-{i}" if split_name else str(_UpperCamelCase      )
																								ids.append(_UpperCamelCase      )

												return self.add_examples(
												    _UpperCamelCase   ,  _UpperCamelCase   ,  _UpperCamelCase   ,  overwrite_labels=_UpperCamelCase   ,  overwrite_examples=_UpperCamelCase      )






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase=None   ,  _UpperCamelCase=None   ,  _UpperCamelCase=False   ,  _UpperCamelCase=False      ):






												"""simple docstring"""
												if labels is not None and len(_UpperCamelCase      ) != len(_UpperCamelCase      ):
																		raise ValueError(
																		    F"Text and labels have mismatched lengths {len(_UpperCamelCase      )} and {len(_UpperCamelCase      )}"      )
												if ids is not None and len(_UpperCamelCase      ) != len(_UpperCamelCase      ):
																		raise ValueError(F"Text and ids have mismatched lengths {len(_UpperCamelCase      )} and {len(_UpperCamelCase      )}"      )
												if ids is None:
																		lowerCAmelCase__			  =  [None] * len(_UpperCamelCase      )
												if labels is None:
																		lowerCAmelCase__			  =  [None] * len(_UpperCamelCase      )
												lowerCAmelCase__			  =  []
												lowerCAmelCase__			  =  set()
												for text_or_text_and_label, label, guid in zip(_UpperCamelCase   ,  _UpperCamelCase   ,  _UpperCamelCase      ):
																		if isinstance(_UpperCamelCase   ,  (tuple, list)      ) and label is None:
																								lowerCAmelCase__  ,				lowerCAmelCase__			  =  text_or_text_and_label
																		else:
																								lowerCAmelCase__			  =  text_or_text_and_label
																		added_labels.add(_UpperCamelCase      )
																		examples.append(InputExample(guid=_UpperCamelCase   ,  text_a=_UpperCamelCase   ,  text_b=_UpperCamelCase   ,  label=_UpperCamelCase      )      )

												# Update examples
												if overwrite_examples:
																		lowerCAmelCase__			  =  examples
												else:
																		self.examples.extend(_UpperCamelCase      )

												# Update labels
												if overwrite_labels:
																		lowerCAmelCase__			  =  list(_UpperCamelCase      )
												else:
																		lowerCAmelCase__			  =  list(set(self.labels      ).union(_UpperCamelCase      )      )

												return self.examples







						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase=None   ,  _UpperCamelCase=False   ,  _UpperCamelCase=0   ,  _UpperCamelCase=True   ,  _UpperCamelCase=None   ,  ):






												"""simple docstring"""
												if max_length is None:
																		lowerCAmelCase__			  =  tokenizer.max_len

												lowerCAmelCase__			  =  {label: i for i, label in enumerate(self.labels      )}

												lowerCAmelCase__			  =  []
												for ex_index, example in enumerate(self.examples      ):
																		if ex_index % 1_00_00 == 0:
																								logger.info(F"Tokenizing example {ex_index}"      )

																		lowerCAmelCase__			  =  tokenizer.encode(
																		    example.text_a   ,  add_special_tokens=_UpperCamelCase   ,  max_length=min(_UpperCamelCase   ,  tokenizer.max_len      )   ,  )
																		all_input_ids.append(_UpperCamelCase      )

												lowerCAmelCase__			  =  max(len(_UpperCamelCase      ) for input_ids in all_input_ids      )

												lowerCAmelCase__			  =  []
												for ex_index, (input_ids, example) in enumerate(zip(_UpperCamelCase   ,  self.examples      )      ):
																		if ex_index % 1_00_00 == 0:
																								logger.info(F"Writing example {ex_index}/{len(self.examples      )}"      )
																		# The mask has 1 for real tokens and 0 for padding tokens. Only real
																		# tokens are attended to.
																		lowerCAmelCase__			  =  [1 if mask_padding_with_zero else 0] * len(_UpperCamelCase      )

																		# Zero-pad up to the sequence length.
																		lowerCAmelCase__			  =  batch_length - len(_UpperCamelCase      )
																		if pad_on_left:
																								lowerCAmelCase__			  =  ([pad_token] * padding_length) + input_ids
																								lowerCAmelCase__			  =  ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
																		else:
																								lowerCAmelCase__			  =  input_ids + ([pad_token] * padding_length)
																								lowerCAmelCase__			  =  attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)

																		if len(_UpperCamelCase      ) != batch_length:
																								raise ValueError(F"Error with input length {len(_UpperCamelCase      )} vs {batch_length}"      )
																		if len(_UpperCamelCase      ) != batch_length:
																								raise ValueError(F"Error with input length {len(_UpperCamelCase      )} vs {batch_length}"      )

																		if self.mode == "classification":
																								lowerCAmelCase__			  =  label_map[example.label]
																		elif self.mode == "regression":
																								lowerCAmelCase__			  =  float(example.label      )
																		else:
																								raise ValueError(self.mode      )

																		if ex_index < 5 and self.verbose:
																								logger.info('*** Example ***'      )
																								logger.info(F"guid: {example.guid}"      )
																								logger.info(F"input_ids: {' '.join([str(_UpperCamelCase      ) for x in input_ids]      )}"      )
																								logger.info(F"attention_mask: {' '.join([str(_UpperCamelCase      ) for x in attention_mask]      )}"      )
																								logger.info(F"label: {example.label} (id = {label})"      )

																		features.append(InputFeatures(input_ids=_UpperCamelCase   ,  attention_mask=_UpperCamelCase   ,  label=_UpperCamelCase      )      )

												if return_tensors is None:
																		return features
												elif return_tensors == "tf":
																		if not is_tf_available():
																								raise RuntimeError('return_tensors set to \'tf\' but TensorFlow 2.0 can\'t be imported'      )
																		import tensorflow as tf

																		def gen():
																								for ex in features:
																														yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)

																		lowerCAmelCase__			  =  tf.data.Dataset.from_generator(
																		    _UpperCamelCase   ,  ({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa)   ,  ({'input_ids': tf.TensorShape([None]      ), 'attention_mask': tf.TensorShape([None]      )}, tf.TensorShape([]      ))   ,  )
																		return dataset
												elif return_tensors == "pt":
																		if not is_torch_available():
																								raise RuntimeError('return_tensors set to \'pt\' but PyTorch can\'t be imported'      )
																		import torch
																		from torch.utils.data import TensorDataset

																		lowerCAmelCase__			  =  torch.tensor([f.input_ids for f in features]   ,  dtype=torch.long      )
																		lowerCAmelCase__			  =  torch.tensor([f.attention_mask for f in features]   ,  dtype=torch.long      )
																		if self.mode == "classification":
																								lowerCAmelCase__			  =  torch.tensor([f.label for f in features]   ,  dtype=torch.long      )
																		elif self.mode == "regression":
																								lowerCAmelCase__			  =  torch.tensor([f.label for f in features]   ,  dtype=torch.float      )

																		lowerCAmelCase__			  =  TensorDataset(_UpperCamelCase   ,  _UpperCamelCase   ,  _UpperCamelCase      )
																		return dataset
												else:
																		raise ValueError('return_tensors should be one of \'tf\' or \'pt\''      )





