o
    Gih                     @   sN
  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mZ d dlmZ d dlmZmZmZm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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> d	dlm?Z? e: rd dl@Z@e@j(jAduZBe@j(jCduZDeEe@j(ddduZFndZBdZDdZFe	G ZHe?eIZJeJKd e8 oe(Le(LejM(djNe(LdkZOe> oe(Le(LejM(djNe(LdkZPeOoePZQeReSddZTe: rd dl@Z@dejUv rXejUd ZVzeWeVZXW n eYyW ZZ zeYdeV deZ eZdZZ[Zww dejUv rejUd Z[ze@\e[ZXW n e]y ZZ ze]de[ eZdZZ[Zww eJ^de[  n:e@jC_ rdZ[ne@j`_ rdZ[ndZ[e(Le(Le@jajNe(LdkZbebrece@jddZeeere@jdjf_ rdne[Z[d	d lgmhZh d!d" Zid#d$ Zjd%d& Zk			'	(dd)d*Zldd+d,Zmd-eRfd.d/Znd d0d1Zoeod2dd3Zpeod4dd3Zqeod5dd3Zrdd7d8Zsd9d: Ztd;d< Zud=d> Zvd?d@ ZwdAdB ZxdCdD ZydEdF ZzdGdH Z{dIdJ Z|dKdL Z}dMdN Z~dOdP ZdQdR ZdSdT ZdUdV ZdWdX ZdYdZ Zd[d\ Zd]d^ Zd_d` Zdadb Zdcdd Zdedf Zdgdh Zdidj Zdkdl Zdmdn Zdodp Zdqdr Zdsdt Zdudv Zdwdx Zdydz Zd{d| Zd}d~ Zdd Zdd Zdd Zdd Zdd Zddee jB dedB d-e jfddZddededB dedB fddZdee"jjB d-e"jjfddZde"jdeRfddZddee"jj ded-efddZedd ZddefddZddefddZddee j ded-efddZd-e jfddZi Zdd Zdd ZddeRdedB dedB fddZdddZG dd dZdd Zdd Zdd Zdd Ze: rddddddZe@jCje@j`jde@jfjddZe@jCje@j`jdd dd d dZe@jCje@j`je@je@jfje@jdZe@jCjeEe@j`ddddddZe@jCjeEe@j`ddddddZe@jCjeEe@j`ddd d d dZe@jCjeEe@j`ddddddZdedeeef fddʄZdedeRfdd̈́ZdefddτZdefddфZdefddӄZdefddՄZdefddׄZdefddلZdefddۄZe: rdeeef defdd߄ZdejUv rejUd ZeeЃѡ s@edeЛ zedeРd ZW n eҐy` ZZ zedeЛ eZdZZ[Zww eWeԡZzejZW n eؐyw   edw dejUv re[ekrde[ deכ dZed7 ZeeكeZ[eed eed eed eed eed eed eed eedB eRdB f Ze jd-efddZereeef ZneZe: rd dlmZ d dlmZmZmZmZmZ 	dde@jjdededeRdB d-ee f
ddZ	dde@jjdededeRdB d-ef
ddZG dd deރZdS (      N)UserDict)contextmanager)BytesIOStringIO)Path)TYPE_CHECKINGAnyCallableSet)norm)version   )DIFFUSERS_REQUEST_TIMEOUT)BACKENDS_MAPPINGis_accelerate_availableis_bitsandbytes_availableis_compel_availableis_flax_availableis_gguf_availableis_kernels_availableis_note_seq_availableis_nvidia_modelopt_availableis_onnx_availableis_opencv_availableis_optimum_quanto_availableis_peft_availableis_timm_availableis_torch_availableis_torch_versionis_torchao_availableis_torchsde_availableis_transformers_available)
get_loggerxpuFzdiffusers.utils.testing_utils' is deprecated and will be removed in a future version. Determinism and device backend utilities have been moved to `diffusers.utils.torch_utils`. peftz0.5transformersz4.33BIG_GPU_MEMORY(   DIFFUSERS_TEST_BACKENDz+Failed to import `DIFFUSERS_TEST_BACKEND` 'zg'! This should be the name of an installed module                     to enable a specified backend.):
DIFFUSERS_TEST_DEVICEzRUnknown testing device specified by environment variable `DIFFUSERS_TEST_DEVICE`: ztorch_device overrode to cudacpuz1.12mps) get_torch_cuda_device_capabilityc                 O   sV   t  stdtj| |g|R i |s)J d| |    d| |   ddS )Nz3PyTorch needs to be installed to use this function.FzMax diff is absolute z. Diff tensor is .T)r   
ValueErrortorchallcloseabsmax)abargskwargs r8   Q/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/utils/testing_utils.pytorch_all_close   s
   *r:   c                 C   s,   t | |t| t|  }d|  }|S )N      ?)npdotr   mean)r4   r5   
similaritydistancer8   r8   r9    numpy_cosine_similarity_distance   s   rA   c                 C   s   |   |  } }|  D ]\}}t|trt|| |< q| D ]\}}t|tr0t|||< q!| D ]}||vr< dS | | || krG dS q3|D ]	}|| vrS dS qJdS )NFT)copyitems
isinstancesetsorted)dict1dict2keyvaluer8   r8   r9   check_if_dicts_are_equal   s(   

rK   test_corrections.txtexpected_slicec                 C   s   |rt jdd tjd}t | st | } |r&| ddd dd df } t|  	 
 t jdd}|d	| d
}|d\}}	}
|
 d }
