





"""simple docstring"""






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)
A			      =	logging.getLogger()

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




class 					__lowercase      (      _UpperCamelCase				):







					'''simple docstring'''




					def 			_lowerCamelCase		(    self						,      _UpperCAmelCase  ):
									os.makedirs(_UpperCAmelCase						,      exist_ok=_UpperCAmelCase  )
									__a			:    Union[str, Any]      							=	{'''source''': '''What is love ?''', '''target''': '''life'''}
									__a			:    Tuple      							=	{'''train''': 12, '''val''': 2, '''test''': 2}
									for split in ["train", "test", "val"]:
													for field in ["source", "target"]:
																	__a			:    Tuple      							=	'''\n'''.join([contents[field]] * n_lines[split]  )
																	with open(os.path.join(_UpperCAmelCase						,      f"""{split}.{field}"""  )						,      '''w'''  ) as f:
																					f.write(_UpperCAmelCase  )







					def 			_lowerCamelCase		(    self						,      _UpperCAmelCase						,      _UpperCAmelCase = "pytorch"  ):
									__a			:    Optional[int]      							=	self.get_auto_remove_tmp_dir()
									__a			:    Optional[int]      							=	os.path.join(_UpperCAmelCase						,      '''output'''  )
									__a			:    Optional[int]      							=	os.path.join(_UpperCAmelCase						,      '''data'''  )
									self._create_dummy_data(data_dir=_UpperCAmelCase  )

									__a			:    int      							=	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			:    Dict      							=	[sys.executable, str(Path(finetune_rag.__file__  ).resolve()  )] + testargs
									execute_subprocess_async(_UpperCAmelCase						,      env=self.get_env()  )

									__a			:    Optional[Any]      							=	os.path.join(_UpperCAmelCase						,      '''metrics.json'''  )
									with open(_UpperCAmelCase  ) as f:
													__a			:    Dict      							=	json.load(_UpperCAmelCase  )
									return result







					@require_torch_gpu
					def 			_lowerCamelCase		(    self  ):
									__a			:    Optional[int]      							=	self._run_finetune(gpus=1  )
									self.assertGreaterEqual(result['''test'''][0]['''test_avg_em''']						,      0.2  )







					@require_torch_multi_gpu
					def 			_lowerCamelCase		(    self  ):
									__a			:    Optional[int]      							=	self._run_finetune(gpus=2  )
									self.assertGreaterEqual(result['''test'''][0]['''test_avg_em''']						,      0.2  )







					@require_torch_gpu
					@require_ray
					def 			_lowerCamelCase		(    self  ):
									__a			:    Dict      							=	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 			_lowerCamelCase		(    self  ):
									__a			:    Dict      							=	self._run_finetune(gpus=1						,      distributed_retriever='''ray'''  )
									self.assertGreaterEqual(result['''test'''][0]['''test_avg_em''']						,      0.2  )





# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce





def 				A__ (snake_case   :		List[Any]				)     ->						Optional[Any]:
					return (torch.arange(state.num_processes				) + 1.0 + (state.num_processes * state.process_index)).to(state.device				)





def 				A__ (snake_case   :		int				)     ->						Any:
					__UpperCamelCase					:	List[str]             =      create_tensor(snake_case				)
					__UpperCamelCase					:	List[Any]             =      gather(snake_case				)
					assert gathered_tensor.tolist() == list(range(1		,	state.num_processes**2 + 1				)				)





def 				A__ (snake_case   :		Optional[Any]				)     ->						Dict:
					__UpperCamelCase					:	Any             =      [state.process_index]
					__UpperCamelCase					:	int             =      gather_object(snake_case				)
					assert len(snake_case				) == state.num_processes, F'''{gathered_obj}, {len(snake_case				)} != {state.num_processes}'''
					assert gathered_obj == list(range(state.num_processes				)				), F'''{gathered_obj} != {list(range(state.num_processes				)				)}'''





def 				A__ (snake_case   :		Any				)     ->						Optional[Any]:
					__UpperCamelCase					:	Optional[Any]             =      create_tensor(snake_case				)
					__UpperCamelCase					:	Any             =      broadcast(snake_case				)
					assert broadcasted_tensor.shape == torch.Size([state.num_processes]				)
					assert broadcasted_tensor.tolist() == list(range(1		,	state.num_processes + 1				)				)





def 				A__ (snake_case   :		Tuple				)     ->						Dict:
					# We need to pad the tensor with one more element if we are the main process
					# to ensure that we can pad
					if state.is_main_process:
										__UpperCamelCase					:	List[Any]             =      torch.arange(state.num_processes + 1				).to(state.device				)
					else:
										__UpperCamelCase					:	List[str]             =      torch.arange(state.num_processes				).to(state.device				)
					__UpperCamelCase					:	List[str]             =      pad_across_processes(snake_case				)
					assert padded_tensor.shape == torch.Size([state.num_processes + 1]				)
					if not state.is_main_process:
										assert padded_tensor.tolist() == list(range(0		,	state.num_processes				)				) + [0]





def 				A__ (snake_case   :		Tuple				)     ->						Dict:
					# For now runs on only two processes
					if state.num_processes != 2:
										return
					__UpperCamelCase					:	Optional[int]             =      create_tensor(snake_case				)
					__UpperCamelCase					:	str             =      reduce(snake_case		,	"""sum"""				)
					__UpperCamelCase					:	Optional[int]             =      torch.tensor([4.0, 6]				).to(state.device				)
					assert torch.allclose(snake_case		,	snake_case				), F'''{reduced_tensor} != {truth_tensor}'''





def 				A__ (snake_case   :		Optional[Any]				)     ->						Optional[Any]:
					# For now runs on only two processes
					if state.num_processes != 2:
										return
					__UpperCamelCase					:	List[Any]             =      create_tensor(snake_case				)
					__UpperCamelCase					:	str             =      reduce(snake_case		,	"""mean"""				)
					__UpperCamelCase					:	Union[str, Any]             =      torch.tensor([2.0, 3]				).to(state.device				)
					assert torch.allclose(snake_case		,	snake_case				), F'''{reduced_tensor} != {truth_tensor}'''





def 				A__ (snake_case   :		Tuple				)     ->						int:
					# For xla_spawn (TPUs)
					main()





def 				A__ ()     ->						List[Any]:
					__UpperCamelCase					:	List[Any]             =      PartialState()
					state.print(F'''State: {state}'''				)
					state.print("""testing gather"""				)
					test_gather(snake_case				)
					state.print("""testing gather_object"""				)
					test_gather_object(snake_case				)
					state.print("""testing broadcast"""				)
					test_broadcast(snake_case				)
					state.print("""testing pad_across_processes"""				)
					test_pad_across_processes(snake_case				)
					state.print("""testing reduce_sum"""				)
					test_reduce_sum(snake_case				)
					state.print("""testing reduce_mean"""				)
					test_reduce_mean(snake_case				)


if __name__ == "__main__":
	main()






