U
    9%el                  
   @   sl	  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZ d dlmZ d dlmZmZmZmZmZ d dlmZ d dlZd dlZd dl mZ! dd	l"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( dd
l)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZi e, r4d dljmkZkmlZl eL r~d dlmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZu d dlvmwZw d dlxmyZy nezZnezZydZ{dZ|dZ}dZ~dZdZdfddZdfddZedddZedddZedddZed ddZed!ddZed"ddZed#ddZed$ddZed%ddZd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Zd>d? Zd@fedAdBdCZdDdE ZdFdG ZdHdI ZdJdK ZdLdM ZdNdO ZdPdQ ZdRdS ZdTdU ZdVdW ZdXdY ZdZd[ Zd\d] Zd^d_ Zd`da Zdbdc Zddde Zdfdg Zdhdi Zdjdk Zdldm Zdndo Zdpdq Zdrds Zdtdu Zdvdw Zdxdy Zdzd{ Zd|d} Zd~d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Ze\ rd dlZdejkrHejd ZzeàešZW n4 ek
rD Z zedeś eɂW 5 dZ[X Y nX n>ejʠˡ rZdZn,erne` rndZnered rdZndZdejkrejd Zzee̡ZW n: ek
r Z zede̛ deɛ eɂW 5 dZ[X Y nX ndZeY rd dlZe8 rd dlZeѠҡ ZndZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZddĄ ZddƄ ZddȄ Zddʄ Zdd̄ Zdd΄ ZddЄ Zdd҄ ZddԄ Zddք Zdd؄ Zddڄ Zdfdd܄Zddބ Zdd ZG dd dZG dd deZG dd deZG dd dZejdd Zejeeejf ed dddZG dd dejZdd Z ejdd Zi Zdd Zdd Zd dlZG dd dZdd ZdddddfedddZdddddfedd dZ	dd Z
dd ZdfddZd	d
 Zdd ZG dd deZdfee dddZG dd dZdddfeee ee dddZddfddZdd ZG dd dejZG dd denZdS (       N)Mapping)StringIO)Path)IterableIteratorListOptionalUnion)mock)logging   )is_clearml_availableis_fairscale_availableis_optuna_availableis_ray_availableis_sigopt_availableis_wandb_available)is_deepspeed_available)>is_accelerate_availableis_apex_availableis_auto_gptq_availableis_bitsandbytes_availableis_bs4_availableis_cv2_availableis_cython_availableis_decord_availableis_detectron2_availableis_essentia_availableis_faiss_availableis_flash_attn_availableis_flax_availableis_fsdp_availableis_ftfy_availableis_ipex_availableis_jieba_availableis_jinja_availableis_jumanpp_availableis_keras_nlp_availableis_levenshtein_availableis_librosa_availableis_natten_availableis_nltk_availableis_onnx_availableis_optimum_availableis_pandas_availableis_peft_availableis_phonemizer_availableis_pretty_midi_availableis_pyctcdecode_availableis_pytesseract_availableis_pytest_available!is_pytorch_quantization_availableis_rjieba_availableis_safetensors_availableis_scipy_availableis_sentencepiece_availableis_seqio_availableis_soundfile_availbleis_spacy_availableis_sudachi_available#is_tensorflow_probability_availableis_tensorflow_text_availableis_tf2onnx_availableis_tf_availableis_timm_availableis_tokenizers_availableis_torch_availableis_torch_bf16_cpu_availableis_torch_bf16_gpu_availableis_torch_neuroncore_availableis_torch_npu_availableis_torch_tensorrt_fx_availableis_torch_tf32_availableis_torch_tpu_availableis_torch_xpu_availableis_torchaudio_availableis_torchdynamo_availableis_torchvision_availableis_vision_available	strtobool)AcceleratorStatePartialState)Module_get_checker_get_continue_on_failure_get_runner
_is_mocked_patch_unwrap_mock_awareget_optionflagsimport_path)skip)DoctestItemzjulien-c/bert-xsmall-dummyzjulien-c/dummy-unknownzjulien-c/dummy-diff-tokenizerZ__DUMMY_TRANSFORMERS_USER__zhttps://hub-ci.huggingface.coZ%hf_94wBhPGp6KrrTH3KDchhKpRxZwd6dmHWLLFc                 C   s^   zt j|  }W n tk
r&   |}Y n4X zt|}W n$ tk
rX   td|  dY nX |S )NIf set, z must be yes or no.)osenvironKeyErrorrQ   
ValueErrorkeydefaultvalue_value rh   Y/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/testing_utils.pyparse_flag_from_env   s    
rj   c                 C   s^   zt j|  }W n tk
r&   |}Y n4X zt|}W n$ tk
rX   td|  dY nX |S )Nr^   z must be a int.)r_   r`   ra   intrb   rc   rh   rh   ri   parse_int_from_env   s    
rl   ZRUN_SLOW)re   ZRUN_PT_TF_CROSS_TESTSTZRUN_PT_FLAX_CROSS_TESTSZRUN_CUSTOM_TOKENIZERSZHUGGINGFACE_CO_STAGINGZTF_GPU_MEMORY_LIMITZRUN_PIPELINE_TESTSZRUN_TOOL_TESTSZRUN_THIRD_PARTY_DEVICE_TESTSc                 C   sV   t rt rt std| S zddl}W n tk
rB   |  Y S X |j | S dS )a'  
    Decorator marking a test as a test that control interactions between PyTorch and TensorFlow.

    PT+TF tests are skipped by default and we can run only them by setting RUN_PT_TF_CROSS_TESTS environment variable
    to a truthy value and selecting the is_pt_tf_cross_test pytest mark.

    ztest is PT+TF testr   N)	_run_pt_tf_cross_testsrD   rA   unittestr\   pytestImportErrormarkis_pt_tf_cross_test	test_casero   rh   rh   ri   rr      s    
rr   c                 C   sV   t rt rt std| S zddl}W n tk
rB   |  Y S X |j | S dS )a&  
    Decorator marking a test as a test that control interactions between PyTorch and Flax

    PT+FLAX tests are skipped by default and we can run only them by setting RUN_PT_FLAX_CROSS_TESTS environment
    variable to a truthy value and selecting the is_pt_flax_cross_test pytest mark.

    ztest is PT+FLAX testr   N)	_run_pt_flax_cross_testsrD   r    rn   r\   ro   rp   rq   is_pt_flax_cross_testrs   rh   rh   ri   rv      s    
rv   c                 C   sJ   t std| S zddl}W n tk
r6   |  Y S X |j | S dS )z
    Decorator marking a test as a staging test.

    Those tests will run using the staging environment of huggingface.co instead of the real model hub.
    ztest is staging testr   N)_run_stagingrn   r\   ro   rp   rq   is_staging_testrs   rh   rh   ri   rx      s    
rx   c                 C   sJ   t std| S zddl}W n tk
r6   |  Y S X |j | S dS )z
    Decorator marking a test as a pipeline test. If RUN_PIPELINE_TESTS is set to a falsy value, those tests will be
    skipped.
    ztest is pipeline testr   N)_run_pipeline_testsrn   r\   ro   rp   rq   is_pipeline_testrs   rh   rh   ri   rz      s    
rz   c                 C   sJ   t std| S zddl}W n tk
r6   |  Y S X |j | S dS )zz
    Decorator marking a test as a tool test. If RUN_TOOL_TESTS is set to a falsy value, those tests will be skipped.
    ztest is a tool testr   N)_run_tool_testsrn   r\   ro   rp   rq   is_tool_testrs   rh   rh   ri   r|     s    
r|   c                 C   s   t td| S )z
    Decorator marking a test as slow.

    Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them.

    ztest is slow)rn   