t|d}td||	|
|g|d W d    d S 1 smw   Y  d S )Ni'  )	thresholdPYTEST_CURRENT_TESTr   
 tensorz = np.arrayz::r4   file)r0   set_printoptionsosenvironget	is_tensor
from_numpystrdetachr+   flattentofloat32replacesplitopenprintjoin)rT   limit_to_slicesmax_torch_printfilenameexpected_tensor_name	test_name
tensor_str
output_str	test_file
test_classtest_fnfr8   r8   r9   print_tensor_test   s   

$"rr   c                 C   sZ   t  d d }tjtj|}|ds"tj|}|dr| r+t||  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stackrX   pathabspathdirnameendswithr   as_posix)append_pathcaller__file__	tests_dirr8   r8   r9   get_tests_dir   s   	

r~   returnc                 C   s.   |   } | dv r
dS | dv rdS td|  )z
    Converts a string representation of truth to `True` (1) or `False` (0). True values are `y`, `yes`, `t`, `true`,
    `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`;
    )yyesttrueon1r   )nnorq   falseoff0r   zinvalid truth value )lowerr/   )rJ   r8   r8   r9   str_to_bool   s   r   c                 C   sV   zt j|  }W n ty   |}Y |S w zt|}W |S  ty*   td|  dw )NzIf set, z must be yes or no.)rX   rY   KeyErrorr   r/   )rI   defaultrJ   _valuer8   r8   r9   parse_flag_from_env   s   
