



import copy

from ...configuration_utils import PretrainedConfig
from ...utils import add_start_docstrings


UpperCAmelCase							 =					R"""
    [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and
    can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.

    Args:
        title_sep (`str`, *optional*, defaults to  `\" / \"`):
            Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].
        doc_sep (`str`, *optional*, defaults to  `\" // \"`):
            Separator inserted between the text of the retrieved document and the original input when calling
            [`RagRetriever`].
        n_docs (`int`, *optional*, defaults to 5):
            Number of documents to retrieve.
        max_combined_length (`int`, *optional*, defaults to 300):
            Max length of contextualized input returned by [`~RagRetriever.__call__`].
        retrieval_vector_size (`int`, *optional*, defaults to 768):
            Dimensionality of the document embeddings indexed by [`RagRetriever`].
        retrieval_batch_size (`int`, *optional*, defaults to 8):
            Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated
            [`RagRetriever`].
        dataset (`str`, *optional*, defaults to `\"wiki_dpr\"`):
            A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids
            using `datasets.list_datasets()`).
        dataset_split (`str`, *optional*, defaults to `\"train\"`)
            Which split of the `dataset` to load.
        index_name (`str`, *optional*, defaults to `\"compressed\"`)
            The index name of the index associated with the `dataset`. One can choose between `\"legacy\"`, `\"exact\"` and
            `\"compressed\"`.
        index_path (`str`, *optional*)
            The path to the serialized faiss index on disk.
        passages_path (`str`, *optional*):
            A path to text passages compatible with the faiss index. Required if using
            [`~models.rag.retrieval_rag.LegacyIndex`]
        use_dummy_dataset (`bool`, *optional*, defaults to `False`)
            Whether to load a \"dummy\" variant of the dataset specified by `dataset`.
        label_smoothing (`float`, *optional*, defaults to 0.0):
            Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing
            in the loss calculation. If set to 0, no label smoothing is performed.
        do_marginalize (`bool`, *optional*, defaults to `False`):
            If `True`, the logits are marginalized over all documents by making use of
            `torch.nn.functional.log_softmax`.
        reduce_loss (`bool`, *optional*, defaults to `False`):
            Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.
        do_deduplication (`bool`, *optional*, defaults to `True`):
            Whether or not to deduplicate the generations from different context documents for a given input. Has to be
            set to `False` if used while training with distributed backend.
        exclude_bos_score (`bool`, *optional*, defaults to `False`):
            Whether or not to disregard the BOS token when computing the loss.
        output_retrieved(`bool`, *optional*, defaults to `False`):
            If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
            `context_attention_mask` are returned. See returned tensors for more detail.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models).
        forced_eos_token_id (`int`, *optional*):
            The id of the token to force as the last generated token when `max_length` is reached. Usually set to
            `eos_token_id`.
"""

@add_start_docstrings(SCREAMING_SNAKE_CASE)
class  __snake_case      (   SCREAMING_SNAKE_CASE):







							'''simple docstring'''






							UpperCamelCase__				:      Union[str, Any]         =					'rag'
							UpperCamelCase__				:      Optional[int]         =					True


							def __init__(							self  ,  a_=None  ,  a_=True  ,  a_=None  ,  a_=None  ,  a_=None  ,  a_=None  ,  a_=None  ,  a_=" / "  ,  a_=" // "  ,  a_=5  ,  a_=300  ,  a_=768  ,  a_=8  ,  a_="wiki_dpr"  ,  a_="train"  ,  a_="compressed"  ,  a_=None  ,  a_=None  ,  a_=False  ,  a_=False  ,  a_=0.0  ,  a_=True  ,  a_=False  ,  a_=False  ,  a_=False  ,  a_=True  ,  a_=None  ,  **a_  ,  ):
											super().__init__(
											    bos_token_id=a_  ,  pad_token_id=a_  ,  eos_token_id=a_  ,  decoder_start_token_id=a_  ,  forced_eos_token_id=a_  ,  is_encoder_decoder=a_  ,  prefix=a_  ,  vocab_size=a_  ,  **a_  ,  )
											assert (
											    "question_encoder" in kwargs and "generator" in kwargs
											), "Config has to be initialized with question_encoder and generator config"
											a__				      =		kwargs.pop("""question_encoder"""		)
											a__				      =		question_encoder_config.pop("""model_type"""		)
											a__				      =		kwargs.pop("""generator"""		)
											a__				      =		decoder_config.pop("""model_type"""		)

											from ..auto.configuration_auto import AutoConfig

											a__				      =		AutoConfig.for_model(a_  ,  **a_		)
											a__				      =		AutoConfig.for_model(a_  ,  **a_		)

											a__				      =		reduce_loss
											a__				      =		label_smoothing
											a__				      =		exclude_bos_score
											a__				      =		do_marginalize

											a__				      =		title_sep
											a__				      =		doc_sep
											a__				      =		n_docs
											a__				      =		max_combined_length

											a__				      =		dataset
											a__				      =		dataset_split
											a__				      =		index_name

											a__				      =		retrieval_vector_size
											a__				      =		retrieval_batch_size
											a__				      =		passages_path
											a__				      =		index_path
											a__				      =		use_dummy_dataset

											a__				      =		output_retrieved

											a__				      =		do_deduplication

											a__				      =		use_cache

											if self.forced_eos_token_id is None:
															a__				      =		getattr(self.generator  ,  """forced_eos_token_id"""  ,  a_		)


							@classmethod
							def _a      (							cls  ,  a_  ,  a_  ,  **a_		):
											return cls(question_encoder=question_encoder_config.to_dict()  ,  generator=generator_config.to_dict()  ,  **a_		)







							def _a      (							self		):
											a__				      =		copy.deepcopy(self.__dict__		)
											a__				      =		self.question_encoder.to_dict()
											a__				      =		self.generator.to_dict()
											a__				      =		self.__class__.model_type
											return output






