o
    h                 
   @   sR  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Zd dlZd dlZd dl mZmZ d dlmZmZmZmZ d dlmZmZ d dlmZmZ d dl m!Z! d dl"m#Z# d dl$m%Z%m&Z&m'Z'm(Z( d d	lm)Z) d d
l*m+Z+ d dl,Z-d dl.Z.d dl/Z/d dl-m0Z0 d dl1m2Z2 d dl3m4Z4 d dl3mZ5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z? ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ eC rd dlmZmZ d dlmZ eu rd dlmZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ neZeZdZdZdZdZdZdZe rd dlZej2jduZej2jduZndZdZe5e¡ZÐdd d!ZĐdd"d#Zed$dd%Zed&dd%Zed'dd%Zed(d)d%Zed*dd%Zed+dd%Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Zd>d? Zd@dA ZdBdC ZdDdE ZdFdG ZdHdI ZdJdK ZdLdM ZeAfdNefdOdPZeBfdNefdQdRZߐddNefdTdUZdVdW ZdXdY ZdZd[ Zd\d] Zd^d_ Zd`da Zdbdc Zddde Zdfdg Zdhdi ZdjefdkdlZdmdn Zdodp Zdqdr Zdsdt Zdudv Zdwdx Zdydz Zd{d| Zd}d~ Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Z dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Ze rd dlZde
jv re
jd Zz
eeZW n  ey Z zede de edZ[ww de
jv rMe
jd Zedkrej s֐ede dedkre sede dÝedkre sede dŝedkre sede dǝedkr&e s&ede dɝz
eeZW nZ eyL Z zedʐe edZ[ww ej rXdZn3eːrce rcdĐZn(eːrne rndƐZneːrye rydȐZneːre rdZndːZndZe rd dlZeV rd dl Z e ! Z"ndZ"dd̈́ Z#ddτ Z$ddф Z%ddӄ Z&ddՄ Z'ddאe(fddلZ)ddۄ Z*dd݄ Z+dd߄ Z,dd Z-dd Z.dd Z/dd Z0dd Z1dd Z2dd Z3dd Z4dd Z5dd Z6dd Z7dd Z8dd Z9dd Z:dd Z;dd Z<d d Z=dd Z>dd Z?dd Z@dd	 ZAd
d ZBdd ZCdd ZDdd ZEdd ZFdd ZGdd ZHdd ZIdd ZJdd ZKdd ZLd d! ZMd"d# ZNd$d% ZOd&d' ZPd(d) ZQd*d+ ZRd,d- ZSd.d/ ZTd0d1 ZUd2d3 ZVd4d5 ZWd6d7 ZXd8d9 ZYd:d; ZZd<d= Z[dŐd>d?Z\d@e4dAe]fdBdCZ^dDe_e`eݐe(f  dAee`eݐe(f ddf fdEdFZadGdH ZbdIdJ ZcdKdL ZddMdN ZedOdP ZfG dQdR dRZgG dSdT dTegZhG dUdV dVegZiG dWdX dXZjejkdYdZ ZlG d[d\ d\Zmejkd]e(ee
jnf dAed fd^d_ZoG d`da daejpZqdbdc Zrejkddde Zsi Ztdfdg Zudhdi Zvd dlwZwG djdk dkZxdldm ZydȐdAexfdndoZzdɐdAexfdqdrZ{dsdt Z|dudv Z}dʐdxdyZ~dzd{ Zd|d} ZG d~d deZdĐde_e fddZG dd dZdːde]de'e( de'e fddZd̐de]de'e( fddZdd Zd͐ddZdd Z	 dd ZG dd dejZG dd deZdeݐde`ee&f fddZe r ejjejejdZejjdddZejjdd dd dZnddiZddiZddd iZe rLejjed< ejjed< e rkejjed< ejjed< ejjed< e rejjed< ejjed< ejjed< e rejjed< ejjed< ejjed< e rejjed< ejjed< ejjed< deݐde]fddZdefddZdefddZe 	rde
jv 	re
jd Ze#e 	sede e
je
je\ZZeje zeded ZW n e	y] Z zede edZ[ww eeZzejZW n e	y Z zededZ[ww de
jv 	reek	rde de dZed7 ZeeeZde`ee&f defddZeed eed eed dd ZedĐdefddZee(edf e(e]df f ZedAefddZG ddÄ deee%f ZdS (      N)UserDictdefaultdict)	GeneratorIterableIteratorMapping)MISSINGfields)cachewraps)StringIO)Path)AnyCallableOptionalUnion)mockpatch)delete_repoversion)Trainer)logging   )is_clearml_availableis_optuna_availableis_ray_availableis_sigopt_availableis_swanlab_availableis_tensorboard_availableis_wandb_available)is_deepspeed_available)aACCELERATE_MIN_VERSIONGGUF_MIN_VERSIONis_accelerate_availableis_apex_availableis_apollo_torch_availableis_aqlm_availableis_auto_awq_availableis_auto_gptq_availableis_av_availableis_bitsandbytes_available'is_bitsandbytes_multi_backend_availableis_bs4_availableis_compressed_tensors_availableis_cv2_availableis_cython_availableis_detectron2_availableis_eetq_availableis_essentia_availableis_faiss_availableis_fbgemm_gpu_availableis_flash_attn_2_availableis_flax_availableis_flute_availableis_fsdp_availableis_ftfy_availableis_g2p_en_availableis_galore_torch_availableis_gguf_availableis_gptqmodel_availableis_grokadamw_availableis_hadamard_availableis_hqq_availableis_ipex_availableis_jieba_availableis_jinja_availableis_jumanpp_availableis_keras_nlp_availableis_levenshtein_availableis_librosa_availableis_liger_kernel_availableis_lomo_availableis_natten_availableis_nltk_availableis_onnx_availableis_optimum_availableis_optimum_quanto_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_quark_availableis_rjieba_availableis_sacremoses_availableis_safetensors_availableis_schedulefree_availableis_scipy_availableis_sentencepiece_availableis_seqio_availableis_soundfile_availableis_spacy_availableis_spqr_availableis_sudachi_availableis_sudachi_projection_available#is_tensorflow_probability_availableis_tensorflow_text_availableis_tf2onnx_availableis_tf_availableis_tiktoken_availableis_timm_availableis_tokenizers_availableis_torch_available!is_torch_bf16_available_on_deviceis_torch_bf16_cpu_availableis_torch_bf16_gpu_availableis_torch_deterministic!is_torch_fp16_available_on_deviceis_torch_greater_or_equalis_torch_hpu_availableis_torch_mlu_availableis_torch_neuroncore_availableis_torch_npu_availableis_torch_sdpa_availableis_torch_tensorrt_fx_availableis_torch_tf32_availableis_torch_xla_availableis_torch_xpu_availableis_torchao_availableis_torchaudio_availableis_torchdynamo_availableis_torchvision_availableis_vision_availableis_vptq_available	strtobool)AcceleratorStatePartialState)is_fp8_available)Module_get_checker_get_continue_on_failure_get_runner
_is_mocked_patch_unwrap_mock_awareget_optionflags)skip)import_path)DoctestItemzjulien-c/bert-xsmall-dummyzjulien-c/dummy-unknownzjulien-c/dummy-diff-tokenizer__DUMMY_TRANSFORMERS_USER__zhttps://hub-ci.huggingface.co%hf_94wBhPGp6KrrTH3KDchhKpRxZwd6dmHWLLFc                 C   V   zt j|  }W n ty   |}Y |S w zt|}W |S  ty*   td|  dw )NIf set, z must be yes or no.)osenvironKeyErrorr   
ValueErrorkeydefaultvalue_value r   n/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/testing_utils.pyparse_flag_from_env   s   
r   c                 C   r   )Nr   z must be a int.)r   r   r   intr   r   r   r   r   parse_int_from_env   s   
r   RUN_SLOW)r   RUN_CUSTOM_TOKENIZERSHUGGINGFACE_CO_STAGINGRUN_PIPELINE_TESTSTRUN_AGENT_TESTSRUN_THIRD_PARTY_DEVICE_TESTSc                 C   F   t s
tjdd| S zddl}W n ty   |  Y S w |j | 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 testreasonr   N)_run_stagingunittestr   pytestImportErrormarkis_staging_test	test_caser   r   r   r   r      s   r   c                 C   r   )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   r   N)_run_pipeline_testsr   r   r   r   r   is_pipeline_testr   r   r   r   r   
  s   r   c                 C   r   )z|
    Decorator marking a test as an agent test. If RUN_TOOL_TESTS is set to a falsy value, those tests will be skipped.
    ztest is an agent testr   r   N)_run_agent_testsr   r   r   r   r   is_agent_testr   r   r   r   r     s   r   c                 C      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)r   
skipUnless_run_slow_testsr   r   r   r   slow)     r   c                 C   s   t jd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 slowr   )r   r   r   r   r   r   tooslow3     r   c                    s   t   fdd}|S )Nc               
      s:   z | i |W S  t y } ztd| d }~ww )Nz)Test skipped due to NotImplementedError: )NotImplementedErrorr   SkipTest)argskwargse	test_funcr   r   wrapper?  s   z(skip_if_not_implemented.<locals>.wrapper	functoolsr   )r   r   r   r   r   skip_if_not_implemented>  s   r   c                 C   s>   t | D ]}|drt| |}t|rt| |t| q| S )zP
    Class decorator to apply @skip_if_not_implemented to all test methods.
    test_)dir
startswithgetattrcallablesetattrr   )cls	attr_nameattrr   r   r   apply_skip_if_not_implementedI  s   

r   c                 C   r   )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)r   r   _run_custom_tokenizersr   r   r   r   custom_tokenizersU  r   r   c                 C      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)r   r   r.   r   r   r   r   require_bs4_     r   c                 C   r   )z
    Decorator marking a test that requires GaLore. These tests are skipped when GaLore isn't installed.
    https://github.com/jiaweizzhao/GaLore
    ztest requires GaLore)r   r   r=   r   r   r   r   require_galore_torchf     r   c                 C   r   )z
    Decorator marking a test that requires GaLore. These tests are skipped when APOLLO isn't installed.
    https://github.com/zhuhanqing/APOLLO
    ztest requires APOLLO)r   r   r'   r   r   r   r   require_apollo_torchn  r   r   c                 C   r   )z
    Decorator marking a test that requires LOMO. These tests are skipped when LOMO-optim isn't installed.
    https://github.com/OpenLMLab/LOMO
    ztest requires LOMO)r   r   rK   r   r   r   r   require_lomov  r   r   c                 C   r   )zs
    Decorator marking a test that requires GrokAdamW. These tests are skipped when GrokAdamW isn't installed.
    ztest requires GrokAdamW)r   r   r@   r   r   r   r   require_grokadamw~  r   r   c                 C   r   )z
    Decorator marking a test that requires schedulefree. These tests are skipped when schedulefree isn't installed.
    https://github.com/facebookresearch/schedule_free
    ztest requires schedulefree)r   r   r]   r   r   r   r   require_schedulefree  r   r   c                 C   r   )zs
    Decorator marking a test that requires OpenCV.

    These tests are skipped when OpenCV isn't installed.

    ztest requires OpenCV)r   r   r0   r   r   r   r   require_cv2     r   c                 C   r   )z}
    Decorator marking a test that requires Levenshtein.

    These tests are skipped when Levenshtein isn't installed.

    ztest requires Levenshtein)r   r   rH   r   r   r   r   require_levenshtein  r   r   c                 C   r   )zo
    Decorator marking a test that requires NLTK.

    These tests are skipped when NLTK isn't installed.

    ztest requires NLTK)r   r   rM   r   r   r   r   require_nltk  r   r   min_versionc                 C      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 version >= )r   r   r%   r   r   r   r   r   require_accelerate  s
   r   c                 C   r   )zj
    Decorator marking a test that requires ggguf. These tests are skipped when gguf isn't installed.
    ztest requires gguf version >= )r   r   r>   r   r   r   r   require_gguf     r   1.12.0c                 C   r   )zi
    Decorator marking a test that requires fsdp. These tests are skipped when fsdp isn't installed.
    ztest requires torch version >= )r   r   r:   r   r   r   r   require_fsdp  r   r   c                 C   r   )zt
    Decorator marking a test that requires g2p_en. These tests are skipped when SentencePiece isn't installed.
    ztest requires g2p_en)r   r   r<   r   r   r   r   require_g2p_en  r   r   c                 C   r   )zw
    Decorator marking a test that requires safetensors. These tests are skipped when safetensors isn't installed.
    ztest requires safetensors)r   r   r\   r   r   r   r   require_safetensors  r   r   c                 C   r   )zm
    Decorator marking a test that requires rjieba. These tests are skipped when rjieba isn't installed.
    ztest requires rjieba)r   r   rZ   r   r   r   r   require_rjieba  r   r   c                 C   r   )zk
    Decorator marking a test that requires jieba. These tests are skipped when jieba isn't installed.
    ztest requires jieba)r   r   rD   r   r   r   r   require_jieba  r   r   c                 C   r   )zk
    Decorator marking a test that requires jinja. These tests are skipped when jinja isn't installed.
    ztest requires jinja)r   r   rE   r   r   r   r   require_jinja  r   r   c                 C   r   )Nztest requires tf2onnx)r   r   rh   r   r   r   r   require_tf2onnx     r   c                 C   r   )Nztest requires ONNX)r   r   rN   r   r   r   r   require_onnx  r   r   c                 C   r   )zo
    Decorator marking a test that requires Timm.

    These tests are skipped when Timm isn't installed.

    ztest requires Timm)r   r   rk   r   r   r   r   require_timm  r   r   c                 C   r   )zs
    Decorator marking a test that requires NATTEN.

    These tests are skipped when NATTEN isn't installed.

    ztest requires natten)r   r   rL   r   r   r   r   require_natten  r   r   c                 C   r   )zu
    Decorator marking a test that requires PyTorch.

    These tests are skipped when PyTorch isn't installed.

    test requires PyTorch)r   r   rm   r   r   r   r   require_torch  r   r   r   c                        fdd}|S )z
    Decorator marking a test that requires PyTorch version >= `version`.

    These tests are skipped when PyTorch version is less than `version`.
    c                    s   t t d  | S )Nz!test requires PyTorch version >= )r   r   rs   r   r   r   r   	decorator  s   z1require_torch_greater_or_equal.<locals>.decoratorr   )r   r   r   r   r   require_torch_greater_or_equal  s   r   c                 C   r   )z
    Decorator marking a test that requires Flash Attention.

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

    ztest requires Flash Attention)r   r   r7   r   r   r   r   require_flash_attn  r   r   c                 C   r   )z
    Decorator marking a test that requires PyTorch's SDPA.

    These tests are skipped when requirements are not met (torch version).
    ztest requires PyTorch SDPA)r   r   rx   r   r   r   r   require_torch_sdpa(  s   r   c                    s$   t dt  fdd}|S )zZ
    A decorator that loads the HF token for tests that require to load gated models.
    HF_HUB_READ_TOKENc                     sT   d ur#t dd  | i |W  d    S 1 sw   Y  d S  | i |S )Nz(huggingface_hub.utils._headers.get_token)return_valuer   r   r   fntokenr   r   _inner7  s
   $z"require_read_token.<locals>._inner)r   getenvr   )r  r  r   r   r   require_read_token1  s   
r  c                 C   r   )zo
    Decorator marking a test that requires PEFT.

    These tests are skipped when PEFT isn't installed.

    ztest requires PEFT)r   r   rR   r   r   r   r   require_peftB  r   r  c                 C   r   )z}
    Decorator marking a test that requires Torchvision.

    These tests are skipped when Torchvision isn't installed.

    ztest requires Torchvision)r   r   r   r   r   r   r   require_torchvisionL  r   r  c                 C      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)r   r   rm   ri   r   r   r   r   require_torch_or_tfV  s   r	  c                 C   r   )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)r   r   rC   r   r   r   r   #require_intel_extension_for_pytorchb  s   r
  c                 C   r   )z
    Decorator marking a test that requires TensorFlow probability.

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

    z$test requires TensorFlow probability)r   r   rf   r   r   r   r   require_tensorflow_probabilityq  s   r  c                 C   r   )zu
    Decorator marking a test that requires torchaudio. These tests are skipped when torchaudio isn't installed.
    ztest requires torchaudio)r   r   r~   r   r   r   r   require_torchaudio}  r   r  c                 C   r   )zu
    Decorator marking a test that requires TensorFlow. These tests are skipped when TensorFlow isn't installed.
    ztest requires TensorFlow)r   r   ri   r   r   r   r   
require_tf  r   r  c                 C   r   )zv
    Decorator marking a test that requires JAX & Flax. These tests are skipped when one / both are not installed
    ztest requires JAX & Flax)r   r   r8   r   r   r   r   require_flax  r   r  c                 C   r   ){
    Decorator marking a test that requires SentencePiece. These tests are skipped when SentencePiece isn't installed.
    ztest requires SentencePiece)r   r   r_   r   r   r   r   require_sentencepiece  r   r  c                 C   r   )zu
    Decorator marking a test that requires Sacremoses. These tests are skipped when Sacremoses isn't installed.
    ztest requires Sacremoses)r   r   r[   r   r   r   r   require_sacremoses  r   r  c                 C   r   )r  ztest requires Seqio)r   r   r`   r   r   r   r   require_seqio  r   r  c                 C   r   )zs
    Decorator marking a test that requires Scipy. These tests are skipped when SentencePiece isn't installed.
    ztest requires Scipy)r   r   r^   r   r   r   r   require_scipy  r   r  c                 C   r   )u   
    Decorator marking a test that requires 🤗 Tokenizers. These tests are skipped when 🤗 Tokenizers isn't installed.
    ztest requires tokenizers)r   r   rl   r   r   r   r   require_tokenizers  r   r  c                 C   r   )z
    Decorator marking a test that requires tensorflow_text. These tests are skipped when tensroflow_text isn't
    installed.
    ztest requires tensorflow_text)r   r   rg   r   r   r   r   require_tensorflow_text  r   r  c                 C   r   )zs
    Decorator marking a test that requires keras_nlp. These tests are skipped when keras_nlp isn't installed.
    ztest requires keras_nlp)r   r   rG   r   r   r   r   require_keras_nlp  r   r  c                 C   r   )zm
    Decorator marking a test that requires pandas. These tests are skipped when pandas isn't installed.
    ztest requires pandas)r   r   rQ   r   r   r   r   require_pandas  r   r  c                 C   r   )zw
    Decorator marking a test that requires PyTesseract. These tests are skipped when PyTesseract isn't installed.
    ztest requires PyTesseract)r   r   rV   r   r   r   r   require_pytesseract  r   r  c                 C   r   )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)r   r   rX   r   r   r   r   require_pytorch_quantization  s   r  c                 C   r   )z
    Decorator marking a test that requires the vision dependencies. These tests are skipped when torchaudio isn't
    installed.
    ztest requires vision)r   r   r   r   r   r   r   require_vision  r   r  c                 C   r   )zi
    Decorator marking a test that requires ftfy. These tests are skipped when ftfy isn't installed.
    ztest requires ftfy)r   r   r;   r   r   r   r   require_ftfy  r   r  c                 C   r   )zk
    Decorator marking a test that requires SpaCy. These tests are skipped when SpaCy isn't installed.
    ztest requires spacy)r   r   rb   r   r   r   r   require_spacy  r   r  c                 C   s8   t  stjdd| S ddl}t|j dkd| S )a  
    Decorator marking a test that requires a multi-GPU CUDA setup (in PyTorch). These tests are skipped on a machine without
    multiple CUDA GPUs.

    To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu"
    r   r   r   Nr   z test requires multiple CUDA GPUsrm   r   r   torchr   cudadevice_countr   r  r   r   r   require_torch_multi_gpu  s   r"  c                 C   s.   t  stjdd| S tttdkd| S )a(  
    Decorator marking a test that requires a multi-accelerator (in PyTorch). These tests are skipped on a machine
    without multiple accelerators. To run *only* the multi_accelerator tests, assuming all test names contain
    multi_accelerator: $ pytest -sv ./tests -k "multi_accelerator"
    r   r   r   z#test requires multiple acceleratorsrm   r   r   r   backend_device_counttorch_devicer   r   r   r   require_torch_multi_accelerator  s
   r&  c                 C   8   t  stjd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   r   N   ztest requires 0 or 1 GPUr  r!  r   r   r   require_torch_non_multi_gpu     r)  c                 C   .   t  stjdd| S tttdk d| S )zW
    Decorator marking a test that requires 0 or 1 accelerator setup (in PyTorch).
    r   r   r(  z test requires 0 or 1 acceleratorr#  r   r   r   r   #require_torch_non_multi_accelerator  s   r,  c                 C   r'  )zT
    Decorator marking a test that requires 0 or 1 or 2 GPU setup (in PyTorch).
    r   r   r   N   ztest requires 0 or 1 or 2 GPUsr  r!  r   r   r   require_torch_up_to_2_gpus%  r*  r.  c                 C   r+  )z\
    Decorator marking a test that requires 0 or 1 or 2 accelerator setup (in PyTorch).
    r   r   r-  z&test requires 0 or 1 or 2 acceleratorsr#  r   r   r   r   "require_torch_up_to_2_accelerators1  s
   r/  c                 C   r   )zG
    Decorator marking a test that requires TorchXLA (in PyTorch).
    ztest requires TorchXLA)r   r   r{   r   r   r   r   require_torch_xla=  r   r0  c                 C   s   t tddd| S )zI
    Decorator marking a test that requires NeuronCore (in PyTorch).
    F)check_devicez test requires PyTorch NeuronCore)r   r   rv   r   r   r   r   require_torch_neuroncoreD  s   r2  c                 C   r   )zB
    Decorator marking a test that requires NPU (in PyTorch).
    test requires PyTorch NPU)r   r   rw   r   r   r   r   require_torch_npuM  r   r4  c                 C   0   t  stjd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"
    r3  r   r   ztest requires multiple NPUs)rw   r   r   r   r  npur   r   r   r   r   require_torch_multi_npuT     r7  c                 C      t tdkd| S )zB
    Decorator marking a test that should be skipped for HPU.
    hpuztest requires a non-HPUr   r   r%  r   r   r   r   require_non_hpua     r<  c                 C   r   )aN  
    Decorator marking a test that requires XPU (in PyTorch).

    These tests are skipped when XPU backend is not available. XPU backend might be available either via stock
    PyTorch (>=2.4) or via Intel Extension for PyTorch. In the latter case, if IPEX is installed, its version
    must match match current PyTorch version.
    ztest requires XPU device)r   r   r|   r   r   r   r   require_torch_xpuh  s   r>  c                 C   r9  )zB
    Decorator marking a test that should be skipped for XPU.
    xpuztest requires a non-XPUr;  r   r   r   r   require_non_xpus  r=  r@  c                 C   r5  )a  
    Decorator marking a test that requires a multi-XPU setup (in PyTorch). These tests are skipped on a machine without
    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 PyTorch XPUr   r   ztest requires multiple XPUs)r|   r   r   r   r  r?  r   r   r   r   r   require_torch_multi_xpuz  r8  rA  c                 C   r5  )a  
    Decorator marking a test that requires a multi-HPU setup (in PyTorch). These tests are skipped on a machine without
    multiple HPUs.

    To run *only* the multi_hpu tests, assuming all test names contain multi_hpu: $ pytest -sv ./tests -k "multi_hpu"
    ztest requires PyTorch HPUr   r   ztest requires multiple HPUs)rt   r   r   r   r  r:  r   r   r   r   r   require_torch_multi_hpu  r8  rB  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):