r   RUN_SLOW)r   RUN_NIGHTLYRUN_COMPILEr;   c                 C   s`   |du rt }d}| D ]}||9 }q
g }t|D ]}|| |  qtj|tjd|  S )zCreates a random float32 tensorNr   )datadtype)	
global_rngrangeappendrandomr0   rT   floatview
contiguous)shapescalerngname
total_dimsdimvalues_r8   r8   r9   floats_tensor   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)unittest
skipUnless_run_slow_tests	test_caser8   r8   r9   slow	     r   c                 C   r   )z
    Decorator marking a test that runs nightly in the diffusers CI.

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

    ztest is nightly)r   r   _run_nightly_testsr   r8   r8   r9   nightly  r   r   c                 C   r   )z
    Decorator marking a test that runs compile tests in the diffusers CI.

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

    ztest is torch compile)r   r   _run_compile_testsr   r8   r8   r9   is_torch_compile  r   r   c                 C      t t d| S )zo
    Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed.
    test requires PyTorch)r   r   r   r   r8   r8   r9   require_torch'     r   c                 C   s   t t o	tddd| S )zl
    Decorator marking a test that requires PyTorch 2. These tests are skipped when it isn't installed.
    >=z2.0.0ztest requires PyTorch 2)r   r   r   r   r   r8   r8   r9   require_torch_2.  s   r   c                        fdd}|S )zPDecorator marking a test that requires torch with a specific version or greater.c                    &   t  otd }t|d  | S )Nr   z>test requires torch with the version greater than or equal to r   r   r   r   r   correct_torch_versiontorch_versionr8   r9   	decorator:     
z6require_torch_version_greater_equal.<locals>.decoratorr8   r   r   r8   r   r9   #require_torch_version_greater_equal7     r   c                    r   )zMDecorator marking a test that requires torch with a specific version greater.c                    r   )N>z2test requires torch with the version greater than r   r   r   r8   r9   r   F  r   z0require_torch_version_greater.<locals>.decoratorr8   r   r8   r   r9   require_torch_version_greaterC  r   r   c                 C   s   t t otdkd| S )z8Decorator marking a test that requires CUDA and PyTorch.r*   ztest requires PyTorch+CUDAr   r   r   torch_devicer   r8   r8   r9   require_torch_gpuO     r   c                    r   )Nc                    s,   t j rt }tt|t kdS d S )Nz/Test not supported for this compute capability.)r0   r*   is_availabler-   r   r   r   )r   current_compute_capabilityexpected_compute_capabilityr8   r9   r   W  s   
z3require_torch_cuda_compatibility.<locals>.decoratorr8   )r   r   r8   r   r9    require_torch_cuda_compatibilityV     r   c                 C   s   t t otdkd| S )zJDecorator marking a test that requires an accelerator backend and PyTorch.r+   z!test requires accelerator+PyTorchr   r   r8   r8   r9   require_torch_acceleratorc  r   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)r   r   skipr0   r   r*   device_countr   r0   r8   r8   r9   require_torch_multi_gpuj  s   r   c                 C   sD   t  s
td| S ddl}t|j dkp|j dkd| S )z
    Decorator marking a test that requires a multi-accelerator setup (in PyTorch). These tests are skipped on a machine
    without multiple hardware accelerators.
    r   r   Nr   z,test requires multiple hardware accelerators)r   r   r   r0   r   r*   r   r#   r   r8   r8   r9   require_torch_multi_acceleratorx  s   r   c                 C      t ttd| S )zZDecorator marking a test that requires an accelerator with support for the FP16 data type.z+test requires accelerator with fp16 support)r   r   _is_torch_fp16_availabler   r   r8   r8   r9   #require_torch_accelerator_with_fp16     r   c                 C   r   )zZDecorator marking a test that requires an accelerator with support for the FP64 data type.z+test requires accelerator with fp64 support)r   r   _is_torch_fp64_availabler   r   r8   r8   r9   #require_torch_accelerator_with_fp64  r   r   c                 C   sf   t  s
td| S ddl}|j std| S |jd}|jd }t|t	kdt	 d| S )z
    Decorator marking a test that requires a bigger GPU (24GB) for execution. Some example pipelines: Flux, SD3, Cog,
    etc.
    r   r   Ntest requires PyTorch CUDA   @z"test requires a GPU with at least 
 GB memory)
r   r   r   r0   r*   r   get_device_propertiestotal_memoryr   r&   )r   r0   device_propertiesr   r8   r8   r9   require_big_gpu_with_torch_cuda  s   

r   c                 C   s   ddl }|j| } t std| S ddl}|j s)|j	 s)td| S |j	 r5|j	
d}n|j
d}|jd }t|tkdt d| S )z
    Decorator marking a test that requires a bigger hardware accelerator (24GB) for execution. Some example pipelines:
    Flux, SD3, Cog, etc.
    r   Nr   r   r   z3test requires a hardware accelerator with at least r   )pytestmarkbig_acceleratorr   r   r   r0   r*   r   r#   r   r   r   r&   )r   r   r0   r   r   r8   r8   r9   require_big_accelerator  s"   


r   c                 C   s   t t ottd| S )zPDecorator marking a test that requires an accelerator with support for training.z/test requires accelerator with training support)r   r   r   backend_supports_trainingr   r   r8   r8   r9   'require_torch_accelerator_with_training  s   r   c                 C      t tdkd| S )z9Decorator marking a test to skip if torch_device is 'mps'r,   ztest requires non 'mps' devicer   r   r   r   r8   r8   r9   skip_mps  s   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   r   r   r8   r8   r9   require_flax  r   r   c                 C   r   )z
    Decorator marking a test that requires compel: https://github.com/damian0815/compel. These tests are skipped when
    the library is not installed.
    ztest requires compel)r   r   r   r   r8   r8   r9   require_compel  s   r   c                 C   r   )zw
    Decorator marking a test that requires onnxruntime. These tests are skipped when onnxruntime isn't installed.
    ztest requires onnxruntime)r   r   r   r   r8   r8   r9   require_onnxruntime  r   r   c                 C   r   )zq
    Decorator marking a test that requires note_seq. These tests are skipped when note_seq isn't installed.
    ztest requires note_seq)r   r   r   r   r8   r8   r9   require_note_seq  r   r   c                 C   r   )z
    Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no
    hardware accelerator available.
    r+   z$test requires a hardware acceleratorr   r   r8   r8   r9   require_accelerator  s   r   c                 C   r   )zq
    Decorator marking a test that requires torchsde. These tests are skipped when torchsde isn't installed.
    ztest requires torchsde)r   r   r    r   r8   r8   r9   require_torchsde  r   r   c                 C   r   )z
    Decorator marking a test that requires PEFT backend, this would require some specific versions of PEFT and
    transformers.
    ztest requires PEFT backendr   r   USE_PEFT_BACKENDr   r8   r8   r9   require_peft_backend  s   r   c                 C   r   )zi
    Decorator marking a test that requires timm. These tests are skipped when timm isn't installed.
    ztest requires timm)r   r   r   r   r8   r8   r9   require_timm  r   r   c                 C   r   )zy
    Decorator marking a test that requires bitsandbytes. These tests are skipped when bitsandbytes isn't installed.
    ztest requires bitsandbytes)r   r   r   r   r8   r8   r9   require_bitsandbytes  r   r   c                 C   r   )zm
    Decorator marking a test that requires quanto. These tests are skipped when quanto isn't installed.
    ztest requires quanto)r   r   r   r   r8   r8   r9   require_quanto  r   r   c                 C   r   )zu
    Decorator marking a test that requires accelerate. These tests are skipped when accelerate isn't installed.
    ztest requires accelerate)r   r   r   r   r8   r8   r9   require_accelerate  r   r   c                    r   )z
    Decorator marking a test that requires PEFT backend with a specific version, this would require some specific
    versions of PEFT and transformers.
    c                    @   t  otttjdjt k}t|d  | S )Nr$   z9test requires PEFT backend with the version greater than )r   r   parse	importlibmetadatabase_versionr   r   )r   correct_peft_versionpeft_versionr8   r9   r   )  s   

z/require_peft_version_greater.<locals>.decoratorr8   )r   r   r8   r   r9   require_peft_version_greater#  s   r  c                    r   )z
    Decorator marking a test that requires transformers with a specific version, this would require some specific
    versions of PEFT and transformers.
    c                    r   )Nr%   z9test requires transformers with the version greater than )r!   r   r   r   r   r   r   r   )r   correct_transformers_versiontransformers_versionr8   r9   r   :  s   
z7require_transformers_version_greater.<locals>.decoratorr8   )r  r   r8   r  r9   $require_transformers_version_greater4  s   	r  c                    r   )Nc                    B   t  otttjdjt k}t|d  d| S )N
acceleratez7Test requires accelerate with the version greater than r.   )r   r   r   r   r   r   r   r   )r   correct_accelerate_versionaccelerate_versionr8   r9   r   G     
z5require_accelerate_version_greater.<locals>.decoratorr8   )r
  r   r8   r	  r9   "require_accelerate_version_greaterF  r   r  c                    r   )Nc                    r  )Nbitsandbytesz9Test requires bitsandbytes with the version greater than r.   )r   r   r   r   r   r   r   r   )r   correct_bnb_versionbnb_versionr8   r9   r   S  r  z7require_bitsandbytes_version_greater.<locals>.decoratorr8   )r  r   r8   r  r9   $require_bitsandbytes_version_greaterR  r   r  c                    r   )Nc                    s<   t t tj djt  k}t|d  d| S )Nhuggingface_hubz<Test requires huggingface_hub with the version greater than r.   )r   r   r   r   r   r   r   )r   correct_hf_hub_versionhf_hub_versionr8   r9   r   _  s   z1require_hf_hub_version_greater.<locals>.decoratorr8   )r  r   r8   r  r9   require_hf_hub_version_greater^  r   r  c                    r   )Nc                    B   t  otttjdjt k}t|d  d| S )Nggufz1Test requires gguf with the version greater than r.   )r   r   r   r   r   r   r   r   )r   correct_gguf_versiongguf_versionr8   r9   r   k  r  z8require_gguf_version_greater_or_equal.<locals>.decoratorr8   )r  r   r8   r  r9   %require_gguf_version_greater_or_equalj  r   r  c                    r   )Nc                    r  )Ntorchaoz0Test requires torchao with version greater than r.   )r   r   r   r   r   r   r   r   )r   correct_torchao_versiontorchao_versionr8   r9   r   w  r  z;require_torchao_version_greater_or_equal.<locals>.decoratorr8   )r   r   r8   r  r9   (require_torchao_version_greater_or_equalv  r   r!  c                    r   )Nc                    r  )Nmodeloptz1Test requires modelopt with version greater than r.   )r   r   r   r   r   r   r   r   )r   correct_nvidia_modelopt_versionmodelopt_versionr8   r9   r     r  z<require_modelopt_version_greater_or_equal.<locals>.decoratorr8   )r%  r   r8   r$  r9   )require_modelopt_version_greater_or_equal  r   r&  c                    r   )Nc                    r  )Nkernelsz0Test requires kernels with version greater than r.   )r   r   r   r   r   r   r   r   )r   correct_kernels_versionkernels_versionr8   r9   r     r  z;require_kernels_version_greater_or_equal.<locals>.decoratorr8   )r*  r   r8   r)  r9   (require_kernels_version_greater_or_equal  r   r+  c                 C   s   t t d| S )zJ
    Decorator marking a test that will be skipped after PEFT backend
    z%test skipped in favor of PEFT backendr   r   r8   r8   r9   deprecate_after_peft_backend  r   r,  c                  C   s   t j} | j| j}}||fS N)sysversion_infomajorminor)sys_infor0  r1  r8   r8   r9   get_python_version  s   r3  arry
local_pathc                 C   s   t | trU|d ur!t|| dd | dd | dd  S | ds+| dr@tj| td}|	  t
t|j} | S tj| rMt
| } | S td|  d	t | t
jr^	 | S td
)N/rQ   http://https://timeoutIIncorrect path or url, URLs must start with `http://` or `https://`, and  is not a valid pathzjIncorrect format used for numpy ndarray. Should be an url linking to an image, a local path, or a ndarray.)rD   r]   r   rc   rz   
startswithrequestsrZ   r   raise_for_statusr<   loadr   contentrX   rv   isfiler/   ndarray)r4  r5  responser8   r8   r9   
load_numpy  s(   
0

rG  Turlmap_locationweights_onlyc                 C   s0   t j| td}|  tjt|j||d}|S )Nr;  )rI  rJ  )r@  rZ   r   rA  r0   rB  r   rC  )rH  rI  rJ  rF  r4  r8   r8   r9   load_pt  s   rK  imagec                 C   s   t | tr2| ds| drtjtj| dtdj	} n#t
j| r*tj| } ntd|  dt | tjjr<| } ntdtj| } | d} | S )	z
    Loads `image` to a PIL Image.

    Args:
        image (`str` or `PIL.Image.Image`):
            The image to convert to the PIL Image format.
    Returns:
        `PIL.Image.Image`:
            A PIL Image.
    r9  r:  T)streamr<  r=  r>  zdIncorrect format used for image. Should be an url linking to an image, a local path, or a PIL image.RGB)rD   r]   r?  PILImagerd   r@  rZ   r   rawrX   rv   rD  r/   ImageOpsexif_transposeconvert)rL  r8   r8   r9   