skipUnless_run_slow_testsrt   rh   rh   ri   slow  s    r   c                 C   s   t d| S )z
    Decorator marking a test as too slow.

    Slow tests are skipped while they're in the process of being fixed. No test should stay tagged as "tooslow" as
    these will not be tested by the CI.

    ztest is too slow)rn   r\   r   rh   rh   ri   tooslow!  s    r   c                 C   s   t td| S )z
    Decorator marking a test for a custom tokenizer.

    Custom tokenizers require additional dependencies, and are skipped by default. Set the RUN_CUSTOM_TOKENIZERS
    environment variable to a truthy value to run them.
    ztest of custom tokenizers)rn   r}   _run_custom_tokenizersr   rh   rh   ri   custom_tokenizers,  s    r   c                 C   s   t t d| S )z}
    Decorator marking a test that requires BeautifulSoup4. These tests are skipped when BeautifulSoup4 isn't installed.
    ztest requires BeautifulSoup4)rn   r}   r   r   rh   rh   ri   require_bs46  s    r   c                 C   s   t t d| S )zs
    Decorator marking a test that requires OpenCV.

    These tests are skipped when OpenCV isn't installed.

    ztest requires OpenCV)rn   r}   r   r   rh   rh   ri   require_cv2=  s    r   c                 C   s   t t d| S )z}
    Decorator marking a test that requires Levenshtein.

    These tests are skipped when Levenshtein isn't installed.

    ztest requires Levenshtein)rn   r}   r(   r   rh   rh   ri   require_levenshteinG  s    r   c                 C   s   t t d| S )zo
    Decorator marking a test that requires NLTK.

    These tests are skipped when NLTK isn't installed.

    ztest requires NLTK)rn   r}   r+   r   rh   rh   ri   require_nltkQ  s    r   c                 C   s   t t d| S )zu
    Decorator marking a test that requires accelerate. These tests are skipped when accelerate isn't installed.
    ztest requires accelerate)rn   r}   r   r   rh   rh   ri   require_accelerate[  s    r   z1.12.0)min_versionc                 C   s   t t|d| | S )zi
    Decorator marking a test that requires fsdp. These tests are skipped when fsdp isn't installed.
    ztest requires torch version >= )rn   r}   r!   )rt   r   rh   rh   ri   require_fsdpb  s    r   c                 C   s   t t d| S )zw
    Decorator marking a test that requires safetensors. These tests are skipped when safetensors isn't installed.
    ztest requires safetensors)rn   r}   r7   r   rh   rh   ri   require_safetensorsk  s    r   c                 C   s   t t d| S )zm
    Decorator marking a test that requires rjieba. These tests are skipped when rjieba isn't installed.
    ztest requires rjieba)rn   r}   r6   r   rh   rh   ri   require_rjiebar  s    r   c                 C   s   t t d| S )zk
    Decorator marking a test that requires jieba. These tests are skipped when jieba isn't installed.
    ztest requires jieba)rn   r}   r$   r   rh   rh   ri   require_jiebay  s    r   c                 C   s   t t d| S )zk
    Decorator marking a test that requires jinja. These tests are skipped when jinja isn't installed.
    ztest requires jinja)rn   r}   r%   r   rh   rh   ri   require_jinja  s    r   c                 C   s   t t d| S )Nztest requires tf2onnx)rn   r}   r@   r   rh   rh   ri   require_tf2onnx  s    r   c                 C   s   t t d| S )Nztest requires ONNX)rn   r}   r,   r   rh   rh   ri   require_onnx  s    r   c                 C   s   t t d| S )zo
    Decorator marking a test that requires Timm.

    These tests are skipped when Timm isn't installed.

    ztest requires Timm)rn   r}   rB   r   rh   rh   ri   require_timm  s    r   c                 C   s   t t d| S )zs
    Decorator marking a test that requires NATTEN.

    These tests are skipped when NATTEN isn't installed.

    ztest requires natten)rn   r}   r*   r   rh   rh   ri   require_natten  s    r   c                 C   s   t t d| S )zu
    Decorator marking a test that requires PyTorch.

    These tests are skipped when PyTorch isn't installed.

    test requires PyTorch)rn   r}   rD   r   rh   rh   ri   require_torch  s    r   c                 C   s   t t d| S )z
    Decorator marking a test that requires Flash Attention.

    These tests are skipped when Flash Attention isn't installed.

    ztest requires Flash Attention)rn   r}   r   r   rh   rh   ri   require_flash_attn  s    r   c                 C   s   t t d| S )zo
    Decorator marking a test that requires PEFT.

    These tests are skipped when PEFT isn't installed.

    ztest requires PEFT)rn   r}   r/   r   rh   rh   ri   require_peft  s    r   c                 C   s   t t d| S )z}
    Decorator marking a test that requires Torchvision.

    These tests are skipped when Torchvision isn't installed.

    ztest requires Torchvision)rn   r}   rO   r   rh   rh   ri   require_torchvision  s    r   c                 C   s   t t pt d| S )z
    Decorator marking a test that requires PyTorch or TensorFlow.

    These tests are skipped when neither PyTorch not TensorFlow is installed.

    z#test requires PyTorch or TensorFlow)rn   r}   rD   rA   r   rh   rh   ri   require_torch_or_tf  s    r   c                 C   s   t t d| S )z
    Decorator marking a test that requires Intel Extension for PyTorch.

    These tests are skipped when Intel Extension for PyTorch isn't installed or it does not match current PyTorch
    version.

    ztest requires Intel Extension for PyTorch to be installed and match current PyTorch version, see https://github.com/intel/intel-extension-for-pytorch)rn   r}   r#   r   rh   rh   ri   #require_intel_extension_for_pytorch  s    r   c                 C   s   t t d| S )z
    Decorator marking a test that requires TensorFlow probability.

    These tests are skipped when TensorFlow probability isn't installed.

    z$test requires TensorFlow probability)rn   r}   r>   r   rh   rh   ri   require_tensorflow_probability  s    r   c                 C   s   t t d| S )zu
    Decorator marking a test that requires torchaudio. These tests are skipped when torchaudio isn't installed.
    ztest requires torchaudio)rn   r}   rM   r   rh   rh   ri   require_torchaudio  s    r   c                 C   s   t t d| S )zu
    Decorator marking a test that requires TensorFlow. These tests are skipped when TensorFlow isn't installed.
    ztest requires TensorFlow)rn   r}   rA   r   rh   rh   ri   