TRANSFORMERS_TEST_DEVICEr  zTRANSFORMERS_TEST_DEVICE=zH, but CUDA is unavailable. Please double-check your testing environment.r?  zG, but XPU is unavailable. Please double-check your testing environment.r6  zG, but NPU is unavailable. Please double-check your testing environment.mluzG, but MLU is unavailable. Please double-check your testing environment.r:  zG, but HPU is unavailable. Please double-check your testing environment.zUUnknown testing device specified by environment variable `TRANSFORMERS_TEST_DEVICE`: cpuc                 C   r   )z2Decorator marking a test that requires TorchDynamoztest requires TorchDynamo)r   r   r   r   r   r   r   require_torchdynamo     rG  c                 C   r   )z.Decorator marking a test that requires torchaoztest requires torchao)r   r   r}   r   r   r   r   require_torchao  rH  rI  c                    r   )Nc                    sB   t  otttjdjt k}t|d  d| S )Ntorchaoz4Test requires torchao with the version greater than .)r}   r   parse	importlibmetadatabase_versionr   r   )r   correct_torchao_versiontorchao_versionr   r   r     s   
z;require_torchao_version_greater_or_equal.<locals>.decoratorr   )rR  r   r   rQ  r   (require_torchao_version_greater_or_equal  s   rS  c                 C   r   )z8Decorator marking a test that requires Torch-TensorRT FXztest requires Torch-TensorRT FX)r   r   ry   r   r   r   r   require_torch_tensorrt_fx  rH  rT  c                 C   s   t tdkd| S )z8Decorator marking a test that requires CUDA and PyTorch.r  ztest requires CUDAr;  r   r   r   r   require_torch_gpu  s   rU     memoryc                 C   sJ   t dkrtjd| dd| S ttjdjd |kd| d| S )zXDecorator marking a test that requires a CUDA GPU with more than `memory` GiB of memory.r  z(test requires a CUDA GPU with more than z GiB of memoryr   r   i   @z#test requires a GPU with more than )r%  r   r   r   r  r  get_device_propertiestotal_memory)r   rW  r   r   r   require_torch_large_gpu  s   
rZ  c                 C   s   t  rt r| S t| S )zl
    Decorator marking a test that requires a GPU if bitsandbytes multi-backend feature is not enabled.
    )r,   r-   rU  r   r   r   r   2require_torch_gpu_if_bnb_not_multi_backend_enabled  s   r[  c                 C   s   t tduo	tdkd| S )zMDecorator marking a test that requires an accessible accelerator and PyTorch.NrF  ztest requires acceleratorr;  r   r   r   r   require_torch_accelerator  s   r\  c                 C      t ttd| S )zBDecorator marking a test that requires a device that supports fp16z&test requires device with fp16 support)r   r   rr   r%  r   r   r   r   require_torch_fp16  
   r^  c                 C      t t ot d| S )z7Decorator marking a test that requires supports for fp8ztest requires fp8 support)r   r   r%   r   r   r   r   r   require_fp8  s   ra  c                 C   r]  )zBDecorator marking a test that requires a device that supports bf16z&test requires device with bf16 support)r   r   rn   r%  r   r   r   r   require_torch_bf16#  r_  rb  c                 C   r   )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)r   r   rp   r   r   r   r   require_torch_bf16_gpu*     rc  c                 C   r   )z>Decorator marking a test that requires torch>=1.10, using CPU.z$test requires torch>=1.10, using CPU)r   r   ro   r   r   r   r   require_torch_bf16_cpu2  rd  re  c                 C   s   t  rtt d| S | S )Nz3test requires torch to use deterministic algorithms)r|   r   r   rq   r   r   r   r   require_deterministic_for_xpu:  s
   rf  c                 C   r   )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)r   r   rz   r   r   r   r   require_torch_tf32C  s
   rg  c                 C   r   )z2Decorator marking a test that requires detectron2.ztest requires `detectron2`)r   r   r2   r   r   r   r   require_detectron2J  rH  rh  c                 C   r   )z-Decorator marking a test that requires faiss.ztest requires `faiss`)r   r   r5   r   r   r   r   require_faissO  rH  ri  c                 C   r   )zs
    Decorator marking a test that requires optuna.

    These tests are skipped when optuna isn't installed.

    ztest requires optuna)r   r   r   r   r   r   r   require_optunaT  r   rj  c                 C   r   )zw
    Decorator marking a test that requires Ray/tune.

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

    ztest requires Ray/tune)r   r   r   r   r   r   r   require_ray^  r   rk  c                 C   r   )zs
    Decorator marking a test that requires SigOpt.

    These tests are skipped when SigOpt isn't installed.

    ztest requires SigOpt)r   r   r   r   r   r   r   require_sigopth  r   rl  c                 C   r   )zu
    Decorator marking a test that requires swanlab.

    These tests are skipped when swanlab isn't installed.

    ztest requires swanlab)r   r   r   r   r   r   r   require_swanlabr  r   rm  c                 C   r   )zq
    Decorator marking a test that requires wandb.

    These tests are skipped when wandb isn't installed.

    ztest requires wandb)r   r   r!   r   r   r   r   require_wandb|  r   rn  c                 C   r   )zp
    Decorator marking a test requires clearml.

    These tests are skipped when clearml isn't installed.

    ztest requires clearml)r   r   r   r   r   r   r   require_clearml  r   ro  c                 C   r   )zx
    Decorator marking a test that requires soundfile

    These tests are skipped when soundfile isn't installed.

    ztest requires soundfile)r   r   ra   r   r   r   r   require_soundfile  r   rp  c                 C   r   )z:
    Decorator marking a test that requires deepspeed
    ztest requires deepspeed)r   r   r"   r   r   r   r   require_deepspeed  r   rq  c                 C   r   )z5
    Decorator marking a test that requires apex
    ztest requires apex)r   r   r&   r   r   r   r   require_apex  r   rr  c                 C   r   )z5
    Decorator marking a test that requires aqlm
    ztest requires aqlm)r   r   r(   r   r   r   r   require_aqlm  r   rs  c                 C   r   )z5
    Decorator marking a test that requires vptq
    ztest requires vptq)r   r   r   r   r   r   r   require_vptq  r   rt  c                 C   r   )z5
    Decorator marking a test that requires spqr
    ztest requires spqr)r   r   rc   r   r   r   r   require_spqr  r   ru  c              
   C   s\   t  }|r&zddl}W n ty% } zdt|v rd}W Y d}~nd}~ww t|d| S )z5
    Decorator marking a test that requires eetq
    r   Nshard_checkpointFztest requires eetq)r3   eetqr   strr   r   )r   eetq_availablerw  excr   r   r   require_eetq  s   r{  c                 C   r   )z3
    Decorator marking a test that requires av
    ztest requires av)r   r   r+   r   r   r   r   
