






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)
__UpperCamelCase   :   Tuple      =    logging.getLogger()

__UpperCamelCase   :   str      =    logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)


class 							__UpperCamelCase     (  _lowerCAmelCase ):







	def 			_a (	self   :				Tuple							,					_lowerCAmelCase   :				Optional[int]      )		->			int:
		"""simple docstring"""







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







	def 			_a (	self   :				Tuple							,					_lowerCAmelCase   :				int							,					_lowerCAmelCase   :				str = "pytorch"      )		->			int:
		"""simple docstring"""







		__lowercase   							=	self.get_auto_remove_tmp_dir()
		__lowercase   							=	os.path.join(_lowerCAmelCase							,					"""output"""      )
		__lowercase   							=	os.path.join(_lowerCAmelCase							,					"""data"""      )
		self._create_dummy_data(data_dir=_lowerCAmelCase      )

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

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

		__lowercase   							=	os.path.join(_lowerCAmelCase							,					"""metrics.json"""      )
		with open(_lowerCAmelCase      ) as f:
			__lowercase   							=	json.load(_lowerCAmelCase      )
		return result







	@require_torch_gpu
	def 			_a (	self   :				Any      )		->			Any:
		"""simple docstring"""







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







	@require_torch_multi_gpu
	def 			_a (	self   :				Tuple      )		->			str:
		"""simple docstring"""







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







	@require_torch_gpu
	@require_ray
	def 			_a (	self   :				Union[str, Any]      )		->			str:
		"""simple docstring"""







		__lowercase   							=	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   :				Union[str, Any]      )		->			Union[str, Any]:
		"""simple docstring"""







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



import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCamelCase  =logging.get_logger(__name__)


lowerCamelCase  ="▁"

lowerCamelCase  ={"vocab_file": "spiece.model"}

lowerCamelCase  ={
    "vocab_file": {
        "google/reformer-crime-and-punishment": (
            "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model"
        )
    }
}

lowerCamelCase  ={
    "google/reformer-crime-and-punishment": 5_2_4_2_8_8,
}




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	VOCAB_FILES_NAMES
     SCREAMING_SNAKE_CASE_		 =	PRETRAINED_VOCAB_FILES_MAP
     SCREAMING_SNAKE_CASE_		 =	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     SCREAMING_SNAKE_CASE_		 =	['''input_ids''', '''attention_mask''']






     def __init__(				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE="</s>"    ,    __SCREAMING_SNAKE_CASE="<unk>"    ,    __SCREAMING_SNAKE_CASE=[]    ,    __SCREAMING_SNAKE_CASE = None    ,    **__SCREAMING_SNAKE_CASE    ,    )	-> None:




           """simple docstring"""







           UpperCamelCase__     : int											=					{} if sp_model_kwargs is None else sp_model_kwargs

           super().__init__(
               eos_token=__SCREAMING_SNAKE_CASE    ,    unk_token=__SCREAMING_SNAKE_CASE    ,    additional_special_tokens=__SCREAMING_SNAKE_CASE    ,    sp_model_kwargs=self.sp_model_kwargs    ,    **__SCREAMING_SNAKE_CASE    ,    )

           UpperCamelCase__     : Dict											=					vocab_file
           UpperCamelCase__     : Any											=					spm.SentencePieceProcessor(**self.sp_model_kwargs	)
           self.sp_model.Load(__SCREAMING_SNAKE_CASE	)






     @property
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> List[Any]:




           """simple docstring"""







           return self.sp_model.get_piece_size()






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Dict[str, int]:




           """simple docstring"""







           UpperCamelCase__     : Tuple											=					{self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE	): i for i in range(self.vocab_size	)}
           vocab.update(self.added_tokens_encoder	)
           return vocab






     def __getstate__(				self	)	-> Any:




           """simple docstring"""







           UpperCamelCase__     : Dict											=					self.__dict__.copy()
           UpperCamelCase__     : int											=					None
           return state






     def __setstate__(				self    ,    __SCREAMING_SNAKE_CASE	)	-> str:




           """simple docstring"""







           UpperCamelCase__     : int											=					d

           # for backward compatibility
           if not hasattr(self    ,    '''sp_model_kwargs'''	):
                 UpperCamelCase__     : int											=					{}

           UpperCamelCase__     : Optional[Any]											=					spm.SentencePieceProcessor(**self.sp_model_kwargs	)
           self.sp_model.Load(self.vocab_file	)






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> List[str]:




           """simple docstring"""







           return self.sp_model.encode(__SCREAMING_SNAKE_CASE    ,    out_type=__SCREAMING_SNAKE_CASE	)






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> List[str]:




           """simple docstring"""







           return self.sp_model.piece_to_id(__SCREAMING_SNAKE_CASE	)






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> List[Any]:




           """simple docstring"""







           if index < self.sp_model.get_piece_size():
                 UpperCamelCase__     : str											=					self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE	)
           return token






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> Dict:




           """simple docstring"""







           UpperCamelCase__     : List[str]											=					[]
           UpperCamelCase__     : Union[str, Any]											=					''''''
           for token in tokens:
                 # make sure that special tokens are not decoded using sentencepiece model
                 if token in self.all_special_tokens:
                       out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE	) + token
                       UpperCamelCase__     : str											=					[]
                 else:
                       current_sub_tokens.append(__SCREAMING_SNAKE_CASE	)
           out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE	)
           return out_string.strip()






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE = None	)	-> Tuple[str]:




           """simple docstring"""







           if not os.path.isdir(__SCREAMING_SNAKE_CASE	):
                 logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''	)
                 return
           UpperCamelCase__     : Optional[int]											=					os.path.join(
               __SCREAMING_SNAKE_CASE    ,    (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']	)

           if os.path.abspath(self.vocab_file	) != os.path.abspath(__SCREAMING_SNAKE_CASE	) and os.path.isfile(self.vocab_file	):
                 copyfile(self.vocab_file    ,    __SCREAMING_SNAKE_CASE	)
           elif not os.path.isfile(self.vocab_file	):
                 with open(__SCREAMING_SNAKE_CASE    ,    '''wb'''	) as fi:
                       UpperCamelCase__     : int											=					self.sp_model.serialized_model_proto()
                       fi.write(__SCREAMING_SNAKE_CASE	)

           return (out_vocab_file,)