require_tf  s    r   c                 C   s   t t d| S )zv
    Decorator marking a test that requires JAX & Flax. These tests are skipped when one / both are not installed
    ztest requires JAX & Flax)rn   r}   r    r   rh   rh   ri   require_flax   s    r   c                 C   s   t t d| S ){
    Decorator marking a test that requires SentencePiece. These tests are skipped when SentencePiece isn't installed.
    ztest requires SentencePiece)rn   r}   r9   r   rh   rh   ri   require_sentencepiece  s    r   c                 C   s   t t d| S )r   ztest requires Seqio)rn   r}   r:   r   rh   rh   ri   require_seqio  s    r   c                 C   s   t t d| S )zs
    Decorator marking a test that requires Scipy. These tests are skipped when SentencePiece isn't installed.
    ztest requires Scipy)rn   r}   r8   r   rh   rh   ri   require_scipy  s    r   c                 C   s   t t d| S )u   
    Decorator marking a test that requires 🤗 Tokenizers. These tests are skipped when 🤗 Tokenizers isn't installed.
    ztest requires tokenizers)rn   r}   rC   r   rh   rh   ri   require_tokenizers  s    r   c                 C   s   t t d| S )z
    Decorator marking a test that requires tensorflow_text. These tests are skipped when tensroflow_text isn't
    installed.
    ztest requires tensorflow_text)rn   r}   r?   r   rh   rh   ri   require_tensorflow_text#  s    r   c                 C   s   t t d| S )zs
    Decorator marking a test that requires keras_nlp. These tests are skipped when keras_nlp isn't installed.
    ztest requires keras_nlp)rn   r}   r'   r   rh   rh   ri   require_keras_nlp+  s    r   c                 C   s   t t d| S )zm
    Decorator marking a test that requires pandas. These tests are skipped when pandas isn't installed.
    ztest requires pandas)rn   r}   r.   r   rh   rh   ri   require_pandas2  s    r   c                 C   s   t t d| S )zw
    Decorator marking a test that requires PyTesseract. These tests are skipped when PyTesseract isn't installed.
    ztest requires PyTesseract)rn   r}   r3   r   rh   rh   ri   require_pytesseract9  s    r   c                 C   s   t t d| S )z
    Decorator marking a test that requires PyTorch Quantization Toolkit. These tests are skipped when PyTorch
    Quantization Toolkit isn't installed.
    z*test requires PyTorch Quantization Toolkit)rn   r}   r5   r   rh   rh   ri   require_pytorch_quantization@  s    r   c                 C   s   t t d| S )z
    Decorator marking a test that requires the vision dependencies. These tests are skipped when torchaudio isn't
    installed.
    ztest requires vision)rn   r}   rP   r   rh   rh   ri   require_visionJ  s    r   c                 C   s   t t d| S )zi
    Decorator marking a test that requires ftfy. These tests are skipped when ftfy isn't installed.
    ztest requires ftfy)rn   r}   r"   r   rh   rh   ri   require_ftfyR  s    r   c                 C   s   t t d| S )zk
    Decorator marking a test that requires SpaCy. These tests are skipped when SpaCy isn't installed.
    ztest requires spacy)rn   r}   r<   r   rh   rh   ri   require_spacyY  s    r   c                 C   s   t t d| S )zm
    Decorator marking a test that requires decord. These tests are skipped when decord isn't installed.
    ztest requires decord)rn   r}   r   r   rh   rh   ri   require_decord`  s    r   c                 C   s6   t  std| S ddl}t|j dkd| S )a  
    Decorator marking a test that requires a multi-GPU setup (in PyTorch). These tests are skipped on a machine without
    multiple GPUs.

    To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu"
    r   r   Nr   ztest requires multiple GPUsrD   rn   r\   torchr}   cudadevice_countrt   r   rh   rh   ri   require_torch_multi_gpug  s    r   c                 C   s6   t  std| S ddl}t|j dk d| S )zO
    Decorator marking a test that requires 0 or 1 GPU setup (in PyTorch).
    r   r   N   ztest requires 0 or 1 GPUr   r   rh   rh   ri   require_torch_non_multi_gpuv  s    r   c                 C   s6   t  std| S ddl}t|j dk d| S )zT
    Decorator marking a test that requires 0 or 1 or 2 GPU setup (in PyTorch).
    r   r   N   ztest requires 0 or 1 or 2 GPUsr   r   rh   rh   ri   require_torch_up_to_2_gpus  s    r   c                 C   s   t tddd| S )zD
    Decorator marking a test that requires a TPU (in PyTorch).
    FZcheck_deviceztest requires PyTorch TPU)rn   r}   rK   r   rh   rh   ri   require_torch_tpu  s    r   c                 C   s   t tddd| S )zI
    Decorator marking a test that requires NeuronCore (in PyTorch).
    Fr   z test requires PyTorch NeuronCore)rn   r}   rG   r   rh   rh   ri   require_torch_neuroncore  s    r   c                 C   s   t t d| S )zB
    Decorator marking a test that requires NPU (in PyTorch).
    test requires PyTorch NPU)rn   r}   rH   r   rh   rh   ri   require_torch_npu  s    r   c                 C   s.   t  std| S ttj dkd| S )a  
    Decorator marking a test that requires a multi-NPU setup (in PyTorch). These tests are skipped on a machine without
    multiple NPUs.

    To run *only* the multi_npu tests, assuming all test names contain multi_npu: $ pytest -sv ./tests -k "multi_npu"
    r   r   ztest requires multiple NPUs)rH   rn   r\   r}   r   npur   r   rh   rh   ri   require_torch_multi_npu  s    r   c                 C   s   t t d| S )z
    Decorator marking a test that requires XPU and IPEX.

    These tests are skipped when Intel Extension for PyTorch isn't installed or it does not match current PyTorch
    version.
    z$test requires IPEX and an XPU device)rn   r}   rL   r   rh   rh   ri   require_torch_xpu  s    r   c                 C   s.   t  std| S ttj dkd| S )a'  
    Decorator marking a test that requires a multi-XPU setup with IPEX and atleast one XPU device. These tests are
    skipped on a machine without IPEX or multiple XPUs.

    To run *only* the multi_xpu tests, assuming all test names contain multi_xpu: $ pytest -sv ./tests -k "multi_xpu"
    z-test requires IPEX and atleast one XPU devicer   ztest requires multiple XPUs)rL   rn   r\   r}   r   xpur   r   rh   rh   ri   require_torch_multi_xpu  s    r   ZTRANSFORMERS_TEST_DEVICEzUUnknown testing device specified by environment variable `TRANSFORMERS_TEST_DEVICE`: r   r   r   cpuZTRANSFORMERS_TEST_BACKENDz.Failed to import `TRANSFORMERS_TEST_BACKEND` 'zf'! This should be the name of an installed module. The original error (look up to see its traceback):
c                 C   s   t t d| S )z2Decorator marking a test that requires TorchDynamoztest requires TorchDynamo)rn   r}   rN   r   rh   rh   ri   require_torchdynamo  s    r   c                 C   s   t t d| S )z8Decorator marking a test that requires Torch-TensorRT FXztest requires Torch-TensorRT FX)rn   r}   rI   r   rh   rh   ri   require_torch_tensorrt_fx  s    r   c                 C   s   t tdkd| S )z8Decorator marking a test that requires CUDA and PyTorch.r   ztest requires CUDA)rn   r}   torch_devicer   rh   rh   ri   require_torch_gpu  s    r   c                 C   s   t t d| S )zbDecorator marking a test that requires torch>=1.10, using Ampere GPU or newer arch with cuda>=11.0zItest requires torch>=1.10, using Ampere GPU or newer arch with cuda>=11.0)rn   r}   rF   r   rh   rh   ri   require_torch_bf16_gpu  s    r   c                 C   s   t t d| S )z>Decorator marking a test that requires torch>=1.10, using CPU.z$test requires torch>=1.10, using CPU)rn   r}   rE   r   rh   rh   ri   require_torch_bf16_cpu  s    r   c                 C   s   t t d| S )z[Decorator marking a test that requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7.zAtest requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7)rn   r}   rJ   r   rh   rh   ri   require_torch_tf32  s     r   c                 C   s   t t d| S )z2Decorator marking a test that requires detectron2.ztest requires `detectron2`)rn   r}   r   r   rh   rh   ri   require_detectron2  s    r   c                 C   s   t t d| S )z-Decorator marking a test that requires faiss.ztest requires `faiss`)rn   r}   r   r   rh   rh   ri   require_faiss"  s    r   c                 C   s   t t d| S )zs
    Decorator marking a test that requires optuna.

    These tests are skipped when optuna isn't installed.

    ztest requires optuna)rn   r}   r   r   rh   rh   ri   require_optuna'  s    r   c                 C   s   t t d| S )zw
    Decorator marking a test that requires Ray/tune.

    These tests are skipped when Ray/tune isn't installed.

    ztest requires Ray/tune)rn   r}   r   r   rh   rh   ri   require_ray1  s    r   c                 C   s   t t d| S )zs
    Decorator marking a test that requires SigOpt.

    These tests are skipped when SigOpt isn't installed.

    ztest requires SigOpt)rn   r}   r   r   rh   rh   ri   require_sigopt;  s    r   c                 C   s   t t d| S )zq
    Decorator marking a test that requires wandb.

    These tests are skipped when wandb isn't installed.

    ztest requires wandb)rn   r}   r   r   rh   rh   ri   require_wandbE  s    r   c                 C   s   t t d| S )zp
    Decorator marking a test requires clearml.

    These tests are skipped when clearml isn't installed.

    ztest requires clearml)rn   r}   r   r   rh   rh   ri   require_clearmlO  s    r   c                 C   s   t t d| S )zx
    Decorator marking a test that requires soundfile

    These tests are skipped when soundfile isn't installed.

    ztest requires soundfile)rn   r}   r;   r   rh   rh   ri   require_soundfileY  s    r   c                 C   s   t t d| S )z:
    Decorator marking a test that requires deepspeed
    ztest requires deepspeed)rn   r}   r   r   rh   rh   ri   require_deepspeedc  s    r   c                 C   s   t t d| S )z:
    Decorator marking a test that requires fairscale
    ztest requires fairscale)rn   r}   r   r   rh   rh   ri   require_fairscalej  s    r   c                 C   s   t t d| S )z5
    Decorator marking a test that requires apex
    ztest requires apex)rn   r}   r   r   rh   rh   ri   require_apexq  s    r   c                 C   s   t t d| S )z7
    Decorator for bits and bytes (bnb) dependency
    ztest requires bnb)rn   r}   r   r   rh   rh   ri   require_bitsandbytesx  s    r   c                 C   s   t t d| S )z*
    Decorator for optimum dependency
    ztest requires optimum)rn   r}   r-   r   rh   rh   ri   require_optimum  s    r   c                 C   s   t t d| S )z,
    Decorator for auto_gptq dependency
    ztest requires auto-gptq)rn   r}   r   r   rh   rh   ri   require_auto_gptq  s    r   c                 C   s   t t d| S )z;
    Decorator marking a test that requires phonemizer
    ztest requires phonemizer)rn   r}   r0   r   rh   rh   ri   require_phonemizer  s    r   c                 C   s   t t d| S )z<
    Decorator marking a test that requires pyctcdecode
    ztest requires pyctcdecode)rn   r}   r2   r   rh   rh   ri   require_pyctcdecode  s    r   c                 C   s   t t d| S )z8
    Decorator marking a test that requires librosa
    ztest requires librosa)rn   r}   r)   r   rh   rh   ri   require_librosa  s    r   c                 C   s   t t d| S )z9
    Decorator marking a test that requires essentia
    ztest requires essentia)rn   r}   r   r   rh   rh   ri   require_essentia  s    r   c                 C   s   t t d| S )z<
    Decorator marking a test that requires pretty_midi
    ztest requires pretty_midi)rn   r}   r1   r   rh   rh   ri   require_pretty_midi  s    r   c                 C   s   t | d k	S N)shutilwhich)cmdrh   rh   ri   
cmd_exists  s    r   c                 C   s   t tdd| S )z@
    Decorator marking a test that requires `/usr/bin/time`
    /usr/bin/timeztest requires /usr/bin/time)rn   r}   r   r   rh   rh   ri   require_usr_bin_time  s    r   c                 C   s   t t d| S )z8
    Decorator marking a test that requires sudachi
    ztest requires sudachi)rn   r}   r=   r   rh   rh   ri   require_sudachi  s    r   c                 C   s   t t d| S )8
    Decorator marking a test that requires jumanpp
    ztest requires jumanpp)rn   r}   r&   r   rh   rh   ri   require_jumanpp  s    r   c                 C   s   t t d| S )r   ztest requires cython)rn   r}   r   r   rh   rh   ri   require_cython  s    r   c                  C   sT   t  rddl} | j S t r6ddl}t|jdS t	 rLddl
}| S dS dS )z^
    Return the number of available gpus (regardless of whether torch, tf or jax is used)
    r   NZGPU)rD   r   r   r   rA   
tensorflowlenconfigZlist_physical_devicesr    jax)r   tfr   rh   rh   ri   get_gpu_count  s    
r   c                 C   sV   t  d d }tjtj|}|ds<tj|}q$| rNtj|| S |S dS )a  
    Args:
        append_path: optional path to append to the tests dir path

    Return:
        The full path to the `tests` dir, so that the tests can be invoked from anywhere. Optionally `append_path` is
        joined after the `tests` dir the former is provided.

    r   testsN)inspectstackr_   pathabspathdirnameendswithjoin)Zappend_pathZcaller__file__	tests_dirrh   rh   ri   get_tests_dir  s    
r   c                 C   s   t dd| dt jS )Nz^.*\r r   )resubM)bufrh   rh   ri   apply_print_resets
  s    r   c                 C   s:   t |  }|| }|dks6td| d| d S )Nzexpecting to find z in output: f)r   lowerfindAssertionError)outwhatZout_prZ	match_strrh   rh   ri   assert_screenout  s    r  c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )
CaptureStdav  
    Context manager to capture:

        - stdout: replay it, clean it up and make it available via `obj.out`
        - stderr: replay it and make it available via `obj.err`

    Args:
        out (`bool`, *optional*, defaults to `True`): Whether to capture stdout or not.
        err (`bool`, *optional*, defaults to `True`): Whether to capture stderr or not.
        replay (`bool`, *optional*, defaults to `True`): Whether to replay or not.
            By default each captured stream gets replayed back on context's exit, so that one can see what the test was
            doing. If this is a not wanted behavior and the captured data shouldn't be replayed, pass `replay=False` to
            disable this feature.

    Examples:

    ```python
    # to capture stdout only with auto-replay
    with CaptureStdout() as cs:
        print("Secret message")
    assert "message" in cs.out

    # to capture stderr only with auto-replay
    import sys

    with CaptureStderr() as cs:
        print("Warning: ", file=sys.stderr)
    assert "Warning" in cs.err

    # to capture both streams with auto-replay
    with CaptureStd() as cs:
        print("Secret message")
        print("Warning: ", file=sys.stderr)
    assert "message" in cs.out
    assert "Warning" in cs.err

    # to capture just one of the streams, and not the other, with auto-replay
    with CaptureStd(err=False) as cs:
        print("Secret message")
    assert "message" in cs.out
    # but best use the stream-specific subclasses

    # to capture without auto-replay
    with CaptureStd(replay=False) as cs:
        print("Secret message")
    assert "message" in cs.out
    ```Tc                 C   sJ   || _ |rt | _d| _nd | _d| _|r:t | _d| _nd | _d| _d S )Nz=error: CaptureStd context is unfinished yet, called too earlyznot capturing stdoutznot capturing stderr)replayr   out_bufr   err_buferr)selfr   r  r  rh   rh   ri   __init__E  s    zCaptureStd.__init__c                 C   s0   | j rtj| _| j t_| jr,tj| _| jt_| S r   )r  sysstdoutout_oldr  stderrerr_oldr  rh   rh   ri   	__enter__V  s    zCaptureStd.__enter__c                 G   sh   | j r4| jt_| j  }| jr*tj| t|| _| j	rd| j
t_| j	 }| jr^tj| || _d S r   )r  r  r
  r  getvaluer  writer   r   r  r  r  r  )r  excZcapturedrh   rh   ri   __exit__a  s    


zCaptureStd.__exit__c                 C   s8   d}| j r|d| j d7 }| jr4|d| j d7 }|S )Nr   zstdout: 
stderr: )r  r   r  r  )r  msgrh   rh   ri   __repr__p  s    zCaptureStd.__repr__N)TTT__name__
__module____qualname____doc__r	  r  r  r  rh   rh   rh   ri   r    s
   0
r  c                       s"   e Zd ZdZd fdd	Z  ZS )CaptureStdoutz+Same as CaptureStd but captures only stdoutTc                    s   t  jd|d d S )NF)r  r  superr	  r  r  	__class__rh   ri   r	    s    zCaptureStdout.__init__)Tr  r  r  r  r	  __classcell__rh   rh   r"  ri   r    s   r  c                       s"   e Zd ZdZd fdd	Z  ZS )CaptureStderrz+Same as CaptureStd but captures only stderrTc                    s   t  jd|d d S )NF)r   r  r  r!  r"  rh   ri   r	    s    zCaptureStderr.__init__)Tr$  rh   rh   r"  ri   r&    s   r&  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )CaptureLoggera:  
    Context manager to capture `logging` streams

    Args:
        logger: 'logging` logger object

    Returns:
        The captured output is available via `self.out`

    Example:

    ```python
    >>> from transformers import logging
    >>> from transformers.testing_utils import CaptureLogger

    >>> msg = "Testing 1, 2, 3"
    >>> logging.set_verbosity_info()
    >>> logger = logging.get_logger("transformers.models.bart.tokenization_bart")
    >>> with CaptureLogger(logger) as cl:
    ...     logger.info(msg)
    >>> assert cl.out, msg + "
"
    ```
    c                 C   s&   || _ t | _t| j| _d| _d S )Nr   )loggerr   ior   StreamHandlershr   )r  r(  rh   rh   ri   r	    s    zCaptureLogger.__init__c                 C   s   | j | j | S r   )r(  
addHandlerr+  r  rh   rh   ri   r    s    zCaptureLogger.__enter__c                 G   s   | j | j | j | _d S r   )r(  removeHandlerr+  r)  r  r   )r  r  rh   rh   ri   r    s    zCaptureLogger.__exit__c                 C   s   d| j  dS )Nz
captured: r  )r   r  rh   rh   ri   r    s    zCaptureLogger.__repr__Nr  rh   rh   rh   ri   r'    s
   r'  c              	   c   s.   t  }zt |  dV  W 5 t | X dS )aT  
    This is a context manager to temporarily change transformers modules logging level to the desired value and have it
    restored to the original setting at the end of the scope.

    Example:

    ```python
    with LoggingLevel(logging.INFO):
        AutoModel.from_pretrained("gpt2")  # calls logger.info() several times
    ```
    N)transformers_loggingZget_verbosityset_verbosity)levelZ