require_av  r   r|  c                 C   sJ   t  rt rzddl}|j| W S  ty   |  Y S w tjdd| S )z
    Decorator marking a test that requires the bitsandbytes library. Will be skipped when the library or its hard dependency torch is not installed.
    r   Nz$test requires bitsandbytes and torchr   )r,   rm   r   r   bitsandbytesr   r   r   r   r   r   r   require_bitsandbytes  s   r~  c                 C   r   )z*
    Decorator for optimum dependency
    ztest requires optimum)r   r   rO   r   r   r   r   require_optimum  r   r  c                 C   s   t t dS )z0
    Decorator for `tensorboard` dependency
    ztest requires tensorboard)r   r   r    r   r   r   r   require_tensorboard  s   r  c                 C   r  )z,
    Decorator for auto_gptq dependency
    z$test requires gptqmodel or auto-gptq)r   r   r?   r*   r   r   r   r   require_gptq  
   r  c                 C   r   )z&
    Decorator for hqq dependency
    ztest requires hqq)r   r   rB   r   r   r   r   require_hqq  r   r  c                 C   r   )z+
    Decorator for auto_awq dependency
    ztest requires autoawq)r   r   r)   r   r   r   r   require_auto_awq  r   r  c                 C   r   )z)
    Decorator for quanto dependency
    ztest requires optimum-quanto)r   r   rP   r   r   r   r   require_optimum_quanto	  r   r  c                 C   r   )z5
    Decorator for compressed_tensors dependency
    z test requires compressed_tensors)r   r   r/   r   r   r   r   require_compressed_tensors  r   r  c                 C   r   )z-
    Decorator for fbgemm_gpu dependency
    ztest requires fbgemm-gpu)r   r   r6   r   r   r   r   require_fbgemm_gpu  r   r  c                 C   r   )z(
    Decorator for quark dependency
    ztest requires quark)r   r   rY   r   r   r   r   require_quark  r   r  c                 C   r`  )zC
    Decorator marking a test that requires higgs and hadamard
    z/test requires flute and fast_hadamard_transform)r   r   r9   rA   r   r   r   r   require_flute_hadamard%  r  r  c                 C   r   )z;
    Decorator marking a test that requires phonemizer
    ztest requires phonemizer)r   r   rS   r   r   r   r   require_phonemizer.  r   r  c                 C   r   )z<
    Decorator marking a test that requires pyctcdecode
    ztest requires pyctcdecode)r   r   rU   r   r   r   r   require_pyctcdecode5  r   r  c                 C   r   )z8
    Decorator marking a test that requires librosa
    ztest requires librosa)r   r   rI   r   r   r   r   require_librosa<  r   r  c                 C   r   )z=
    Decorator marking a test that requires liger_kernel
    ztest requires liger_kernel)r   r   rJ   r   r   r   r   require_liger_kernelC  r   r  c                 C   r   )z9
    Decorator marking a test that requires essentia
    ztest requires essentia)r   r   r4   r   r   r   r   require_essentiaJ  r   r  c                 C   r   )z<
    Decorator marking a test that requires pretty_midi
    ztest requires pretty_midi)r   r   rT   r   r   r   r   require_pretty_midiQ  r   r  c                 C   s   t | d uS N)shutilwhich)cmdr   r   r   
cmd_existsX     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)r   r   r  r   r   r   r   require_usr_bin_time\  r=  r  c                 C   r   )z8
    Decorator marking a test that requires sudachi
    ztest requires sudachi)r   r   rd   r   r   r   r   require_sudachic  r   r  c                 C   r   )zC
    Decorator marking a test that requires sudachi_projection
    z/test requires sudachi which supports projection)r   r   re   r   r   r   r   require_sudachi_projectionj  s   r  c                 C   r   )8
    Decorator marking a test that requires jumanpp
    ztest requires jumanpp)r   r   rF   r   r   r   r   require_jumanpps  r   r  c                 C   r   )r  ztest requires cython)r   r   r1   r   r   r   r   require_cythonz  r   r  c                 C   r   )zq
    Decorator marking a test that requires TikToken. These tests are skipped when TikToken isn't installed.
    ztest requires TikToken)r   r   rj   r   r   r   r   require_tiktoken  r   r  c                  C   sP   t  rddl} | j S t rddl}t|jdS t	 r&ddl
}| S dS )z^
    Return the number of available gpus (regardless of whether torch, tf or jax is used)
    r   NGPU)rm   r  r  r   ri   
tensorflowlenconfiglist_physical_devicesr8   jax)r  tfr  r   r   r   get_gpu_count  s   
r  c                 C   sZ   t  d d }tjtj|}|ds"tj|}|dr| r+tj|| S |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   tests)inspectstackr   pathabspathdirnameendswithjoin)append_pathcaller__file__	tests_dirr   r   r   get_tests_dir  s   

r  trainerreturnc                 C   s,   | j }|  }| j|||jd}|d }|S )N)r   
dataloadertotal_train_batch_sizer   )r   get_train_dataloaderset_initial_training_valuesper_device_train_batch_size)r  training_argstrain_dataloaderinitial_training_valuessteps_per_epochr   r   r   get_steps_per_epoch  s   r  side_effect_valuesc                 c   s    | E dH  	 | d V  q)z
    Function that returns side effects for the _evaluate method.
    Used when we're unsure of exactly how many times _evaluate will be called.
    NTr   )r  r   r   r   evaluate_side_effect_factory  s
   

r  c                 C   s   t dd| dt jS )Nz^.*\r r   )resubM)bufr   r   r   apply_print_resets     r  c                 C   s:   t |  }|| }|dksJ d| d| d S )Nr  zexpecting to find z in output: f)r  lowerfind)outwhatout_pr	match_strr   r   r   assert_screenout  s    r  c                 C   s&  d}g d}| j jj|v rd }t| j dst| j drd }t| j dr+|d ur+|| j _t| j drWd| j jv rW|d urWt| j j| j _t| j jt	rRd| j jd< nd| j j_t| j drd| j j
v r|d urt| j j
| j _
t| j j
t	r~d| j j
d< nd| j j
_t| j dr| j j| j _d S d S )	Nr   )ZambaModelTesterZamba2ModelTesterRwkvModelTesterAriaVisionText2TextModelTesterGPTNeoModelTesterDPTModelTesterout_featuresout_indicesnum_hidden_layersvision_configtext_confignum_hidden_groups)model_tester	__class____name__hasattrr  r  copydeepcopy
isinstancedictr  r  )r   target_num_hidden_layersexceptional_classesr   r   r   $set_model_tester_for_less_flaky_test  s6   



r  c                 C   sZ   g d}|D ]}t | |d qg d}|D ]}t| |r*|D ]}t t| ||d qqd S )N)rms_norm_epslayer_norm_epsnorm_epsnorm_epsilonlayer_norm_epsilonbatch_norm_eps      ?)r  r  text_encoderaudio_encoderdecoder)r   r  r   )r  target_attrstarget_attrattrsr   r   r   r   set_config_for_less_flaky_test  s   
r  c                 C   sj   d}g d}t  r/t| tjjr1|  D ]}t|j|r.|D ]}t	||r-t
||d q qd S d S d S )N)	LayerNorm	GroupNorm	BatchNormRMSNormBatchNorm2dBatchNorm1dBitGroupNormActivationWeightStandardizedConv2d)epsepsilonvariance_epsilonr  )rm   r  r  nnr   modulestyper  r  r  r   )modeltarget_namesr  moduler   r   r   r   set_model_for_less_flaky_test*  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   sL   || _ |rt | _d| _nd | _d| _|rt | _d| _d S 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  r   r   r   __init__p  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  r   r   r   	__enter__  s   zCaptureStd.__enter__c                 G   sl   | j r| jt_| j  }| jrtj| t|| _| j	r4| j
t_| j	 }| jr/tj| || _d S d S r  )r  r  r  r  getvaluer  writer  r  r	  r  r  r
  )r  rz  capturedr   r   r   __exit__  s   



zCaptureStd.__exit__c                 C   s8   d}| j r|d| j d7 }| jr|d| j d7 }|S )Nr  zstdout: 
stderr: )r  r  r	  r
  )r  msgr   r   r   __repr__  s   zCaptureStd.__repr__N)TTTr  
__module____qualname____doc__r  r  r  r  r   r   r   r   r  ?  s    
0r  c                       "   e Zd ZdZd fdd	Z  ZS )CaptureStdoutz+Same as CaptureStd but captures only stdoutTc                       t  jd|d d S )NF)r
  r  superr  r  r  r  r   r   r    r  zCaptureStdout.__init__Tr  r  r  r  r  __classcell__r   r   r&  r   r!        r!  c                       r   )CaptureStderrz+Same as CaptureStd but captures only stderrTc                    r"  )NF)r  r  r#  r%  r&  r   r   r    r  zCaptureStderr.__init__r'  r(  r   r   r&  r   r+    r*  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-  r   r   r   r    s   
zCaptureLogger.__init__c                 C   s   | j | j | S r  )r-  
addHandlerr0  r  r   r   r   r    s   zCaptureLogger.__enter__c                 G   s   | j | j | j | _d S r  )r-  removeHandlerr0  r.  r  r  )r  rz  r   r   r   r    s   zCaptureLogger.__exit__c                 C   s   d| j  dS )Nz
captured: r  )r  r  r   r   r   r    r  zCaptureLogger.__repr__Nr  r   r   r   r   r,    s    r,  c              	   c   s8    t  }zt |  dV  W t | dS t | w )ae  
    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("openai-community/gpt2")  # calls logger.info() several times
    ```
    N)transformers_loggingget_verbosityset_verbosity)level
