



import json
import logging
import os
import sys
from pathlib import Path

import finetune_rag

from transformers.file_utils import is_apex_available
from transformers.testing_utils import (
    TestCasePlus,
    execute_subprocess_async,
    require_ray,
    require_torch_gpu,
    require_torch_multi_gpu,
)


logging.basicConfig(level=logging.DEBUG)
SCREAMING_SNAKE_CASE__       =      logging.getLogger()

SCREAMING_SNAKE_CASE__       =      logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)


class      __lowerCAmelCase     (		UpperCAmelCase_      ):
					"""simple docstring"""






					def     _a							(     self					:       Optional[int]				,					_snake_case					:       int					):






								"""simple docstring"""


								os.makedirs(_snake_case				,					exist_ok=_snake_case					)
								A__       =    {'source': 'What is love ?', 'target': 'life'}
								A__       =    {'train': 12, 'val': 2, 'test': 2}
								for split in ["train", "test", "val"]:
											for field in ["source", "target"]:
														A__       =    '\n'.join([contents[field]] * n_lines[split]					)
														with open(os.path.join(_snake_case				,					F'''{split}.{field}'''					)				,					'w'					) as f:
																	f.write(_snake_case					)



					def     _a							(     self					:       Union[str, Any]				,					_snake_case					:       int				,					_snake_case					:       str = "pytorch"					):






								"""simple docstring"""


								A__       =    self.get_auto_remove_tmp_dir()
								A__       =    os.path.join(_snake_case				,					'output'					)
								A__       =    os.path.join(_snake_case				,					'data'					)
								self._create_dummy_data(data_dir=_snake_case					)

								A__       =    F'''
                --data_dir {data_dir} \
                --output_dir {output_dir} \
                --model_name_or_path facebook/rag-sequence-base \
                --model_type rag_sequence \
                --do_train \
                --do_predict \
                --n_val -1 \
                --val_check_interval 1.0 \
                --train_batch_size 2 \
                --eval_batch_size 1 \
                --max_source_length 25 \
                --max_target_length 25 \
                --val_max_target_length 25 \
                --test_max_target_length 25 \
                --label_smoothing 0.1 \
                --dropout 0.1 \
                --attention_dropout 0.1 \
                --weight_decay 0.001 \
                --adam_epsilon 1e-08 \
                --max_grad_norm 0.1 \
                --lr_scheduler polynomial \
                --learning_rate 3e-04 \
                --num_train_epochs 1 \
                --warmup_steps 4 \
                --gradient_accumulation_steps 1 \
                --distributed-port 8787 \
                --use_dummy_dataset 1 \
                --distributed_retriever {distributed_retriever} \
            '''.split()

								if gpus > 0:
											testargs.append(F'''--gpus={gpus}'''					)
											if is_apex_available():
														testargs.append('--fp16'					)
								else:
											testargs.append('--gpus=0'					)
											testargs.append('--distributed_backend=ddp_cpu'					)
											testargs.append('--num_processes=2'					)

								A__       =    [sys.executable, str(Path(finetune_rag.__file__					).resolve()					)] + testargs
								execute_subprocess_async(_snake_case				,					env=self.get_env()					)

								A__       =    os.path.join(_snake_case				,					'metrics.json'					)
								with open(_snake_case					) as f:
											A__       =    json.load(_snake_case					)
								return result



					@require_torch_gpu
					def     _a							(     self					:       Dict					):






								"""simple docstring"""


								A__       =    self._run_finetune(gpus=1					)
								self.assertGreaterEqual(result['test'][0]['test_avg_em']				,					0.2					)



					@require_torch_multi_gpu
					def     _a							(     self					:       Tuple					):






								"""simple docstring"""


								A__       =    self._run_finetune(gpus=2					)
								self.assertGreaterEqual(result['test'][0]['test_avg_em']				,					0.2					)



					@require_torch_gpu
					@require_ray
					def     _a							(     self					:       List[Any]					):






								"""simple docstring"""


								A__       =    self._run_finetune(gpus=1				,					distributed_retriever='ray'					)
								self.assertGreaterEqual(result['test'][0]['test_avg_em']				,					0.2					)



					@require_torch_multi_gpu
					@require_ray
					def     _a							(     self					:       Optional[int]					):






								"""simple docstring"""


								A__       =    self._run_finetune(gpus=1				,					distributed_retriever='ray'					)
								self.assertGreaterEqual(result['test'][0]['test_avg_em']				,					0.2					)









from typing import Dict

from .base import GenericTensor, Pipeline


class      __lowerCAmelCase     (		UpperCAmelCase_      ):
					"""simple docstring"""






					def     _a							(     self					:       Any				,					_snake_case					:       str=None				,					_snake_case					:       Dict=None				,					_snake_case					:       Any=None				,					**_snake_case					:       str					):






								"""simple docstring"""


								if tokenize_kwargs is None:
											A__       =    {}

								if truncation is not None:
											if "truncation" in tokenize_kwargs:
														raise ValueError(
														    'truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)'					)
											A__       =    truncation

								A__       =    tokenize_kwargs

								A__       =    {}
								if return_tensors is not None:
											A__       =    return_tensors

								return preprocess_params, {}, postprocess_params



					def     _a							(     self					:       Any				,					_snake_case					:       Dict				,					**_snake_case					:       Optional[Any]					):






								"""simple docstring"""


								A__       =    self.framework
								A__       =    self.tokenizer(_snake_case				,					return_tensors=_snake_case				,					**_snake_case					)
								return model_inputs



					def     _a							(     self					:       List[Any]				,					_snake_case					:       Dict					):






								"""simple docstring"""


								A__       =    self.model(**_snake_case					)
								return model_outputs



					def     _a							(     self					:       Optional[Any]				,					_snake_case					:       List[Any]				,					_snake_case					:       str=False					):






								"""simple docstring"""


								if return_tensors:
											return model_outputs[0]
								if self.framework == "pt":
											return model_outputs[0].tolist()
								elif self.framework == "tf":
											return model_outputs[0].numpy().tolist()



					def __call__(     self					:       Dict				,					*_snake_case					:       int				,					**_snake_case					:       List[str]					):






								"""simple docstring"""


								return super().__call__(*_snake_case				,					**_snake_case					)