orig_levelrh   rh   ri   LoggingLevel  s
    

r1  )r   returnc              	   c   s6   t | } ztjd|  dV  W 5 tj|  X dS )z
    Temporary add given path to `sys.path`.

    Usage :

    ```python
    with ExtendSysPath("/path/to/dir"):
        mymodule = importlib.import_module("mymodule")
    ```
    r   N)r_   fspathr
  r   removeinsert)r   rh   rh   ri   ExtendSysPath  s
    

r6  c                   @   s   e Zd ZdZdd Zedd Zedd Zedd	 Zed
d Z	edd Z
edd Zedd Zedd Zedd Zedd Zedd Zedd Zdd Zd%dd Zd!d" Zd#d$ ZdS )&TestCasePlusa  
    This class extends *unittest.TestCase* with additional features.

    Feature 1: A set of fully resolved important file and dir path accessors.

    In tests often we need to know where things are relative to the current test file, and it's not trivial since the
    test could be invoked from more than one directory or could reside in sub-directories with different depths. This
    class solves this problem by sorting out all the basic paths and provides easy accessors to them:

    - `pathlib` objects (all fully resolved):

       - `test_file_path` - the current test file path (=`__file__`)
       - `test_file_dir` - the directory containing the current test file
       - `tests_dir` - the directory of the `tests` test suite
       - `examples_dir` - the directory of the `examples` test suite
       - `repo_root_dir` - the directory of the repository
       - `src_dir` - the directory of `src` (i.e. where the `transformers` sub-dir resides)

    - stringified paths---same as above but these return paths as strings, rather than `pathlib` objects:

       - `test_file_path_str`
       - `test_file_dir_str`
       - `tests_dir_str`
       - `examples_dir_str`
       - `repo_root_dir_str`
       - `src_dir_str`

    Feature 2: Flexible auto-removable temporary dirs which are guaranteed to get removed at the end of test.

    1. Create a unique temporary dir:

    ```python
    def test_whatever(self):
        tmp_dir = self.get_auto_remove_tmp_dir()
    ```

    `tmp_dir` will contain the path to the created temporary dir. It will be automatically removed at the end of the
    test.


    2. Create a temporary dir of my choice, ensure it's empty before the test starts and don't
    empty it after the test.

    ```python
    def test_whatever(self):
        tmp_dir = self.get_auto_remove_tmp_dir("./xxx")
    ```

    This is useful for debug when you want to monitor a specific directory and want to make sure the previous tests
    didn't leave any data in there.

    3. You can override the first two options by directly overriding the `before` and `after` args, leading to the
        following behavior:

    `before=True`: the temporary dir will always be cleared at the beginning of the test.

    `before=False`: if the temporary dir already existed, any existing files will remain there.

    `after=True`: the temporary dir will always be deleted at the end of the test.

    `after=False`: the temporary dir will always be left intact at the end of the test.

    Note 1: In order to run the equivalent of `rm -r` safely, only subdirs of the project repository checkout are
    allowed if an explicit `tmp_dir` is used, so that by mistake no `/tmp` or similar important part of the filesystem
    will get nuked. i.e. please always pass paths that start with `./`

    Note 2: Each test can register multiple temporary dirs and they all will get auto-removed, unless requested
    otherwise.

    Feature 3: Get a copy of the `os.environ` object that sets up `PYTHONPATH` specific to the current test suite. This
    is useful for invoking external programs from the test suite - e.g. distributed training.


    ```python
    def test_whatever(self):
        env = self.get_env()
    ```c                 C   s   g | _ t| j| _t| j }|jd | _dD ]*}|j| }|d 	 r2|d 	 r2 q^q2|rj|| _