orig_levelr   r   r   LoggingLevel  s   
r8  c                   @   s@   e Zd ZdZddee dee ddfddZdd	 Zd
d ZdS )TemporaryHubRepoa  Create a temporary Hub repository and return its `RepoUrl` object. This is similar to
    `tempfile.TemporaryDirectory` and can be used as a context manager. For example:

        with TemporaryHubRepo(token=self._token) as temp_repo:
            ...

    Upon exiting the context, the repository and everything contained in it are removed.

    Example:

    ```python
    with TemporaryHubRepo(token=self._token) as temp_repo:
        model.push_to_hub(tmp_repo.repo_id, token=self._token)
    ```
    N	namespacer  r  c                 C   sf   || _ t "}t|j}|d ur| d| }tj|| j d| _W d    d S 1 s,w   Y  d S )N/)r  )r  tempfileTemporaryDirectoryr   namehuggingface_hubcreate_reporepo_url)r  r:  r  tmp_dirrepo_idr   r   r   r  	  s   

"zTemporaryHubRepo.__init__c                 C      | j S r  )rA  r  r   r   r   r    s   zTemporaryHubRepo.__enter__c                 C   s   t | jj| jdd d S )NT)rC  r  
missing_ok)r   rA  rC  r  )r  rz  r   tbr   r   r   r    s   zTemporaryHubRepo.__exit__NN)	r  r  r  r  r   rx  r  r  r  r   r   r   r   r9    s
     r9  r  c              	   c   sB    t | } ztjd|  dV  W tj|  dS tj|  w )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  insertremove)r  r   r   r   ExtendSysPath  s   
