

'''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							:							Dict  							=		logging.getLogger()

__A							:							List[Any]  							=		logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     Dict     )							->							Optional[int]:

     '''simple docstring'''




     os.makedirs(__lowerCamelCase				,     exist_ok=__lowerCamelCase     )
     lowerCamelCase__  =     {"source": "What is love ?", "target": "life"}
     lowerCamelCase__  =     {"train": 12, "val": 2, "test": 2}
     for split in ["train", "test", "val"]:
      for field in ["source", "target"]:
       lowerCamelCase__  =     "\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     :     Union[str, Any]				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     str = "pytorch"     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.get_auto_remove_tmp_dir()
     lowerCamelCase__  =     os.path.join(__lowerCamelCase				,     "output"     )
     lowerCamelCase__  =     os.path.join(__lowerCamelCase				,     "data"     )
     self._create_dummy_data(data_dir=__lowerCamelCase     )

     lowerCamelCase__  =     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"     )

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

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

    @require_torch_gpu
    def    a__				(					self     :     Optional[int]     )							->							Optional[Any]:

     '''simple docstring'''




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

    @require_torch_multi_gpu
    def    a__				(					self     :     Dict     )							->							Union[str, Any]:

     '''simple docstring'''




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

    @require_torch_gpu
    @require_ray
    def    a__				(					self     :     int     )							->							Union[str, Any]:

     '''simple docstring'''




     lowerCamelCase__  =     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]     )							->							Dict:

     '''simple docstring'''




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









'''simple docstring'''





# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
 import jax
 import jaxlib

__A							:							Any  							=		get_logger()

__A							:							Optional[dict]  							=		None
class 				lowercase       (							TensorFormatter[Mapping, "jax.Array", Mapping]      ):


    '''simple docstring'''

    def __init__(					self     :     str				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     Dict=None				,     **__lowerCamelCase     :     str     )							->							List[Any]:

     '''simple docstring'''




     super().__init__(features=__lowerCamelCase     )
     import jax
     from jaxlib.xla_client import Device

     if isinstance(__lowerCamelCase				,     __lowerCamelCase     ):
      raise ValueError(
          f'''Expected {device} to be a `str` not {type(__lowerCamelCase     )}, as `jaxlib.xla_extension.Device` '''
          "is not serializable neither with `pickle` nor with `dill`. Instead you can surround "
          "the device with `str()` to get its string identifier that will be internally mapped "
          "to the actual `jaxlib.xla_extension.Device`."     )
     lowerCamelCase__  =     device if isinstance(__lowerCamelCase				,     __lowerCamelCase     ) else str(jax.devices()[0]     )
     # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
     # with `pickle` nor with `dill`, so we need to use a global variable instead
     global DEVICE_MAPPING
     if DEVICE_MAPPING is None:
      lowerCamelCase__  =     self._map_devices_to_str()
     if self.device not in list(DEVICE_MAPPING.keys()     ):
      logger.warning(
          f'''Device with string identifier {self.device} not listed among the available '''
          f'''devices: {list(DEVICE_MAPPING.keys()     )}, so falling back to the default '''
          f'''device: {str(jax.devices()[0]     )}.'''     )
      lowerCamelCase__  =     str(jax.devices()[0]     )
     lowerCamelCase__  =     jnp_array_kwargs

    @staticmethod
    def    a__				(					)							->							Dict[str, "jaxlib.xla_extension.Device"]:

     '''simple docstring'''




     import jax

     return {str(__lowerCamelCase     ): device for device in jax.devices()}

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     Optional[int]     )							->							List[str]:

     '''simple docstring'''




     import jax
     import jax.numpy as jnp

     if isinstance(__lowerCamelCase				,     __lowerCamelCase     ) and column:
      if all(
          isinstance(__lowerCamelCase				,     jax.Array     ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column     ):
       return jnp.stack(__lowerCamelCase				,     axis=0     )
     return column

    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     List[Any]     )							->							Optional[int]:

     '''simple docstring'''




     import jax
     import jax.numpy as jnp

     if isinstance(__lowerCamelCase				,     (str, bytes, type(__lowerCamelCase     ))     ):
      return value
     elif isinstance(__lowerCamelCase				,     (np.character, np.ndarray)     ) and np.issubdtype(value.dtype				,     np.character     ):
      return value.tolist()

     lowerCamelCase__  =     {}

     if isinstance(__lowerCamelCase				,     (np.number, np.ndarray)     ) and np.issubdtype(value.dtype				,     np.integer     ):
      # the default int precision depends on the jax config
      # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
      if jax.config.jax_enable_xaa:
       lowerCamelCase__  =     {"dtype": jnp.intaa}
      else:
       lowerCamelCase__  =     {"dtype": jnp.intaa}
     elif isinstance(__lowerCamelCase				,     (np.number, np.ndarray)     ) and np.issubdtype(value.dtype				,     np.floating     ):
      lowerCamelCase__  =     {"dtype": jnp.floataa}
     elif config.PIL_AVAILABLE and "PIL" in sys.modules:
      import PIL.Image

      if isinstance(__lowerCamelCase				,     PIL.Image.Image     ):
       lowerCamelCase__  =     np.asarray(__lowerCamelCase     )

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
     global DEVICE_MAPPING
     if DEVICE_MAPPING is None:
      lowerCamelCase__  =     self._map_devices_to_str()

     with jax.default_device(DEVICE_MAPPING[self.device]     ):
      # calling jnp.array on a np.ndarray does copy the data
      # see https://github.com/google/jax/issues/4486
      return jnp.array(__lowerCamelCase				,     **{**default_dtype, **self.jnp_array_kwargs}     )

    def    a__				(					self     :     List[str]				,     __lowerCamelCase     :     Optional[Any]     )							->							Dict:

     '''simple docstring'''




     import jax

     # support for torch, tf, jax etc.
     if config.TORCH_AVAILABLE and "torch" in sys.modules:
      import torch

      if isinstance(__lowerCamelCase				,     torch.Tensor     ):
       return self._tensorize(data_struct.detach().cpu().numpy()[()]     )
     if hasattr(__lowerCamelCase				,     "__array__"     ) and not isinstance(__lowerCamelCase				,     jax.Array     ):
      lowerCamelCase__  =     data_struct.__array__()
     # support for nested types like struct of list of struct
     if isinstance(__lowerCamelCase				,     np.ndarray     ):
      if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
       return self._consolidate([self.recursive_tensorize(__lowerCamelCase     ) for substruct in data_struct]     )
     elif isinstance(__lowerCamelCase				,     (list, tuple)     ):
      return self._consolidate([self.recursive_tensorize(__lowerCamelCase     ) for substruct in data_struct]     )
     return self._tensorize(__lowerCamelCase     )

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     dict     )							->							int:

     '''simple docstring'''




     return map_nested(self._recursive_tensorize				,     __lowerCamelCase				,     map_list=__lowerCamelCase     )

    def    a__				(					self     :     Union[str, Any]				,     __lowerCamelCase     :     pa.Table     )							->							Mapping:

     '''simple docstring'''




     lowerCamelCase__  =     self.numpy_arrow_extractor().extract_row(__lowerCamelCase     )
     lowerCamelCase__  =     self.python_features_decoder.decode_row(__lowerCamelCase     )
     return self.recursive_tensorize(__lowerCamelCase     )

    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     pa.Table     )							->							"jax.Array":

     '''simple docstring'''




     lowerCamelCase__  =     self.numpy_arrow_extractor().extract_column(__lowerCamelCase     )
     lowerCamelCase__  =     self.python_features_decoder.decode_column(__lowerCamelCase				,     pa_table.column_names[0]     )
     lowerCamelCase__  =     self.recursive_tensorize(__lowerCamelCase     )
     lowerCamelCase__  =     self._consolidate(__lowerCamelCase     )
     return column




    def    a__				(					self     :     List[str]				,     __lowerCamelCase     :     pa.Table     )							->							Mapping:

     '''simple docstring'''




     lowerCamelCase__  =     self.numpy_arrow_extractor().extract_batch(__lowerCamelCase     )
     lowerCamelCase__  =     self.python_features_decoder.decode_batch(__lowerCamelCase     )
     lowerCamelCase__  =     self.recursive_tensorize(__lowerCamelCase     )
     for column_name in batch:
      lowerCamelCase__  =     self._consolidate(batch[column_name]     )
     return batch