ntd| j | j
d | _| j
d | _| j
d | _d S )Nr   )r   r   r   srcr   z+can't figure out the root of the repo from examples)teardown_tmp_dirsr   getfiler#  _test_file_pathr   resolveparents_test_file_diris_dir_repo_root_dirrb   
_tests_dir_examples_dir_src_dir)r  r   uptmp_dirrh   rh   ri   setUp2  s    
zTestCasePlus.setUpc                 C   s   | j S r   )r<  r  rh   rh   ri   test_file_pathF  s    zTestCasePlus.test_file_pathc                 C   s
   t | jS r   )strr<  r  rh   rh   ri   test_file_path_strJ  s    zTestCasePlus.test_file_path_strc                 C   s   | j S r   )r?  r  rh   rh   ri   test_file_dirN  s    zTestCasePlus.test_file_dirc                 C   s
   t | jS r   )rI  r?  r  rh   rh   ri   test_file_dir_strR  s    zTestCasePlus.test_file_dir_strc                 C   s   | j S r   )rB  r  rh   rh   ri   r   V  s    zTestCasePlus.tests_dirc                 C   s
   t | jS r   )rI  rB  r  rh   rh   ri   tests_dir_strZ  s    zTestCasePlus.tests_dir_strc                 C   s   | j S r   )rC  r  rh   rh   ri   examples_dir^  s    zTestCasePlus.examples_dirc                 C   s
   t | jS r   )rI  rC  r  rh   rh   ri   examples_dir_strb  s    zTestCasePlus.examples_dir_strc                 C   s   | j S r   )rA  r  rh   rh   ri   repo_root_dirf  s    zTestCasePlus.repo_root_dirc                 C   s
   t | jS r   )rI  rA  r  rh   rh   ri   repo_root_dir_strj  s    zTestCasePlus.repo_root_dir_strc                 C   s   | j S r   )rD  r  rh   rh   ri   src_dirn  s    zTestCasePlus.src_dirc                 C   s
   t | jS r   )rI  rD  r  rh   rh   ri   src_dir_strr  s    zTestCasePlus.src_dir_strc                 C   sZ   t j }| jg}d| jkr*|| j n|| j ||dd d	||d< |S )a  
        Return a copy of the `os.environ` object that sets up `PYTHONPATH` correctly, depending on the test suite it's
        invoked from. This is useful for invoking external programs from the test suite - e.g. distributed training.

        It always inserts `./src` first, then `./tests` or `./examples` depending on the test suite type and finally
        the preset `PYTHONPATH` if any (all full resolved paths).

        z	/examples