rK  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 	 r.|d 	 r. nq|r5|| _
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_dirr   
_tests_dir_examples_dir_src_dir)r  r  uprB  r   r   r   setUp}  s   
zTestCasePlus.setUpc                 C   rD  r  )rQ  r  r   r   r   test_file_path     zTestCasePlus.test_file_pathc                 C   
   t | jS r  )rx  rQ  r  r   r   r   test_file_path_str     
zTestCasePlus.test_file_path_strc                 C   rD  r  )rT  r  r   r   r   test_file_dir  r]  zTestCasePlus.test_file_dirc                 C   r^  r  )rx  rT  r  r   r   r   test_file_dir_str  r`  zTestCasePlus.test_file_dir_strc                 C   rD  r  )rW  r  r   r   r   r    r]  zTestCasePlus.tests_dirc                 C   r^  r  )rx  rW  r  r   r   r   tests_dir_str  r`  zTestCasePlus.tests_dir_strc                 C   rD  r  )rX  r  r   r   r   examples_dir  r]  zTestCasePlus.examples_dirc                 C   r^  r  )rx  rX  r  r   r   r   examples_dir_str  r`  zTestCasePlus.examples_dir_strc                 C   rD  r  )rV  r  r   r   r   repo_root_dir  r]  zTestCasePlus.repo_root_dirc                 C   r^  r  )rx  rV  r  r   r   r   repo_root_dir_str  r`  zTestCasePlus.repo_root_dir_strc                 C   rD  r  )rY  r  r   r   r   src_dir  r]  zTestCasePlus.src_dirc                 C   r^  r  )rx  rY  r  r   r   r   src_dir_str  r`  zTestCasePlus.src_dir_strc                 C   sZ   t j }| jg}d| jv 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   r  ri  rb  appendre  rc  getr  )r  envpathsr   r   r   get_env  s   
	
zTestCasePlus.get_envNc                 C   s   |dur:|du r
d}|du rd}t | }|ds#td| d|du r2| r2tj|dd |jddd n|du r@d}|du rFd}t	 }|du rT| 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rS  exist_ok)r   rR  r   r   existsr  rmtreemkdirr<  mkdtemprO  rl  )r  rB  beforeafterr  r   r   r   get_auto_remove_tmp_dir  s*   

z$TestCasePlus.get_auto_remove_tmp_dirc                 C   s|   t dstdtd| d}t }t||  d W d   n1 s'w   Y  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("google-t5/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 ''rn  Nr  r  r  i   )
r  r   shlexsplitr  execute_subprocess_asyncrp  r   r
  replace)r  one_liner_strr  csmax_rssr   r   r   python_one_liner_max_rss  s    z%TestCasePlus.python_one_liner_max_rssc                 C   sb   | j D ]	}tj|dd qg | _ t r-t  t  ttj	
 D ]}d|v r,tj	|= q"d S d S )NTrr  
ACCELERATE)rO  r  rw  r%   r   _reset_stater   listr   r   keys)r  r  kr   r   r   tearDown:  s   
zTestCasePlus.tearDown)NNN)r  r  r  r  r[  propertyr\  r_  ra  rb  r  rc  rd  re  rf  rg  rh  ri  rp  r|  r  r  r   r   r   r   rL  .  s>    N












D!rL  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   r   r  r   r   )r   r   r   r   mockenvI  r   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  |  fdd|D  dS  |  fdd|D  w )	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 r   r   .0r  r~  r   r   
<dictcomp>g      z#mockenv_context.<locals>.<dictcomp>c                 3   s    | ]	}| vr|V  qd S r  r   r  r~  r   r   	<genexpr>i  s    z"mockenv_context.<locals>.<genexpr>c                    s   g | ]}  |d qS r  popr  r~  r   r   
<listcomp>m      z#mockenv_context.<locals>.<listcomp>Nc                    s   g | ]}  |qS r   r  r  r~  r   r   r  q  r  )r   r   setr  	frozensetupdate)rJ  r  stompedupdate_afterremove_afterr   r~  r   mockenv_contextU  s    


r  c                 C   s.   d}|t vr| j|dddd dt |< dS 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)actionr   helpr   N)pytest_opt_registered	addoption)parseroptionr   r   r   pytest_addoption_sharedz  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
rH||
 q<q8|r|jdd dd t|d dA}d}|d t|D ]-\}}
|
j|k r|t||  d| d  n||
jdd|
jdd|
j d qhW d   n1 sw   Y  dd }d|j_t|d d}|||| _|   W d   n1 sw   Y  t|d d}|||| _||  W d   n1 sw   Y  d|j_t|d  d}|||| _|   W d   n	1 sw   Y  t|d! d}|||| _|   W d   n	1 s2w   Y  t|d" d}|||| _|   |   W d   n	1 sXw   Y  d#| _t|d$ d}|||| _|   W d   n	1 s}w   Y  t|d% d}|||| _|   W d   n	1 sw   Y  || _|| _||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/Trt  c                    s   i | ]}|  d | dqS )r;  z.txtr   r  r   r   r   r    s    z0pytest_terminal_summary_main.<locals>.<dictcomp>)		durationserrorsfailures_longfailures_shortfailures_linepassesstatssummary_shortwarningsdurationc                 S   rD  r  )r  xr   r   r   <lambda>  s    z.pytest_terminal_summary_main.<locals>.<lambda>)r   reverser  wg?zslowest durations
z durations < z secs were omittedz02.2fzs z<8 r  Nc              	   S   sp   |  d}|s	d S | dd |D ]$}| |}| 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   )

getreports	write_sep_getfailureheadliner  r  longreprtextr  S_twline)trreportsrepr  longreprr   r   r   summary_failures_short  s   

z<pytest_terminal_summary_main.<locals>.summary_failures_shortautor  r  r  r  r  r  wPpsxXEfr  r  )_pytest.configr  r  r  get_terminal_writerr  tbstylereportcharsr   rx  r  valuesr  rl  sortopenr  	enumerater  whennodeidr  summary_failuressummary_errorssummary_warningsshort_test_summarysummary_stats)r  idr  r  orig_writerorig_tbstyleorig_reportcharsreport_filesdlistreplistr  fdurations_minir  r   r  r   pytest_terminal_summary_main  s   





(	




	

r  c                   @   s   e Zd Zdd ZdS )
_RunOutputc                 C   s   || _ || _|| _d S r  )
returncoder  r  )r  r  r  r  r   r   r   r  	  s   
z_RunOutput.__init__N)r  r  r  r  r   r   r   r   r  	  s    r  c                    s&   	 |   I d H }|r|| nd S qr  )readline)streamcallbackr  r   r   r   _read_stream	  s   
r  c              	      s   |rt dd|  tj| d g| dd  R |tjjtjj|dI d H }g g  dfdd	tjtt|j	fd	d
tt|j
 fdd
g|dI d H  t| I d H  S )Nz

Running: r  r   r   )stdinr  r  rn  r  c                    s2   |  d } ||   st|| |d d S d S )Nutf-8)file)decoderstriprl  print)r  sinkpipelabel)quietr   r   tee@	  s
   
z_stream_subprocess.<locals>.teec                       |  t jddS )Nzstdout:r  )r  r  l)r  r  r   r   r  I	      z$_stream_subprocess.<locals>.<lambda>c                    r  )Nzstderr:r  )r  r  r  )r
  r  r   r   r  J	  r  timeout)r  )r  r  asynciocreate_subprocess_exec
subprocessPIPEwaitcreate_taskr  r  r  r  )r  rn  r  r  r  echopr   )r
  r  r  r  r   _stream_subprocess(	  s.   
r     c           
   
   C   s~   t  }|t| |||||d}d| }|jdkr/d|j}	td| d|j d|	 |js=|js=td| d|S )	N)rn  r  r  r  r  r  r   r  r}  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  rn  r  r  r  r  loopresultcmd_strr  r   r   r   r  Q	  s   

r  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.
    PYTEST_XDIST_WORKERgw0z^gwr  r   )r   r   rm  r  r  r  r   )workerr   r   r   pytest_xdist_worker_idg	  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  )port
uniq_deltar   r   r   get_torch_dist_unique_portq	  s   r  r-  c                    s(  ddl }t| tr fdd| D S t| tr"t fdd| D S t| |jr.t|  S t| tr> fdd|  D S t| t	t
|jfrI| S | du rO| S t r_t| tjr_t|   S t rot| rot|    S t| tryt|  S t| |j|j|jfrt|   S tdt|  )	z
    Simplifies an object by rounding float numbers, and downcasting tensors/numpy arrays to get simple equality test
    within tests.
    r   Nc                       g | ]}t | qS r   nested_simplifyr  itemdecimalsr   r   r  	  r  z#nested_simplify.<locals>.<listcomp>c                    r  r   r  r  r  r   r   r  	  r  c                    s"   i | ]\}}t | t | qS r   r  )r  r  vr  r   r   r  	  s   " z#nested_simplify.<locals>.<dictcomp>zNot supported: )numpyr  r  tuplendarrayr  tolistr   itemsrx  r   int64rm   r  Tensorri   r  	is_tensorfloatroundint32float32float16r  	Exceptionr  )objr  npr   r  r   r  }	  s,   




r  c                 C   s   t | ]}| }t|dkr|d dksJ n9t|dks J |d  dks*J |dd D ]}t|d t|d   }|dksFJ q0|d  dksYJ W d    d S W d    d S 1 sdw   Y  d S )	Nr   r   z{}r-  {r  r(  })r  	readlinesr  striplstrip)	file_pathr  linesr  left_indentr   r   r   "check_json_file_has_correct_format	  s   
"r6  c                 C   s   t | tjjr	| S | | fS r  )r  collectionsabcr   r  r   r   r   	to_2tuple	  s   r9  c                   @   s   e Zd ZdS )SubprocessCallExceptionN)r  r  r  r   r   r   r   r:  	  s    r:  commandc              
   C   sr   zt j| t jd}|rt|dr|d}|W S W dS  t jy8 } ztdd|  d|j  |d}~ww )z
    Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture
    if an error occurred 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;  return_stdoutr?  r   r   r   r   run_command	  s   

rA  c                   @   sF   e Zd ZdZdd ZdddZdedefd	d
Ze	defddZ
dS )RequestCountera  
    Helper class that will count all requests made online.

    Might not be robust if urllib3 changes its logging format but should be good enough for us.

    Usage:
    ```py
    with RequestCounter() as counter:
        _ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert")
    assert counter["GET"] == 0
    assert counter["HEAD"] == 1
    assert counter.total_calls == 1
    ```
    c                    sV   t t _t  _g  _ fdd}tjt	j
jd|t	j
jjd _ j  _ S )Nc                    s    fdd}|S )Nc                     s   j t   | i |S r  )_extra_inforl  	threading	get_identr   )funcr  r   r   wrap	  s   zHRequestCounter.__enter__.<locals>.patched_with_thread_info.<locals>.wrapr   )rF  rG  r  )rF  r   patched_with_thread_info	  s   z:RequestCounter.__enter__.<locals>.patched_with_thread_infodebug)side_effect)r   r   _counterrD  rE  
_thread_idrC  r   objecturllib3connectionpoollogrI  patcherstartr   )r  rH  r   r  r   r  	  s   

zRequestCounter.__enter__r  Nc                 O   s   t | jjt | jksJ t| j| jjD ]2\}}|| jkrq|jd dkr'q|jd |jdd   }dD ]}||v rF| j|  d7  <  nq5q| j	  d S )Nr  i3  r   r   )	HEADGETPOSTPUTDELETECONNECTOPTIONSTRACEPATCH)
r  r   call_args_listrC  ziprL  r   rK  rQ  stop)r  r   r   	thread_idcallrP  methodr   r   r   r  	  s   
zRequestCounter.__exit__r   c                 C   s
   | j | S r  )rK  )r  r   r   r   r   __getitem__	     
zRequestCounter.__getitem__c                 C   s   t | j S r  )sumrK  r  r  r   r   r   total_calls	  s   zRequestCounter.total_callsr  N)r  r  r  r  r  r  rx  r   rb  r  re  r   r   r   r   rB  	  s    
rB     max_attemptswait_before_retrydescriptionc                    s    fdd}|S )a  
    To decorate flaky tests. They will be retried on failures.

    Please note that our push tests use `pytest-rerunfailures`, which prompts the CI to rerun certain types of
    failed tests. More specifically, if the test exception contains any substring in `FLAKY_TEST_FAILURE_PATTERNS`
    (in `.circleci/create_circleci_config.py`), it will be rerun. If you find a recurrent pattern of failures,
    expand `FLAKY_TEST_FAILURE_PATTERNS` in our CI configuration instead of using `is_flaky`.

    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                       t   fdd}|S )Nc                     s   d}| k rAz| i |W S  t y< } z"td| d| d  d d ur.t |d7 }W Y d }~nd }~ww | k s| i |S )Nr   Test failed with  at try r;  rK  )r+  r-  errortimesleepr   r   retry_countr
  rh  test_func_refri  r   r   r   
  s   

z,is_flaky.<locals>.decorator.<locals>.wrapperr   rt  r   rh  ri  rt  r   r   
  s   zis_flaky.<locals>.decoratorr   )rh  ri  rj  r   r   rv  r   is_flaky
  s   rx  r(  c                    s    fdd}|S )a  
    To decorate tests that download from the Hub. They can fail due to a
    variety of network issues such as timeouts, connection resets, etc.

    Args:
        max_attempts (`int`, *optional*, defaults to 5):
            The maximum number of attempts to retry the flaky test.
        wait_before_retry (`float`, *optional*, defaults to 2):
            If provided, will wait that number of seconds before retrying the test.
    c                    rk  )Nc                     s   d}| k rPz| i |W S  t jjt jjt jjt jjt jjfyK } z"td| d| d  d d ur=t	
 |d7 }W Y d }~nd }~ww | k s| i |S )Nr   rl  rm  r;  z8 as it couldn't connect to the specified Hub repository.)requests
exceptionsConnectionErrorTimeoutReadTimeout	HTTPErrorRequestExceptionr-  rn  ro  rp  rq  rs  r   r   r   8
  s*   
z-hub_retry.<locals>.decorator.<locals>.wrapperr   ru  rv  rw  r   r   7
  s   zhub_retry.<locals>.decoratorr   )rh  ri  r   r   rv  r   	hub_retry+
  s   r  c                 C   s   ddl }|jd| S )a  
    Decorator marking a test with order(1). When pytest-order plugin is installed, tests marked with this decorator
    are garanteed to run first.

    This is especially useful in some test settings like on a Gaudi instance where a Gaudi device can only be used by a
    single process at a time. So we make sure all tests that run in a subprocess are launched first, to avoid device
    allocation conflicts.
    r   Nr   )r   r   orderr   r   r   r   	run_firstU
  s   	r  c              
   C   s   |du rt tjdd}d}t|}|d}|d}|j||d |j	||||fd}|
  z|j|d}	|  W n tyZ }
 z|  | |
 W Y d}
~
nd}
~
ww |j|d |	d durq| |	d   dS 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`.
    NPYTEST_TIMEOUTiX  spawnr   r  )targetr   rn  )r   r   r   rm  multiprocessingget_contextQueueJoinableQueueputProcessrR  	task_doner+  	terminatefailr  )r   target_funcinputsr  start_methohdctxinput_queueoutput_queueprocessresultsr   r   r   r   run_test_in_subprocessc
  s*   