load_image  s    


rU  
batch_sizec                 C   s   | j \}}dd ||fD \}}| j||ftjjd} t| tjd } t	| d  
ddddg| } t| } d	|  d
 S )Nc                 s   s    | ]	}||d   V  qdS )   Nr8   .0xr8   r8   r9   	<genexpr>  s    z#preprocess_image.<locals>.<genexpr>)resampleg     o@r      r      g       @r;   )sizeresizerO  rP  LANCZOSr<   arrayastypera   vstack	transposer0   r\   )rL  rV  whr8   r8   r9   preprocess_image  s   
 
rh  output_gif_pathc                 C   s<   |d u rt jddj}| d j|d| dd  dddd |S )	Nz.gifsuffixr   Tr   Fd   )save_allappend_imagesoptimizedurationloop)tempfileNamedTemporaryFiler   save)rL  ri  r8   r8   r9   export_to_gif  s   
ru  c                 c   s    t | }|V  |  d S r-  )ioBufferedWriterflush)raw_frq   r8   r8   r9   buffered_writer   s   
rz  output_ply_pathc                    s  |du rt jddj} j   } j  }tj	 fdddD dd}t
t|d	}|d
 |d |tdt| dd |d |d |d |durk|d |d |d |dur|tdt| dd |d |d |dur|d  t}dd t| | D }td}|D ]
}||j|  qntd}| D ]
}	||j|	  q|dur| D ]}
||jt|
g|
R   qtd}W d   |S W d   |S 1 sw   Y  |S )z&
    Write a PLY file for a mesh.
    Nz.plyrj  c                    "   g | ]} j |    qS r8   vertex_channelsr^   r+   numpyrX  meshr8   r9   