PYTHONPATHr   :)
r_   r`   copyrS  rL  appendrO  rM  getr   )r  envpathsrh   rh   ri   get_envv  s    	

zTestCasePlus.get_envNc                 C   s   |dk	rt|dkrd}|dkr d}t | }|dsFtd| d|dkrd| rdtj|dd |jddd n |dkrd}|dkrd}t	 }|dkr| j
| |S )	a  
        Args:
            tmp_dir (`string`, *optional*):
                if `None`:

                   - a unique temporary path will be created
                   - sets `before=True` if `before` is `None`
                   - sets `after=True` if `after` is `None`
                else:

                   - `tmp_dir` will be created
                   - sets `before=True` if `before` is `None`
                   - sets `after=False` if `after` is `None`
            before (`bool`, *optional*):
                If `True` and the `tmp_dir` already exists, make sure to empty it right away if `False` and the
                `tmp_dir` already exists, any existing files will remain there.
            after (`bool`, *optional*):
                If `True`, delete the `tmp_dir` at the end of the test if `False`, leave the `tmp_dir` and its contents
                intact at the end of the test.

        Returns:
            tmp_dir(`string`): either the same value as passed via *tmp_dir* or the path to the auto-selected tmp dir
        NTFz./zI`tmp_dir` can only be a relative path, i.e. `./some/path`, but received ``ignore_errorsr>  exist_ok)r   r=  
startswithrb   existsr   rmtreemkdirtempfilemkdtempr:  rW  )r  rF  beforeafterr   rh   rh   ri   get_auto_remove_tmp_dir  s*    

z$TestCasePlus.get_auto_remove_tmp_dirc              	   C   sh   t dstdtd| d}t }t||  d W 5 Q R X t|jdd 	dd	d
 }|S )a  
        Runs the passed python one liner (just the code) and returns how much max cpu memory was used to run the
        program.

        Args:
            one_liner_str (`string`):
                a python one liner code that gets passed to `python -c`

        Returns:
            max cpu memory bytes used to run the program. This value is likely to vary slightly from run to run.

        Requirements:
            this helper needs `/usr/bin/time` to be installed (`apt install time`)

        Example:

        ```
        one_liner_str = 'from transformers import AutoModel; AutoModel.from_pretrained("t5-large")'
        max_rss = self.python_one_liner_max_rss(one_liner_str)
        ```
        r   z:/usr/bin/time is required, install with `apt install time`z/usr/bin/time -f %M python -c ''rY  r  r  r   i   )
r   rb   shlexsplitr  execute_subprocess_asyncr[  rk   r  replace)r  Zone_liner_strr   csZmax_rssrh   rh   ri   python_one_liner_max_rss  s     z%TestCasePlus.python_one_liner_max_rssc                 C   s^   | j D ]}tj|dd qg | _ t rZt  t  ttj	
 D ]}d|krDtj	|= qDd S )NTr]  Z
ACCELERATE)r:  r   rc  r   rR   Z_reset_staterS   listr_   r`   keys)r  r   krh   rh   ri   tearDown  s    
zTestCasePlus.tearDown)NNN)r  r  r  r  rG  propertyrH  rJ  rK  rL  r   rM  rN  rO  rP  rQ  rR  rS  r[  ri  rr  rv  rh   rh   rh   ri   r7    s<   N












D!r7  c                  K   s   t jtj| S )z
    this is a convenience wrapper, that allows this ::

    @mockenv(RUN_SLOW=True, USE_TF=False) def test_something():
        run_slow = os.getenv("RUN_SLOW", False) use_tf = os.getenv("USE_TF", False)

    )r
   patchdictr_   r`   )kwargsrh   rh   ri   mockenv  s    r{  c               	   /   s   t j |pi }| pg } t| t| B t  @ } fdd|D }t fdd|D }z& |  fdd| D  dV  W 5  |  fdd|D  X dS )	aM  
    Temporarily updates the `os.environ` dictionary in-place. Similar to mockenv

    The `os.environ` dictionary is updated in-place so that the modification is sure to work in all situations.

    Args:
      remove: Environment variables to remove.
      update: Dictionary of environment variables and values to add/update.
    c                    s   i | ]}| | qS rh   rh   .0ru  rk  rh   ri   
<dictcomp>  s      z#mockenv_context.<locals>.<dictcomp>c                 3   s   | ]}| kr|V  qd S r   rh   r|  rk  rh   ri   	<genexpr>  s      z"mockenv_context.<locals>.<genexpr>c                    s   g | ]}  |qS rh   popr|  rk  rh   ri   
<listcomp>&  s     z#mockenv_context.<locals>.<listcomp>c                    s   g | ]}  |d qS r   r  r|  rk  rh   ri   r  "  s     N)r_   r`   setrt  	frozensetupdate)r4  r  ZstompedZupdate_afterZremove_afterrh   rk  ri   mockenv_context
  s     


r  c                 C   s*   d}|t kr&| j|dddd dt |< dS )z
    This function is to be called from `conftest.py` via `pytest_addoption` wrapper that has to be defined there.

    It allows loading both `conftest.py` files at once without causing a failure due to adding the same `pytest`
    option.

    z--make-reportsstoreFzSgenerate report files. The value of this option is used as a prefix to report names)actionre   helpr   N)pytest_opt_registeredZ	addoption)parseroptionrh   rh   ri   pytest_addoption_shared/  s    r  c              
      s  ddl m} t|sd}| j}| }|jj}| j}d|  t j	ddd  fddd	D }g }| j
 D ]"}	|	D ]}
t|
d
rx||
 qxqp|r<|jdd dd t|d d|}d}|d t|D ]^\}}
|
j|k r
|t||  d| d  q2||
jdd|
jdd|
j d qW 5 Q R X dd }d|j_t|d d}|||| _|   W 5 Q R X t|d d}|||| _||  W 5 Q R X d|j_t|d d}|||| _|   W 5 Q R X t|d  d}|||| _|   W 5 Q R X t|d! d"}|||| _|   |   W 5 Q R X d"| _t|d# d}|||| _|   W 5 Q R X t|d$ d}|||| _|   W 5 Q R X || _|| _||j_d%S )&a  
    Generate multiple reports at the end of test suite run - each report goes into a dedicated file in the current
    directory. The report files are prefixed with the test suite name.

    This function emulates --duration and -rA pytest arguments.

    This function is to be called from `conftest.py` via `pytest_terminal_summary` wrapper that has to be defined
    there.

    Args:
    - tr: `terminalreporter` passed from `conftest.py`
    - id: unique id like `tests` or `examples` that will be incorporated into the final reports filenames - this is
      needed as some jobs have multiple runs of pytest, so we can't have them overwrite each other.

    NB: this functions taps into a private _pytest API and while unlikely, it could break should pytest do internal
    changes - also it calls default internal methods of terminalreporter which can be hijacked by various `pytest-`
    plugins and interfere.

    r   )create_terminal_writerr   zreports/Tr_  c                    s   i | ]}|  d | dqS )/z.txtrh   r|  dirrh   ri   r~  b  s    z0pytest_terminal_summary_main.<locals>.<dictcomp>)		durationserrorsfailures_longfailures_shortfailures_lineZpassesstatssummary_shortwarningsdurationc                 S   s   | j S r   )r  xrh   rh   ri   <lambda>z      z.pytest_terminal_summary_main.<locals>.<lambda>)rd   reverser  wg?zslowest durations
z durations < z secs were omittedz02.2fzs z<8 r  c              	   S   sp   |  d}|sd S | dd |D ]H}| |}| jd|ddd tdd|jd	tjtjB }| j	| q"d S )
Nfailed=zFAILURES SHORT STACK_T)redboldz.*_ _ _ (_ ){10,}_ _ r   r   )
Z
getreportsZ	write_sepZ_getfailureheadliner   r   Zlongreprtextr   S_twline)trZreportsrepr  Zlongreprrh   rh   ri   summary_failures_short  s    