r  c                    s$   ddl t  fdd}|S )z
    To decorate a test to run in a subprocess using the `subprocess` module. This could avoid potential GPU memory
    issues (GPU OOM or a test that causes many subsequential failing with `CUDA error: device-side assert triggered`).
    r   Nc               
      s  t dd dkr | i | d S dt jddd d }zkdd l}|t j}d|d< d|d< d	|v rxt|d	 j	j
}t|D ]"\}}||d	 j
v rf|d
dd  }d
 jd  g| ||< qDtj ddg| }dd |D }n	tj dd| g}tj||ddd W d S  tjy } zg|j }	|	d}
d|
d v rd}|
dd  D ]9}|dr|tdd  }d|ddd  }q|dr|drd|v r nt|dkr|d| 7 }qd| }|g|
 }
d|
}	j|	ddd }~ww )N_INSIDE_SUB_PROCESS1r  PYTEST_CURRENT_TESTr  r   trueCIpytestconfigz::r   __file__z-mr   c                 S   s   g | ]}|d vr|qS ))z--no-summaryr   )r  r  r   r   r   r  
  r  z>run_test_using_subprocess.<locals>.wrapper.<locals>.<listcomp>T)rn  checkcapture_outputr  z= test session starts =r  zFAILED z - r  z failed in z(subprocess) F)pytrace)r   r  r  r   rm  r  r  r  r  invocation_paramsr   r  __globals__r  
