
import unittest

import numpy as np

from transformers import is_flax_available
from transformers.testing_utils import require_flax

from ..test_modeling_flax_common import ids_tensor


if is_flax_available():
							import jax
							import jax.numpy as jnp

							from transformers.generation import (
							    FlaxForcedBOSTokenLogitsProcessor,
							    FlaxForcedEOSTokenLogitsProcessor,
							    FlaxLogitsProcessorList,
							    FlaxMinLengthLogitsProcessor,
							    FlaxTemperatureLogitsWarper,
							    FlaxTopKLogitsWarper,
							    FlaxTopPLogitsWarper,
							)

@require_flax
class        _UpperCamelCase				(					unittest.TestCase  ):






			'''simple docstring'''

			def       lowerCAmelCase__	(       self :       Optional[Any]						,	snake_case_ :       Any						,	snake_case_ :       str      ):
							UpperCamelCase_:							str	=						jnp.ones((batch_size, length)      ) / length
							return scores

			def       lowerCAmelCase__	(       self :       Tuple      ):
							UpperCamelCase_:							Union[str, Any]	=						None
							UpperCamelCase_:							List[Any]	=						20

							UpperCamelCase_:							str	=						self._get_uniform_logits(batch_size=2						,	length=_A      )

							# tweak scores to not be uniform anymore
							UpperCamelCase_:							int	=						scores.at[1, 5].set((1 / length) + 0.1      )  # peak, 1st batch
							UpperCamelCase_:							int	=						scores.at[1, 10].set((1 / length) - 0.4      )  # valley, 1st batch

							# compute softmax
							UpperCamelCase_:							List[str]	=						jax.nn.softmax(_A						,	axis=-1      )

							UpperCamelCase_:							Union[str, Any]	=						FlaxTemperatureLogitsWarper(temperature=0.5      )
							UpperCamelCase_:							Optional[Any]	=						FlaxTemperatureLogitsWarper(temperature=1.3      )

							UpperCamelCase_:							Tuple	=						jax.nn.softmax(temp_dist_warper_sharper(_A						,	scores.copy()						,	cur_len=_A      )						,	axis=-1      )
							UpperCamelCase_:							str	=						jax.nn.softmax(temp_dist_warper_smoother(_A						,	scores.copy()						,	cur_len=_A      )						,	axis=-1      )

							# uniform distribution stays uniform
							self.assertTrue(jnp.allclose(probs[0, :]						,	warped_prob_sharp[0, :]						,	atol=1e-3      )      )
							self.assertTrue(jnp.allclose(probs[0, :]						,	warped_prob_smooth[0, :]						,	atol=1e-3      )      )

							# sharp peaks get higher, valleys get lower
							self.assertLess(probs[1, :].max()						,	warped_prob_sharp[1, :].max()      )
							self.assertGreater(probs[1, :].min()						,	warped_prob_sharp[1, :].min()      )

							# smooth peaks get lower, valleys get higher
							self.assertGreater(probs[1, :].max()						,	warped_prob_smooth[1, :].max()      )
							self.assertLess(probs[1, :].min()						,	warped_prob_smooth[1, :].min()      )

			def       lowerCAmelCase__	(       self :       Tuple      ):
							UpperCamelCase_:							List[str]	=						None
							UpperCamelCase_:							Dict	=						10
							UpperCamelCase_:							Optional[Any]	=						2

							# create ramp distribution
							UpperCamelCase_:							Union[str, Any]	=						np.broadcast_to(np.arange(_A      )[None, :]						,	(batch_size, vocab_size)      ).copy()
							UpperCamelCase_:							Any	=						ramp_logits[1:, : vocab_size // 2] + vocab_size

							UpperCamelCase_:							List[Any]	=						FlaxTopKLogitsWarper(3      )

							UpperCamelCase_:							List[Any]	=						top_k_warp(_A						,	_A						,	cur_len=_A      )

							# check that correct tokens are filtered
							self.assertListEqual(jnp.isinf(scores[0]      ).tolist()						,	7 * [True] + 3 * [False]      )
							self.assertListEqual(jnp.isinf(scores[1]      ).tolist()						,	2 * [True] + 3 * [False] + 5 * [True]      )

							# check special case
							UpperCamelCase_:							List[str]	=						5
							UpperCamelCase_:							int	=						FlaxTopKLogitsWarper(top_k=1						,	filter_value=0.0						,	min_tokens_to_keep=3      )

							UpperCamelCase_:							List[str]	=						np.broadcast_to(np.arange(_A      )[None, :]						,	(batch_size, length)      ).copy()
							UpperCamelCase_:							Optional[int]	=						top_k_warp_safety_check(_A						,	_A						,	cur_len=_A      )

							# min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
							self.assertListEqual((scores == 0.0).sum(axis=-1      ).tolist()						,	[2, 2]      )

			def       lowerCAmelCase__	(       self :       Tuple      ):
							UpperCamelCase_:							Tuple	=						None
							UpperCamelCase_:							Optional[Any]	=						10
							UpperCamelCase_:							Optional[int]	=						2

							# create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
							UpperCamelCase_:							List[Any]	=						np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]]      )      )

							UpperCamelCase_:							Any	=						FlaxTopPLogitsWarper(0.8      )
							UpperCamelCase_:							Any	=						np.exp(top_p_warp(_A						,	_A						,	cur_len=_A      )      )

							# dist should be filtered to keep min num values so that sum is >= top_p
							# exp (-inf) => 0
							UpperCamelCase_:							Optional[int]	=						np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]      )
							self.assertTrue(np.allclose(_A						,	_A						,	atol=1e-3      )      )

							# check edge cases with negative and extreme logits
							UpperCamelCase_:							str	=						np.broadcast_to(np.arange(_A      )[None, :]						,	(batch_size, vocab_size)      ).copy() - (
							    vocab_size // 2
							)

							# make ramp_logits more extreme
							UpperCamelCase_:							Any	=						ramp_logits[1] * 100.0

							# make sure at least 2 tokens are kept
							UpperCamelCase_:							Optional[Any]	=						FlaxTopPLogitsWarper(0.9						,	min_tokens_to_keep=2						,	filter_value=0.0      )
							UpperCamelCase_:							int	=						top_p_warp(_A						,	_A						,	cur_len=_A      )

							# first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
							self.assertListEqual((filtered_dist != 0.0).sum(axis=-1      ).tolist()						,	[3, 2]      )

			def       lowerCAmelCase__	(       self :       int      ):
							UpperCamelCase_:							List[Any]	=						20
							UpperCamelCase_:							List[Any]	=						4
							UpperCamelCase_:							Dict	=						0

							UpperCamelCase_:							Union[str, Any]	=						FlaxMinLengthLogitsProcessor(min_length=10						,	eos_token_id=_A      )

							# check that min length is applied at length 5
							UpperCamelCase_:							Optional[int]	=						ids_tensor((batch_size, 20)						,	vocab_size=20      )
							UpperCamelCase_:							str	=						5
							UpperCamelCase_:							Union[str, Any]	=						self._get_uniform_logits(_A						,	_A      )
							UpperCamelCase_:							str	=						min_dist_processor(_A						,	_A						,	cur_len=_A      )
							self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()						,	4 * [-float("""inf"""      )]      )

							# check that min length is not applied anymore at length 15
							UpperCamelCase_:							Tuple	=						self._get_uniform_logits(_A						,	_A      )
							UpperCamelCase_:							Any	=						15
							UpperCamelCase_:							Dict	=						min_dist_processor(_A						,	_A						,	cur_len=_A      )
							self.assertFalse(jnp.isinf(_A      ).any()      )

			def       lowerCAmelCase__	(       self :       Dict      ):
							UpperCamelCase_:							Optional[Any]	=						20
							UpperCamelCase_:							int	=						4
							UpperCamelCase_:							int	=						0

							UpperCamelCase_:							List[str]	=						FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A      )

							# check that all scores are -inf except the bos_token_id score
							UpperCamelCase_:							Optional[int]	=						ids_tensor((batch_size, 1)						,	vocab_size=20      )
							UpperCamelCase_:							Tuple	=						1
							UpperCamelCase_:							Tuple	=						self._get_uniform_logits(_A						,	_A      )
							UpperCamelCase_:							Optional[int]	=						logits_processor(_A						,	_A						,	cur_len=_A      )
							self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]      ).all()      )
							self.assertListEqual(scores[:, bos_token_id].tolist()						,	4 * [0]      )  # score for bos_token_id shold be zero

							# check that bos_token_id is not forced if current length is greater than 1
							UpperCamelCase_:							str	=						3
							UpperCamelCase_:							Optional[int]	=						self._get_uniform_logits(_A						,	_A      )
							UpperCamelCase_:							Tuple	=						logits_processor(_A						,	_A						,	cur_len=_A      )
							self.assertFalse(jnp.isinf(_A      ).any()      )

			def       lowerCAmelCase__	(       self :       Dict      ):
							UpperCamelCase_:							List[Any]	=						20
							UpperCamelCase_:							Optional[Any]	=						4
							UpperCamelCase_:							Dict	=						0
							UpperCamelCase_:							Optional[Any]	=						5

							UpperCamelCase_:							str	=						FlaxForcedEOSTokenLogitsProcessor(max_length=_A						,	eos_token_id=_A      )

							# check that all scores are -inf except the eos_token_id when max_length is reached
							UpperCamelCase_:							int	=						ids_tensor((batch_size, 4)						,	vocab_size=20      )
							UpperCamelCase_:							int	=						4
							UpperCamelCase_:							Union[str, Any]	=						self._get_uniform_logits(_A						,	_A      )
							UpperCamelCase_:							List[str]	=						logits_processor(_A						,	_A						,	cur_len=_A      )
							self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]      ).all()      )
							self.assertListEqual(scores[:, eos_token_id].tolist()						,	4 * [0]      )  # score for eos_token_id should be zero

							# check that eos_token_id is not forced if max_length is not reached
							UpperCamelCase_:							Any	=						3
							UpperCamelCase_:							Union[str, Any]	=						self._get_uniform_logits(_A						,	_A      )
							UpperCamelCase_:							Optional[Any]	=						logits_processor(_A						,	_A						,	cur_len=_A      )
							self.assertFalse(jnp.isinf(_A      ).any()      )

			def       lowerCAmelCase__	(       self :       Any      ):
							UpperCamelCase_:							int	=						4
							UpperCamelCase_:							List[str]	=						10
							UpperCamelCase_:							int	=						15
							UpperCamelCase_:							Any	=						2
							UpperCamelCase_:							Dict	=						1
							UpperCamelCase_:							Optional[int]	=						15

							# dummy input_ids and scores
							UpperCamelCase_:							Union[str, Any]	=						ids_tensor((batch_size, sequence_length)						,	_A      )
							UpperCamelCase_:							str	=						input_ids.copy()

							UpperCamelCase_:							Union[str, Any]	=						self._get_uniform_logits(_A						,	_A      )
							UpperCamelCase_:							int	=						scores.copy()

							# instantiate all dist processors
							UpperCamelCase_:							List[str]	=						FlaxTemperatureLogitsWarper(temperature=0.5      )
							UpperCamelCase_:							Optional[int]	=						FlaxTopKLogitsWarper(3      )
							UpperCamelCase_:							Union[str, Any]	=						FlaxTopPLogitsWarper(0.8      )

							# instantiate all logits processors
							UpperCamelCase_:							List[Any]	=						FlaxMinLengthLogitsProcessor(min_length=10						,	eos_token_id=_A      )
							UpperCamelCase_:							Tuple	=						FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A      )
							UpperCamelCase_:							Any	=						FlaxForcedEOSTokenLogitsProcessor(max_length=_A						,	eos_token_id=_A      )

							UpperCamelCase_:							List[str]	=						10

							# no processor list
							UpperCamelCase_:							Dict	=						temp_dist_warp(_A						,	_A						,	cur_len=_A      )
							UpperCamelCase_:							Optional[int]	=						top_k_warp(_A						,	_A						,	cur_len=_A      )
							UpperCamelCase_:							Dict	=						top_p_warp(_A						,	_A						,	cur_len=_A      )
							UpperCamelCase_:							int	=						min_dist_proc(_A						,	_A						,	cur_len=_A      )
							UpperCamelCase_:							List[Any]	=						bos_dist_proc(_A						,	_A						,	cur_len=_A      )
							UpperCamelCase_:							Optional[int]	=						eos_dist_proc(_A						,	_A						,	cur_len=_A      )

							# with processor list
							UpperCamelCase_:							Dict	=						FlaxLogitsProcessorList(
							    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]      )
							UpperCamelCase_:							List[str]	=						processor(_A						,	_A						,	cur_len=_A      )

							# scores should be equal
							self.assertTrue(jnp.allclose(_A						,	_A						,	atol=1e-3      )      )

							# input_ids should never be changed
							self.assertListEqual(input_ids.tolist()						,	input_ids_comp.tolist()      )




			def       lowerCAmelCase__	(       self :       int      ):
							UpperCamelCase_:							int	=						4
							UpperCamelCase_:							List[Any]	=						10
							UpperCamelCase_:							Tuple	=						15
							UpperCamelCase_:							Union[str, Any]	=						2
							UpperCamelCase_:							Optional[int]	=						1
							UpperCamelCase_:							List[str]	=						15

							# dummy input_ids and scores
							UpperCamelCase_:							int	=						ids_tensor((batch_size, sequence_length)						,	_A      )
							UpperCamelCase_:							Optional[int]	=						input_ids.copy()

							UpperCamelCase_:							Optional[Any]	=						self._get_uniform_logits(_A						,	_A      )
							UpperCamelCase_:							List[Any]	=						scores.copy()

							# instantiate all dist processors
							UpperCamelCase_:							Optional[int]	=						FlaxTemperatureLogitsWarper(temperature=0.5      )
							UpperCamelCase_:							Optional[int]	=						FlaxTopKLogitsWarper(3      )
							UpperCamelCase_:							Tuple	=						FlaxTopPLogitsWarper(0.8      )

							# instantiate all logits processors
							UpperCamelCase_:							Optional[int]	=						FlaxMinLengthLogitsProcessor(min_length=10						,	eos_token_id=_A      )
							UpperCamelCase_:							Optional[int]	=						FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A      )
							UpperCamelCase_:							Any	=						FlaxForcedEOSTokenLogitsProcessor(max_length=_A						,	eos_token_id=_A      )

							UpperCamelCase_:							List[str]	=						10

							# no processor list
							def run_no_processor_list(snake_case_ :       Optional[int]						,	snake_case_ :       Any						,	snake_case_ :       Tuple      ):
											UpperCamelCase_:							Optional[Any]	=						temp_dist_warp(_A						,	_A						,	cur_len=_A      )
											UpperCamelCase_:							Optional[Any]	=						top_k_warp(_A						,	_A						,	cur_len=_A      )
											UpperCamelCase_:							List[Any]	=						top_p_warp(_A						,	_A						,	cur_len=_A      )
											UpperCamelCase_:							Optional[Any]	=						min_dist_proc(_A						,	_A						,	cur_len=_A      )
											UpperCamelCase_:							Tuple	=						bos_dist_proc(_A						,	_A						,	cur_len=_A      )
											UpperCamelCase_:							Dict	=						eos_dist_proc(_A						,	_A						,	cur_len=_A      )
											return scores

							# with processor list
							def run_processor_list(snake_case_ :       int						,	snake_case_ :       Optional[int]						,	snake_case_ :       Tuple      ):
											UpperCamelCase_:							Optional[Any]	=						FlaxLogitsProcessorList(
											    [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]      )
											UpperCamelCase_:							List[Any]	=						processor(_A						,	_A						,	cur_len=_A      )
											return scores

							UpperCamelCase_:							Dict	=						jax.jit(_A      )
							UpperCamelCase_:							Optional[Any]	=						jax.jit(_A      )

							UpperCamelCase_:							List[str]	=						jitted_run_no_processor_list(_A						,	_A						,	_A      )
							UpperCamelCase_:							List[Any]	=						jitted_run_processor_list(_A						,	_A						,	_A      )

							# scores should be equal
							self.assertTrue(jnp.allclose(_A						,	_A						,	atol=1e-3      )      )

							# input_ids should never be changed
							self.assertListEqual(input_ids.tolist()						,	input_ids_comp.tolist()      )








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)
lowerCamelCase_						: Union[str, Any]         =  logging.getLogger()