z<pytest_terminal_summary_main.<locals>.summary_failures_shortautor  r  r  r  r  r  ZwPpsxXEfr  r  N)Z_pytest.configr  r   r   Zget_terminal_writerr  ZtbstyleZreportcharsr   rd  r  valueshasattrrW  sortopenr  	enumerater  whenZnodeidr  Zsummary_failuresZsummary_errorsZsummary_warningsZshort_test_summaryZsummary_stats)r  idr  r   Zorig_writerZorig_tbstyleZorig_reportcharsZreport_filesZdlistZreplistr  fZdurations_minir  rh   r  ri   pytest_terminal_summary_mainB  sp    



2	r  c                   @   s   e Zd Zdd ZdS )
_RunOutputc                 C   s   || _ || _|| _d S r   )
returncoder  r  )r  r  r  r  rh   rh   ri   r	    s    z_RunOutput.__init__N)r  r  r  r	  rh   rh   rh   ri   r    s   r  c                    s$   |   I d H }|r || q q q d S r   )readline)streamcallbackr  rh   rh   ri   _read_stream  s    
r  r2  c                    s   |rt dd|  tj| d f| dd  |tjjtjj|dI d H }g g  dfdd	tjt|jfd	d
t|j	 fdd
g|dI d H  t
| I d H  S )Nz

Running: r  r   r   )stdinr  r  rY  r   c                    s.   |  d } ||   s*t|| |d d S )Nutf-8file)decoderstriprW  print)r  Zsinkpipelabel)quietrh   ri   tee  s    
z_stream_subprocess.<locals>.teec                    s   |  t jddS )Nzstdout:r  )r
  r  l)r   r  rh   ri   r    r  z$_stream_subprocess.<locals>.<lambda>c                    s   |  t jddS )Nzstderr:r  )r
  r  r  )r  r  rh   ri   r    r  timeout)r   )r  r   asynciocreate_subprocess_exec
subprocessPIPEwaitr  r  r  r  )r   rY  r  r  r  echoprh   )r  r   r  r  ri   _stream_subprocess  s,    
r     c           
   
   C   s~   t  }|t| |||||d}d| }|jdkr^d|j}	td| d|j d|	 |jsz|jsztd| d|S )	N)rY  r  r  r  r  r  r   r  rj  z' failed with returncode z,

The combined stderr from workers follows:
z' produced no output.)	r  get_event_looprun_until_completer  r   r  r  RuntimeErrorr  )
r   rY  r  r  r  r  loopresultZcmd_strr  rh   rh   ri   ro    s    

ro  c                  C   s*   t jdd} tdd| dtj} t| S )z
    Returns an int value of worker's numerical id under `pytest-xdist`'s concurrent workers `pytest -n N` regime, or 0
    if `-n 1` or `pytest-xdist` isn't being used.
    ZPYTEST_XDIST_WORKERZgw0z^gwr   r   )r_   r`   rX  r   r   r   rk   )Zworkerrh   rh   ri   pytest_xdist_worker_id  s    r  c                  C   s   d} t  }| | S )z
    Returns a port number that can be fed to `torch.distributed.launch`'s `--master_port` argument.

    Under `pytest-xdist` it adds a delta number based on a worker id so that concurrent tests don't try to use the same
    port at once.
    i<s  )r  )portZ
uniq_deltarh   rh   ri   get_torch_dist_unique_port&  s    r  r   c                    s,  ddl }t| tr$ fdd| D S t| trDt fdd| D S t| |jr\t|  S t| tr| fdd|  D S t| t	t
|jfr| S | dkr| S t rt| tjrt|   S t rt| rt|    S t| t rt|  S t| |j|jfrt|   S tdt|  dS )	z
    Simplifies an object by rounding float numbers, and downcasting tensors/numpy arrays to get simple equality test
    within tests.
    r   Nc                    s   g | ]}t | qS rh   nested_simplifyr}  itemdecimalsrh   ri   r  :  s     z#nested_simplify.<locals>.<listcomp>c                    s   g | ]}t | qS rh   r  r  r  rh   ri   r  <  s     c                    s"   i | ]\}}t | t | qS rh   r  )r}  ru  vr  rh   ri   r~  @  s      z#nested_simplify.<locals>.<dictcomp>zNot supported: )numpy
isinstancers  tupleZndarrayr  tolistr   itemsrI  rk   Zint64rD   r   ZTensorrA   r   Z	is_tensorfloatroundZint32Zfloat32r  	Exceptiontype)objr  nprh   r  ri   r  2  s,    



r  c              	   C   s   t | d}| }t|dkr2|d dkstnrt|dksBt|d  dksVt|dd D ],}t|d t|d   }|dksbtqb|d  d	kstW 5 Q R X d S )
Nrr   r   z{}r   {r   r   })r  	readlinesr   r   striplstrip)	file_pathr  linesr  Zleft_indentrh   rh   ri   "check_json_file_has_correct_formatQ  s    r  c                 C   s   t | tjjr| S | | fS r   )r  collectionsabcr   r  rh   rh   ri   	to_2tupleb  s    r  c                   @   s   e Zd ZdS )SubprocessCallExceptionN)r  r  r  rh   rh   rh   ri   r  i  s   r  )commandc              
   C   s~   z2t j| t jd}|r0t|dr*|d}|W S W nF t jk
rx } z&tdd|  d|j  |W 5 d}~X Y nX dS )z
    Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture
    if an error occured while running `command`
    )r  r  r  z	Command `r  z$` failed with the following error:

N)	r  check_outputSTDOUTr  r  CalledProcessErrorr  r   output)r  Zreturn_stdoutr  erh   rh   ri   run_commandm  s    


r  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	RequestCounterz@
    Helper class that will count all requests made online.
    c                    sH   d _ d _d _tjjj _t	  _
 j j
_ fddtjj_ S )Nr   c                      s    j S r   )sessionrh   r  rh   ri   r    r  z*RequestCounter.__enter__.<locals>.<lambda>)head_request_countget_request_countother_request_counthuggingface_hubutils_httpget_sessionold_get_sessionrequestsSessionr  new_requestrequestr  rh   r  ri   r    s    

zRequestCounter.__enter__c                 O   s   | j tjj_d S r   )r  r  r  r  r  )r  argsrz  rh   rh   ri   r    s    zRequestCounter.__exit__c                 K   sR   |dkr|  j d7  _ n&|dkr0|  jd7  _n|  jd7  _tjf d|i|S )NGETr   HEADmethod)r	  r  r
  r  r  )r  r  rz  rh   rh   ri   r    s    zRequestCounter.new_requestN)r  r  r  r  r  r  r  rh   rh   rh   ri   r  ~  s   r     )max_attemptswait_before_retrydescriptionc                    s    fdd}|S )a  
    To decorate flaky tests. They will be retried on failures.

    Args:
        max_attempts (`int`, *optional*, defaults to 5):
            The maximum number of attempts to retry the flaky test.
        wait_before_retry (`float`, *optional*):
            If provided, will wait that number of seconds before retrying the test.
        description (`str`, *optional*):
            A string to describe the situation (what / where / why is flaky, link to GH issue/PR comments, errors,
            etc.)
    c                    s   t   fdd}|S )Nc                     s   d}| k rzz| |W S  t k
rv } z@td| d| d  dtjd d k	r^t |d7 }W 5 d }~X Y qX q| |S )Nr   zTest failed with z at try r  .r  )r  r  r
  r  timesleep)r  rz  Zretry_countr  )r  test_func_refr  rh   ri   wrapper  s    "
z,is_flaky.<locals>.decorator.<locals>.wrapper)	functoolswraps)r  r   r  r  )r  ri   	decorator  s    zis_flaky.<locals>.decoratorrh   )r  r  r  r$  rh   r#  ri   is_flaky  s    r%  c              
   C   s   |dkrt tjdd}d}t|}|d}|d}|j||d |j	||||fd}|
  z|j|d}	|  W n4 tk
r }
 z|  | |
 W 5 d}
~
X Y nX |j|d |	d dk	r| |	d   dS )	a  
    To run a test in a subprocess. In particular, this can avoid (GPU) memory issue.

    Args:
        test_case (`unittest.TestCase`):
            The test that will run `target_func`.
        target_func (`Callable`):
            The function implementing the actual testing logic.
        inputs (`dict`, *optional*, defaults to `None`):
            The inputs that will be passed to `target_func` through an (input) queue.
        timeout (`int`, *optional*, defaults to `None`):
            The timeout (in seconds) that will be passed to the input and output queues. If not specified, the env.
            variable `PYTEST_TIMEOUT` will be checked. If still `None`, its value will be set to `600`.
    NZPYTEST_TIMEOUTiX  spawnr   r  )targetr  error)rk   r_   r`   rX  multiprocessingZget_contextQueueZJoinableQueueputProcessstart	task_doner  	terminateZfailr   )rt   Ztarget_funcinputsr  Zstart_methohdctxZinput_queueZoutput_queueprocessresultsr  rh   rh   ri   run_test_in_subprocess  s$    