executabler  runr>  r  r  r   r  r  r  )r   r   testr  rn  r;  idxr  r   exception_messager4  textr  rF  r   r   r   r   
  sN    




z*run_test_using_subprocess.<locals>.wrapper)r   r   r   )rF  r   r   r  r   run_test_using_subprocess
  s   1r  c                 C   s   d}t j|| t jd}d}t|D ])\}}d|v r&d|vr&t dd|||< d|v s.d	|v r:t d
|r:|r:d} nqd}|sDd|}|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`.
    z&(```(?:python|py)\s*\n\s*>>> )(.*?```))flagsFzload_dataset(z# doctest: +IGNORE_RESULTz(>>> .*load_dataset\(.*)z\1 # doctest: +IGNORE_RESULTz>>>z...zcuda|to\(0\)|device=0Tr  )r  r  DOTALLr  r  searchr  )stringskip_cuda_testscodeblock_pattern
codeblocksis_cuda_foundr  	codeblockmodified_stringr   r   r   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
          )*)
        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$  rL  )r  r  r>  r&  r   r   rL    s   zHfDocTestParser.parse)r  )r  r  r  r  r  compile	MULTILINEVERBOSE_EXAMPLE_REboolr   r   rm  r  __annotations__rL  r)  r   r   r&  r   r  
  s   
 
r  c                   @   s"   e Zd ZdZdee f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r"| jjj| j| jd| jjd}n)zt	| j| jj| jdd}W n t
yJ   | jdrGtd| j  n Y nw |t d	}t| }td
|t t| jd}|||jD ]}|jrxtj| |j||dV  qhd S )Nc                       s.   e Zd ZdZ fddZ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  r  r   r  r  unwrapr$  _find_lineno)r  r,  source_linesr&  r   r   r  ,  s   


zDHfDoctestModule.collect.<locals>.MockAwareDocTestFinder._find_linenor  Nc              
      sP   t |rd S t  t ||||||| W d    d S 1 s!w   Y  d S r  )r   r   r$  _find)r  r  r,  r>  r  r  globsseenr&  r   r   r  @  s   "z=HfDoctestModule.collect.<locals>.MockAwareDocTestFinder._findrf  )r  r  r  r  r  r  r)  r   r   r&  r   MockAwareDocTestFinder&  s    r  zconftest.py
importmode)rootpath)rootmodedoctest_ignore_import_errorszunable to import module %r)r  F)verboseoptionflagscheckercontinue_on_failure)r>  runnerdtest)doctestDocTestFinderr  r>  r  pluginmanager_importconftest	getoptionr  r   r   r  r   r  r   r   r   r   r  r  rN  r   from_parent)r  r  r  finderr  r  r  r   r   r   collect%  sB   #


zHfDoctestModule.collectN)r  r  r  r  r   r   r  r   r   r   r   r    s    r  devicedispatch_tablec                 O   s<   | |vr|d |i |S ||  }|d u rd S ||i |S )Nr   r   )r  r  r   r   r  r   r   r   _device_agnostic_dispatchk  s   r  )r  rF  r   c                   C      dS Nr   r   r   r   r   r   r        r  c                   C   r  )Nr   r   r   r   r   r   r    r  r   c                   C   r  r  r   r   r   r   r   r    r  xlaseedc                 C   s   t | t|S r  )r  BACKEND_MANUAL_SEED)r  r  r   r   r   backend_manual_seed  s   r  c                 C   
   t | tS r  )r  BACKEND_EMPTY_CACHEr  r   r   r   backend_empty_cache  rc  r  c                 C   r  r  )r  BACKEND_DEVICE_COUNTr  r   r   r   r$    rc  r$  TRANSFORMERS_TEST_DEVICE_SPECzISpecified path to device spec file is not a file or not found. Received 'z.pyz;Provided device spec file was not a Python file! Received 'z.Device spec file did not contain `DEVICE_NAME`zBMismatch between environment variable `TRANSFORMERS_TEST_DEVICE` 'z' and device found in spec 'z'
zNEither unset `TRANSFORMERS_TEST_DEVICE` or ensure it matches device spec name.device_fn_dictattribute_namec              
   C   s`   zt t|}|| t< W d S  ty/ } zd| vr$td| dt d|W Y d }~d S d }~ww )Nr   rq  z` not found in 'z)' and no default fallback function found.)r   device_spec_moduler%  AttributeErrordevice_spec_path)r  r  spec_fnr   r   r   r   update_mapping_from_spec  s   
r  MANUAL_SEED_FNEMPTY_CACHE_FNDEVICE_COUNT_FNc                    s   g }g }dd t |D  t fdd|  D }t |D ]}|jtu r0|j| vr0||j q| D ]}| vr>|| q3|sC|rkdg}|rP|d|  |rZ|d|  |rd|d|  td	|d S )
Nc                 S   s   h | ]}|j qS r   )r>  )r  fieldr   r   r   	<setcomp>  r  z6compare_pipeline_output_to_hub_spec.<locals>.<setcomp>c                    s   g | ]}| v r|qS r   r   )r  r   all_field_namesr   r   r    r  z7compare_pipeline_output_to_hub_spec.<locals>.<listcomp>z(Pipeline output does not match Hub spec!zMatching keys: z*Missing required keys in pipeline output: z2Keys in pipeline output that are not in Hub spec: r  )	r	   sortedr  r   r   r>  rl  r   r  )r?  hub_specmissing_keysunexpected_keysmatching_keysr  
output_keyrn  r   r  r   #compare_pipeline_output_to_hub_spec  s,   
r  c                 C   s"   |rt   t|  tj  d S r  )gcr  r  r  _dynamoreset)r  
gc_collectr   r   r   cleanup  s   r  c                  C   s:   t strddl} | j \}}trd|fS d|fS tdfS )z,
    Get environment device properties.
    r   Nrocmr  )IS_CUDA_SYSTEMIS_ROCM_SYSTEMr  r  get_device_capabilityr%  )r  majorr  r   r   r   rX    s   rX  c                   @   sf   e Zd ZdefddZededefddZededede	fdd	Z
ddedefddZdd ZdS )Expectationsr  c                 C   s   |  t S )zX
        Find best matching expectation based on environment device properties.
        )find_expectationrX  r  r   r   r   get_expectation!  s   zExpectations.get_expectationr   c                 C   s   t dd | D S )Nc                 s   s    | ]}|d u V  qd S r  r   )r  r  r   r   r   r  )  s    z*Expectations.is_default.<locals>.<genexpr>)allr   r   r   r   
is_default'  rH  zExpectations.is_defaultotherc                 C   sp   | \}}|\}}d}||kr|dO }n|dv r|dv r|dO }||kr+|dur+|dO }t |r4|dO }t|S )a  
        Returns score indicating how similar two instances of the `Properties` tuple are.
        Points are calculated using bits, but documented as int.
        Rules are as follows:
            * Matching `type` gives 8 points.
            * Semi-matching `type`, for example cuda and rocm, gives 4 points.
            * Matching `major` (compute capability major version) gives 2 points.
            * Default expectation (if present) gives 1 points.
        r      )r  r     Nr(  r   )r  r  r   )r   r  device_typer  other_device_typeother_majorscorer   r   r   r  +  s   

zExpectations.scorerG  c                    s@   t | j  fddd\}}t |dkrtd  |S )zU
        Find best matching expectation based on provided device properties.
        c                    s   t  | d S r  )r  r  r  r  r   r   r  K  s    z/Expectations.find_expectation.<locals>.<lambda>r  r   z"No matching expectation found for )maxdatar"  r  r  r   )r  r   
result_keyr  r   r  r   r  G  s   zExpectations.find_expectationc                 C   s   | j  S r  )r  r  r   r   r   r  R  s   zExpectations.__repr__N)rG  )r  r  r  r   r  staticmethodDevicePropertiesr  r  r   r  r  r  r   r   r   r   r     s    r  )Fr  )r   )rV  )NNNFF)NNr  FT)r-  )rg  NN)rg  r(  rG  (  r7  
contextlibr  r  r   r  rM  r  r   r  r   r  r  r  r  r  r<  rD  ro  r   r   r   collections.abcr   r   r   r   dataclassesr   r	   r
   r   r.  r   pathlibr   typingr   r   r   r   r   unittest.mockr   huggingface_hub.utilsr?  ry  rN  r   	packagingr   transformersr   r3  integrationsr   r   r   r   r   r    r!   integrations.deepspeedr"   utilsr#   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   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   accelerate.stater   r   accelerate.utils.importsr   _pytest.doctestr   r   r   r   r   r   r   _pytest.outcomesr   _pytest.pathlibr   r   r   rM  SMALL_MODEL_IDENTIFIERDUMMY_UNKNOWN_IDENTIFIERDUMMY_DIFF_TOKENIZER_IDENTIFIERUSERENDPOINT_STAGINGTOKENr  hipr	  r  r  
get_loggerr  r-  r   r   r   r   r   r   r   _run_third_party_device_testsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rx  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/  r0  r2  r4  r7  r<  r>  r@  rA  rB  r   backendimport_moduler  ModuleNotFoundErrorr   r%  is_availabler   r  r  r  r  r  default_backend
jax_devicerG  rI  rS  rT  rU  r&  rZ  r[  r\  r^  ra  rb  rc  re  rf  rg  rh  ri  rj  rk  rl  rm  rn  ro  rp  rq  rr  rs  rt  ru  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,  contextmanagerr8  r9  PathLikerK  TestCaserL  r  r  r  r  r  r  r  r  r  r  r  r  r  r6  r9  r+  r:  rA  rB  rx  r  r  r  r  r  DocTestParserr  r  r  manual_seedr  empty_cacher  r   r  r:  rE  r6  r?  r  r  r$  r  is_filer  r  realpathdevice_spec_dirrl  indeximport_namer  DEVICE_NAMEdevice_namer  r  r  r  r  r  r  rX  r  r   r   r   r   <module>   s  $	 e$	





			



	
















	














	






	
















			.k+ .  ! 		)
 29()*+<
.&L



& &"&