<listcomp>     " z!export_to_ply.<locals>.<listcomp>rN  r   axiswbs   ply
s    format binary_little_endian 1.0
zelement vertex rR   asciis   property float x
s   property float y
s   property float z
s   property uchar red
s   property uchar green
s   property uchar blue
zelement face s%   property list uchar int vertex_index
s   end_header
go@c                 S   s   g | ]\}}g ||R qS r8   r8   )rY  coordrgbr8   r8   r9   r  $  s    z<3f3Bz<3fz<B3I)rr  rs  r   vertsr^   r+   r  facesr<   ru   rz  rd   writebyteslenroundrc  intziptoliststructStructpack)r  r{  coordsr  r  rq   verticesformatitemvertextrir8   r  r9   export_to_ply  s\   












%
%%r  output_obj_pathc                    s   |d u rt jddj} j   } j  }tj	 fdddD dd}dd t
| | D }d	d | D }d
d |D | }t|d}|d| W d    d S 1 sbw   Y  d S )Nz.objrj  c                    r|  r8   r}  rX  r  r8   r9   r  A  r  z!export_to_obj.<locals>.<listcomp>rN  r   r  c                 S   s$   g | ]\}}d j g ||R  qS )z{} {} {} {} {} {})r  )rY  r  colorr8   r8   r9   r  B  s    c              	   S   s>   g | ]}d  t|d d t|d d t|d d qS )z
f {} {} {}r   r   r^  )r  r]   )rY  r  r8   r8   r9   r  F  s   > c                 S   s   g | ]}d | qS )zv r8   )rY  r  r8   r8   r9   r  H  s    rf  rR   )rr  rs  r   r  r^   r+   r  r  r<   ru   r  r  rd   
writelinesrf   )r  r  r  r  vertex_colorsr  combined_datarq   r8   r  r9   export_to_obj:  s   "r  video_framesoutput_video_pathc           
      C   s   t  rdd l}nttd d d|d u rtjddj}|jd }| d j	\}}}|j
||d||fd	}tt| D ]}|| | |j}	||	 q<|S )
Nr   opencvr   export_to_videoz.mp4rj  mp4vrW  )fps	frameSize)r   cv2ImportErrorr   r  rr  rs  r   VideoWriter_fourccr   VideoWriterr   r  cvtColorCOLOR_RGB2BGRr  )
r  r  r  fourccrg  rf  cvideo_writeriimgr8   r8   r9   r  N  s   

r  c                 C   s6   d}|  ds|  dstj|tj| } t| S )NzEhttps://huggingface.co/datasets/fusing/diffusers-testing/resolve/mainr9  r:  )r?  rX   rv   rf   urllibr   quoterG  )rv   base_urlr8   r8   r9   load_hf_numpy_  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optionr8   r8   r9   pytest_addoption_sharedn  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
rF||
 q:q6|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 qfW 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 s0w   Y  t|d" d}|||| _|   |   W d   n	1 sVw   Y  d#| _t|d$ d}|||| _|   W d   n	1 s{w   Y  t|d% d}|||| _|   W d   n	1 sw   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_writerrs   reportsT)parentsexist_okc              	      s$   i | ]}|  d  d| dqS )r6  r   z.txtr8   )rY  kdiridr8   r9   