r4  c                 C   s   d}t t j|t jt jB d| }d}t|D ]R\}}d|krXd|krXt dd|||< d|kshd	|kr.t d
|r.|r.d} qq.d}|sd|}|S )a  Prepare a docstring or a `.md` file to be run by doctest.

    The argument `string` would be the whole file content if it is a `.md` file. For a python file, it would be one of
    its docstring. In each case, it may contain multiple python code examples. If `skip_cuda_tests` is `True` and a
    cuda stuff is detective (with a heuristic), this method will return an empty string so no doctest will be run for
    `string`.
    z1(```(?:python|py)\s*\n\s*>>> )((?:.*?\n)*?.*?```))flagsFzload_dataset(z# doctest: +IGNORE_RESULTz(>>> .*load_dataset\(.*)z\1 # doctest: +IGNORE_RESULTz>>>z...zcuda|to\(0\)|device=0Tr   )	r   rn  compile	MULTILINEDOTALLr  r   searchr   )stringskip_cuda_testsZcodeblock_patternZ
codeblocksZis_cuda_foundr  Z	codeblockZmodified_stringrh   rh   ri   preprocess_string  s(    

r<  c                       sR   e Zd ZU dZedejejB Ze	e
jddZe	ed< d	 fdd	Z  ZS )
HfDocTestParsera  
    Overwrites the DocTestParser from doctest to properly parse the codeblocks that are formatted with black. This
    means that there are no extra lines at the end of our snippets. The `# doctest: +IGNORE_RESULT` marker is also
    added anywhere a `load_dataset` call is made as a print would otherwise fail the corresponding line.

    Tests involving cuda are skipped base on a naive pattern that should be updated if it is not enough.
    a  
        # Source consists of a PS1 line followed by zero or more PS2 lines.
        (?P<source>
            (?:^(?P<indent> [ ]*) >>>    .*)    # PS1 line
            (?:\n           [ ]*  \.\.\. .*)*)  # PS2 lines
        \n?
        # Want consists of any non-blank lines that do not start with PS1.
        (?P<want> (?:(?![ ]*$)    # Not a blank line
             (?![ ]*>>>)          # Not a line starting with PS1
             # !!!!!!!!!!! HF Specific !!!!!!!!!!!
             (?:(?!```).)*        # Match any character except '`' until a '```' is found (this is specific to HF because black removes the last line)
             # !!!!!!!!!!! HF Specific !!!!!!!!!!!
             (?:\n|$)  # Match a new line or end of string
          )*)
        ZSKIP_CUDA_DOCTESTFr;  <string>c                    s   t || j}t ||S )z
        Overwrites the `parse` method to incorporate a skip for CUDA tests, and remove logs and dataset prints before
        calling `super().parse`
        )r<  r;  r   parse)r  r:  namer"  rh   ri   r?  8  s    zHfDocTestParser.parse)r>  )r  r  r  r  r   r6  r7  VERBOSEZ_EXAMPLE_REboolr_   r`   rX  r;  __annotations__r?  r%  rh   rh   r"  ri   r=    s   

r=  c                   @   s"   e Zd ZdZee dddZdS )HfDoctestModulez
    Overwrites the `DoctestModule` of the pytest package to make sure the HFDocTestParser is used when discovering
    tests.
    r  c                 c   s   G dd dt j}| jjdkrB| jjj| j| jd| jjd}nTz t	| j| jj| jdd}W n2 t
k
r   | jdrtd| j  n Y nX |t d	}t| }td
|t t| jd}|||jD ] }|jrtj| |j||dV  qd S )Nc                       s2   e Zd ZdZ fddZdd fddZ  ZS )z7HfDoctestModule.collect.<locals>.MockAwareDocTestFinderzA hackish doctest finder that overrides stdlib internals to fix a stdlib bug.

            https://github.com/pytest-dev/pytest/issues/3456 https://bugs.python.org/issue25532
            c                    s8   t |trt|d|}t|dr*t|}t ||S )a3  Doctest code does not take into account `@property`, this
                is a hackish way to fix it. https://bugs.python.org/issue17446

                Wrapped Doctests will need to be unwrapped so the correct line number is returned. This will be
                reported upstream. #8796
                fget__wrapped__)r  rw  getattrr  r   unwrapr   _find_lineno)r  r  source_linesr"  rh   ri   rI  N  s    


zDHfDoctestModule.collect.<locals>.MockAwareDocTestFinder._find_linenoNr  c              
      s:   t |rd S t  t ||||||| W 5 Q R X d S r   )rX   rY   r   _find)r  r   r  r@  modulerJ  Zglobsseenr"  rh   ri   rK  b  s          z=HfDoctestModule.collect.<locals>.MockAwareDocTestFinder._find)r  r  r  r  rI  rK  r%  rh   rh   r"  ri   MockAwareDocTestFinderH  s   rN  zconftest.pyZ
importmode)rootpath)rootmodeZdoctest_ignore_import_errorszunable to import module %r)r  F)verboseoptionflagscheckerZcontinue_on_failure)r@  runnerZdtest)doctestZDocTestFinderr   r@  r   ZpluginmanagerZ_importconftestZ	getoptionrO  r[   rp   r  r\   r=  rZ   rW   rU   rV   r   r  r9  r]   Zfrom_parent)r  rN  rL  finderrS  rU  testrh   rh   ri   collectG  s8    #


zHfDoctestModule.collectN)r  r  r  r  r   r]   rY  rh   rh   rh   ri   rD  A  s   rD  (  r  
contextlibrV  r!  	importlibr   r   r)  r_   r   rm  r   r  r
  re  r  rn   collections.abcr   r)  r   pathlibr   typingr   r   r   r   r	   r
   r  r  Ztransformersr.  Zintegrationsr   r   r   r   r   r   Zintegrations.deepspeedr   r  r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   Zaccelerate.staterR   rS   Z_pytest.doctestrT   rU   rV   rW   rX   rY   rZ   r[   Z_pytest.outcomesr\   ro   r]   objectZSMALL_MODEL_IDENTIFIERZDUMMY_UNKNOWN_IDENTIFIERZDUMMY_DIFF_TOKENIZER_IDENTIFIERUSERZENDPOINT_STAGINGZTOKENrj   rl   r~   rm   ru   r   rw   Z_tf_gpu_memory_limitry   r{   Z_run_third_party_device_testsrr   rv   rx   rz   r|   r   r   r   r   r   r   r   r   rI  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r`   r   Zdevicer  r  r  r   Zis_availablebackendimport_moduleModuleNotFoundErrorr   r   r   Zdefault_backendZ
jax_devicer   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r&  r'  contextmanagerr1  PathLiker6  ZTestCaser7  r{  r  r  r  r  r  r  r  r  ro  r  r  r  r  r  r  r  r  r  rk   r  r%  r4  r<  ZDocTestParserr=  rD  rh   rh   rh   ri   <module>   s    B(





	






	









&k+
   
!

 	
	)"
0$5.