import os
from argparse import ArgumentParser, Namespace

from ..data import SingleSentenceClassificationProcessor as Processor
from ..pipelines import TextClassificationPipeline
from ..utils import is_tf_available, is_torch_available, logging
from . import BaseTransformersCLICommand


if not is_tf_available() and not is_torch_available():
	raise RuntimeError("""At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training""")

# TF training parameters
UpperCAmelCase							 =					False
UpperCAmelCase							 =					False

def 			A_      (	__a     :				Namespace		):

				"""simple docstring"""
				return TrainCommand(__a		)




class  __snake_case      (   SCREAMING_SNAKE_CASE):







							'''simple docstring'''






							@staticmethod
							def _a      (							a_		):
											a__				      =		parser.add_parser("""train"""  ,  help="""CLI tool to train a model on a task."""		)

											train_parser.add_argument(
											    """--train_data"""  ,  type=a_  ,  required=a_  ,  help="""path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences."""  ,  )
											train_parser.add_argument(
											    """--column_label"""  ,  type=a_  ,  default=0  ,  help="""Column of the dataset csv file with example labels."""		)
											train_parser.add_argument(
											    """--column_text"""  ,  type=a_  ,  default=1  ,  help="""Column of the dataset csv file with example texts."""		)
											train_parser.add_argument(
											    """--column_id"""  ,  type=a_  ,  default=2  ,  help="""Column of the dataset csv file with example ids."""		)
											train_parser.add_argument(
											    """--skip_first_row"""  ,  action="""store_true"""  ,  help="""Skip the first row of the csv file (headers)."""		)

											train_parser.add_argument("""--validation_data"""  ,  type=a_  ,  default=""""""  ,  help="""path to validation dataset."""		)
											train_parser.add_argument(
											    """--validation_split"""  ,  type=a_  ,  default=0.1  ,  help="""if validation dataset is not provided, fraction of train dataset to use as validation dataset."""  ,  )

											train_parser.add_argument("""--output"""  ,  type=a_  ,  default="""./"""  ,  help="""path to saved the trained model."""		)

											train_parser.add_argument(
											    """--task"""  ,  type=a_  ,  default="""text_classification"""  ,  help="""Task to train the model on."""		)
											train_parser.add_argument(
											    """--model"""  ,  type=a_  ,  default="""bert-base-uncased"""  ,  help="""Model's name or path to stored model."""		)
											train_parser.add_argument("""--train_batch_size"""  ,  type=a_  ,  default=32  ,  help="""Batch size for training."""		)
											train_parser.add_argument("""--valid_batch_size"""  ,  type=a_  ,  default=64  ,  help="""Batch size for validation."""		)
											train_parser.add_argument("""--learning_rate"""  ,  type=a_  ,  default=3E-5  ,  help="""Learning rate."""		)
											train_parser.add_argument("""--adam_epsilon"""  ,  type=a_  ,  default=1E-0_8  ,  help="""Epsilon for Adam optimizer."""		)
											train_parser.set_defaults(func=a_		)


							def __init__(							self  ,  a_		):
											a__				      =		logging.get_logger("""transformers-cli/training"""		)

											a__				      =		"""tf""" if is_tf_available() else """torch"""

											os.makedirs(args.output  ,  exist_ok=a_		)
											a__				      =		args.output

											a__				      =		args.column_label
											a__				      =		args.column_text
											a__				      =		args.column_id

											self.logger.info(F'''Loading {args.task} pipeline for {args.model}'''		)
											if args.task == "text_classification":
															a__				      =		TextClassificationPipeline.from_pretrained(args.model		)
											elif args.task == "token_classification":
															raise NotImplementedError
											elif args.task == "question_answering":
															raise NotImplementedError

											self.logger.info(F'''Loading dataset from {args.train_data}'''		)
											a__				      =		Processor.create_from_csv(
											    args.train_data  ,  column_label=args.column_label  ,  column_text=args.column_text  ,  column_id=args.column_id  ,  skip_first_row=args.skip_first_row  ,  )
											a__				      =		None
											if args.validation_data:
															self.logger.info(F'''Loading validation dataset from {args.validation_data}'''		)
															a__				      =		Processor.create_from_csv(
															    args.validation_data  ,  column_label=args.column_label  ,  column_text=args.column_text  ,  column_id=args.column_id  ,  skip_first_row=args.skip_first_row  ,  )

											a__				      =		args.validation_split
											a__				      =		args.train_batch_size
											a__				      =		args.valid_batch_size
											a__				      =		args.learning_rate
											a__				      =		args.adam_epsilon


							def _a      (							self		):
											if self.framework == "tf":
															return self.run_tf()
											return self.run_torch()


							def _a      (							self		):
											raise NotImplementedError







							def _a      (							self		):
											self.pipeline.fit(
											    self.train_dataset  ,  validation_data=self.valid_dataset  ,  validation_split=self.validation_split  ,  learning_rate=self.learning_rate  ,  adam_epsilon=self.adam_epsilon  ,  train_batch_size=self.train_batch_size  ,  valid_batch_size=self.valid_batch_size  ,  )

											# Save trained pipeline
											self.pipeline.save_pretrained(self.output		)