<dictcomp>  s    z0pytest_terminal_summary_main.<locals>.<dictcomp>)		durationserrorsfailures_longfailures_shortfailures_linepassesstatssummary_shortwarningsrp  c                 S   s   | j S r-  )rp  rZ  r8   r8   r9   <lambda>  s    z.pytest_terminal_summary_main.<locals>.<lambda>)rI   reverser  rf  g?zslowest durations
z durations < z secs were omittedz02.2fzs z<8 rR   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 STACKr   T)redboldz.*_ _ _ (_ ){10,}_ _ rS   r   )

getreports	write_sep_getfailureheadlineresublongreprtextMS_twline)trr  repmsglongreprr8   r8   r9   summary_failures_short  s   

z<pytest_terminal_summary_main.<locals>.summary_failures_shortautor  r  r  r  r  r  wPpsxXEfr  r  r  )_pytest.configr  r  configget_terminal_writerr  tbstylereportcharsr   mkdirr  r   hasattrr   sortrd   r  	enumeraterp  whennodeidr  summary_failuressummary_errorssummary_warningssummary_passesshort_test_summarysummary_stats)r  r  r  r  orig_writerorig_tbstyleorig_reportcharsreport_filesdlistreplistr  rq   durations_minr  r  r8   r  r9   pytest_terminal_summary_main  s   



(	







r     max_attemptswait_before_retrydescriptionc                    s    fdd  S )a  
    To decorate flaky tests (methods or entire classes). 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                    sh   t  r$t j D ]\}}t|r!|dr!t || q S t	  fdd}|S )Ntestc                     s   d}|k rJz| i |W S  t yE } z+d pjd| d d| }t|tjd d ur7t |d7 }W Y d }~nd }~ww |k s| i |S )Nr   z[FLAKY] z failed on attempt r6  z: rU   )	Exception__name__re   r.  stderrtimesleep)r6   r7   retry_counterrr  )r  r  objr  r8   r9   wrapper  s*   
z,is_flaky.<locals>.decorator.<locals>.wrapper)
rt   isclasslist__dict__rC   callabler?  setattr	functoolswraps)r  	attr_name
attr_valuer  r   r  r  r  )r  r9   r     s   
zis_flaky.<locals>.decoratorr8   )r  r  r  r8   r  r9   is_flaky  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;  )targetr6   error)r  rX   rY   rZ   multiprocessingget_contextQueueJoinableQueueputProcessstart	task_doner
  	terminatefailrf   )r   target_funcinputsr<  start_methohdctxinput_queueoutput_queueprocessresultser8   r8   r9   run_test_in_subprocess3  s*   


r5  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )CaptureLoggeraG  
    Args:
    Context manager to capture `logging` streams
        logger: 'logging` logger object
    Returns:
        The captured output is available via `self.out`
    Example:
    ```python
    >>> from diffusers import logging
    >>> from diffusers.testing_utils import CaptureLogger

    >>> msg = "Testing 1, 2, 3"
    >>> logging.set_verbosity_info()
    >>> logger = logging.get_logger("diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.py")
    >>> with CaptureLogger(logger) as cl:
    ...     logger.info(msg)
    >>> assert cl.out, msg + "
"
    ```
    c                 C   s&   || _ t | _t| j| _d| _d S )NrS   )loggerr   rv  loggingStreamHandlershout)selfr7  r8   r8   r9   __init__s  s   
zCaptureLogger.__init__c                 C   s   | j | j | S r-  )r7  
addHandlerr:  r<  r8   r8   r9   	__enter__y  s   zCaptureLogger.__enter__c                 G   s   | j | j | j | _d S r-  )r7  removeHandlerr:  rv  getvaluer;  )r<  excr8   r8   r9   __exit__}  s   zCaptureLogger.__exit__c                 C   s   d| j  dS )Nz
captured: rR   )r;  r?  r8   r8   r9   __repr__  s   zCaptureLogger.__repr__N)r  
__module____qualname____doc__r=  r@  rD  rE  r8   r8   r8   r9   r6  ^  s    r6  c                  C      ddl m}  td |  S )z
    Helper function for reproducible behavior during distributed training. See
    - https://pytorch.org/docs/stable/notes/randomness.html for pytorch
    r   )enable_full_determinismzenable_full_determinism has been moved to diffusers.utils.torch_utils. Importing from diffusers.utils.testing_utils is deprecated and will be removed in a future version.)torch_utilsrJ  r7  warning)_enable_full_determinismr8   r8   r9   rJ    s
   rJ  c                  C   rI  )Nr   )disable_full_determinismzdisable_full_determinism has been moved to diffusers.utils.torch_utils. Importing from diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  rN  r7  rL  )_disable_full_determinismr8   r8   r9   rN    s
   rN  c              
   C      t  sdS dd l}|| } z|jd|jd| }|||}W dS  tyA } z| jdkr6t	d| W Y d }~dS d }~ww )NFr   r^  r^  r   Tr*   zYou have passed a device of type 'cuda' which should work with 'fp16', but 'cuda' does not seem to be correctly installed on your machine: )