lowerCamelCase_						: List[str]         =  logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)

class        _UpperCamelCase				(					_A  ):






			'''simple docstring'''

			def       lowerCAmelCase__	(       self :       List[Any]						,	snake_case_ :       Dict      ):
							os.makedirs(snake_case_						,	exist_ok=snake_case_      )
							UpperCamelCase_:							int	=						{"""source""": """What is love ?""", """target""": """life"""}
							UpperCamelCase_:							Tuple	=						{"""train""": 12, """val""": 2, """test""": 2}
							for split in ["train", "test", "val"]:
											for field in ["source", "target"]:
															UpperCamelCase_:							Tuple	=						"""\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       lowerCAmelCase__	(       self :       Dict						,	snake_case_ :       int						,	snake_case_ :       str = "pytorch"      ):
							UpperCamelCase_:							Optional[Any]	=						self.get_auto_remove_tmp_dir()
							UpperCamelCase_:							Dict	=						os.path.join(snake_case_						,	"""output"""      )
							UpperCamelCase_:							Any	=						os.path.join(snake_case_						,	"""data"""      )
							self._create_dummy_data(data_dir=snake_case_      )

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

							UpperCamelCase_:							Optional[Any]	=						[sys.executable, str(Path(finetune_rag.__file__      ).resolve()      )] + testargs
							execute_subprocess_async(snake_case_						,	env=self.get_env()      )

							UpperCamelCase_:							Optional[int]	=						os.path.join(snake_case_						,	"""metrics.json"""      )
							with open(snake_case_      ) as f:
											UpperCamelCase_:							Any	=						json.load(snake_case_      )
							return result

			@require_torch_gpu
			def       lowerCAmelCase__	(       self :       Optional[Any]      ):
							UpperCamelCase_:							List[str]	=						self._run_finetune(gpus=1      )
							self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]						,	0.2      )

			@require_torch_multi_gpu
			def       lowerCAmelCase__	(       self :       Optional[Any]      ):
							UpperCamelCase_:							Any	=						self._run_finetune(gpus=2      )
							self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""]						,	0.2      )

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