r   r0   devicezerosfloat16r`   mulr
  typer/   rS  r0   rZ  r   r4  r8   r8   r9   r         

r   c              
   C   rP  )NFr   rQ  rR  Tr*   zYou have passed a device of type 'cuda' which should work with 'fp64', but 'cuda' does not seem to be correctly installed on your machine: )
r   r0   rS  rT  float64r`   rV  r
  rW  r/   rX  r8   r8   r9   r     rY  r   )r*   r#   r+   r,   r   c                   C      dS Nr   r8   r8   r8   r8   r9   r        r  c                   C   r[  r\  r8   r8   r8   r8   r9   r    r]  reset_peak_memory_statsmax_memory_allocatedsynchronizerS  dispatch_tablec                 O   s<   | |vr|d |i |S ||  }t |s|S ||i |S )Nr   )r  )rS  ra  r6   r7   fnr8   r8   r9   _device_agnostic_dispatch  s   rc  seedc                 C   s    ddl m} td || |S )Nr   )backend_manual_seedzbackend_manual_seed has been moved to diffusers.utils.torch_utils. diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  re  r7  rL  )rS  rd  _backend_manual_seedr8   r8   r9   re    s
   
re  c                 C      ddl m} td || S )Nr   )backend_synchronizezbackend_synchronize has been moved to diffusers.utils.torch_utils. diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  rh  r7  rL  )rS  _backend_synchronizer8   r8   r9   rh    
   rh  c                 C   rg  )Nr   )backend_empty_cachezbackend_empty_cache has been moved to diffusers.utils.torch_utils. diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  rk  r7  rL  )rS  _backend_empty_cacher8   r8   r9   rk  '  rj  rk  c                 C   rg  )Nr   )backend_device_countzbackend_device_count has been moved to diffusers.utils.torch_utils. diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  rm  r7  rL  )rS  _backend_device_countr8   r8   r9   rm  1  rj  rm  c                 C   rg  )Nr   )backend_reset_peak_memory_statszbackend_reset_peak_memory_stats has been moved to diffusers.utils.torch_utils. diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  ro  r7  rL  )rS   _backend_reset_peak_memory_statsr8   r8   r9   ro  ;  rj  ro  c                 C   rg  )Nr   )"backend_reset_max_memory_allocatedzbackend_reset_max_memory_allocated has been moved to diffusers.utils.torch_utils. diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  rq  r7  rL  )rS  #_backend_reset_max_memory_allocatedr8   r8   r9   rq  E  rj  rq  c                 C   rg  )Nr   )backend_max_memory_allocatedzbackend_max_memory_allocated has been moved to diffusers.utils.torch_utils. diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  rs  r7  rL  )rS  _backend_max_memory_allocatedr8   r8   r9   rs  O  rj  rs  c                 C   rg  )Nr   )r   zbackend_supports_training has been moved to diffusers.utils.torch_utils. diffusers.utils.testing_utils is deprecated and will be removed in a future version.)rK  r   r7  rL  )rS  _backend_supports_trainingr8   r8   r9   r   [  rj  r   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   `z` not found in 'z)' and no default fallback function found.)getattrdevice_spec_moduler   AttributeErrordevice_spec_path)rv  rw  spec_fnr4  r8   r8   r9   update_mapping_from_spech  s   
r~  DIFFUSERS_TEST_DEVICE_SPECzCSpecified path to device specification file is not found. Received z.pyz9Provided device spec file is not a Python file! Received z.Device spec file did not contain `DEVICE_NAME`z?Mismatch between environment variable `DIFFUSERS_TEST_DEVICE` 'z' and device found in spec 'z'
zKEither unset `DIFFUSERS_TEST_DEVICE` or ensure it matches device spec name.MANUAL_SEED_FNEMPTY_CACHE_FNDEVICE_COUNT_FNSUPPORTS_TRAININGRESET_PEAK_MEMORY_STATS_FNRESET_MAX_MEMORY_ALLOCATED_FNMAX_MEMORY_ALLOCATED_FNc                  C   sl   t strddl} | j \}}trd|fS d|fS tr2ddl} | j d }d}||@ d? }d|fS tdfS )	z,
    Get environment device properties.
    r   Nrocmr*   architecturel           r#   )IS_CUDA_SYSTEMIS_ROCM_SYSTEMr0   r*   get_device_capabilityIS_XPU_SYSTEMr#   r   )r0   r0  r   archgen_maskgenr8   r8   r9   r     s   r   )_GO_LC_SUPPORTED_PYTORCH_LAYERS)_GROUP_ID_LAZY_LEAF_compute_group_hash"_find_parent_module_in_module_dict/_gather_buffers_with_no_group_offloading_parent2_gather_parameters_with_no_group_offloading_parentmoduleoffload_to_disk_pathoffload_typenum_blocks_per_groupc              	      s  t  }dtdtf fdd}|dkrv|d u rtdg }|  D ]B\}}t|tjjtjjfs5|	|  q t
dt||D ]$}	||	|	|  }
|
sJq=| d|	 d|	t|
 d	  }||| q=q |D ]} ||| jj d
 qe|S |dkr|  D ]\}}t|tr||| q~dd |  D }t| |}t| |}|| }|ri }t|  }|D ]\}}t||}||vrg ||< || 	| q|D ]	}||| q||t |S td| )Ngroup_idr   c                    s   t | }tj d| dS )Ngroup_z.safetensors)r  rX   rv   rf   )r  
short_hashr  r8   r9   get_hashed_filename  s   z<_get_expected_safetensors_files.<locals>.get_hashed_filenameblock_levelzCnum_blocks_per_group must be provided for 'block_level' offloading.r   r   r   _unmatched_group
leaf_levelc                 S   s   h | ]\}}t |tr|qS r8   )rD   r  )rY  r   smr8   r8   r9   	<setcomp>  s
    z2_get_expected_safetensors_files.<locals>.<setcomp>zUnsupported offload_type: )rE   r]   r/   named_childrenrD   r0   nn
ModuleList
Sequentialr   r   r  add	__class__r  named_modulesr  r  r  dictr  r  )r  r  r  r  expected_filesr  unmatched_modulesr   	submoduler  current_modulesr  modules_with_group_offloading
parametersbuffersall_orphansparent_to_tensorsmodule_dicttensor_namer   parent_namer8   r  r9   _get_expected_safetensors_files  sX   
 "



r  c           	      C   s\   t j|sdS t| |||}ttt j|d}|| }|| }| o(| }|||fS )N)FNNz*.safetensors)rX   rv   isdirr  rE   globrf   )	r  r  r  r  r  actual_filesmissing_filesextra_files
is_correctr8   r8   r9    _check_safetensors_serialization  s   
r  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_expectationr   r?  r8   r8   r9   get_expectation  s   zExpectations.get_expectationrI   c                 C   s   t dd | D S )Nc                 s   s    | ]}|d u V  qd S r-  r8   )rY  pr8   r8   r9   r[  %  s    z*Expectations.is_default.<locals>.<genexpr>)allrI   r8   r8   r9   
is_default#  s   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   rW  )r*   r     Nr^  r   )r  r  r  )rI   r  device_typer0  other_device_typeother_majorscorer8   r8   r9   r  '  s   


zExpectations.scoreNNc                    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  r8   r9   r  F  s    z/Expectations.find_expectation.<locals>.<lambda>r  r   z"No matching expectation found for )r3   r   rC   r  r  r/   )r<  rI   
result_keyresultr8   r  r9   r  B  s   zExpectations.find_expectationc                 C   s   | j  S r-  )r   r?  r8   r8   r9   rE  M  s   zExpectations.__repr__N)r  )r  rF  rG  r   r  staticmethodDevicePropertiesboolr  r  r  r  rE  r8   r8   r8   r9   r    s    r  )NNrL   rM   r-  )F)r;   NN)NT)r  NNr  )r  r  r   importlib.metadatart   rv  r8  r"  rX   r   r  r  r.  rr  r  r   urllib.parser  collectionsr   
contextlibr   r   r   pathlibr   typingr   r   r	   r
   r  r<   	PIL.ImagerO  PIL.ImageOpsr@  numpy.linalgr   	packagingr   	constantsr   import_utilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r0   hipr  r*   r  ry  r  Randomr   r  r7  rL  r   r   r   _required_peft_version_required_transformers_versionr   r  getenvr&   rY   backendimport_moduler   ModuleNotFoundErrorr4  r   rS  RuntimeErrorinfor   r#   __version__is_torch_higher_equal_than_1_12r  backendsmps_backend_registeredr,   rK  r-   r:   rA   rK   rr   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&  r+  r,  r3  r]   rE  rG  r  rK  rP  rU  rh  r  ru  rz  r  r  r  r  r  r  r  r   r  r5  r6  rJ  rN  r   r   BACKEND_SUPPORTS_TRAININGempty_cacheBACKEND_EMPTY_CACHEr   BACKEND_DEVICE_COUNTmanual_seedBACKEND_MANUAL_SEEDr^  BACKEND_RESET_PEAK_MEMORY_STATSreset_max_memory_allocated"BACKEND_RESET_MAX_MEMORY_ALLOCATEDr_  BACKEND_MAX_MEMORY_ALLOCATEDr`  BACKEND_SYNCHRONIZEr  rc  re  rh  rk  rm  ro  rq  rs  r   r~  r|  is_filer/   indeximport_namerz  DEVICE_NAMEdevice_namer{  r  tupler  	lru_cacher   DevicePropertiesUserDictdiffusers.hooks._commonr   diffusers.hooks.group_offloadingr  r  r  r  r  r  Moduler  r  r  r8   r8   r8   r9   <module>   sJ   T







	$" 

3 "0+'

















H
