
    i                     ^   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mZ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l0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZC d	dlmDZD  e?       rKd dlEZEeEjZ                  j                  duZGeEjZ                  j                  duZI eJeEjZ                  dd      duZKndZGdZIdZK e	j                         ZM eDeN      ZOeOj                  d        e=       xrX  e-j                   e-j                  ej                  j[                  d            j                         e-j                  d      kD  ZT eC       xrX  e-j                   e-j                  ej                  j[                  d            j                         e-j                  d      kD  ZUeTxr eUZV eW ej                  dd            ZY e?       rCd dlEZEdej                  v r"ej                  d   Z[	  ej                  e[      Z]dej                  v r7ej                  d   Z`	  eEj                  e`      Z]eOj                  de`        neEj                  j                         rdZ`neEj                  j                         rdZ`ndZ` e-j                   e-j                  eEj                        j                         e-j                  d      k\  Zgegr= eheEj                  d      Zjejr&eEj                  j                  j                         rdne`Z`d	d llmmZm d! Znd" Zod# Zp	 	 	 	 dd$Zqdd%Zrd&eWfd'Zsdd(Zt etd)d*      Zu etd+d*      Zv etd,d*      Zwdd-Zxd. Zyd/ Zzd0 Z{d1 Z|d2 Z}d3 Z~d4 Zd5 Zd6 Zd7 Zd8 Zd9 Zd: Zd; Zd< Zd= Zd> Zd? Zd@ ZdA ZdB ZdC ZdD ZdE ZdF ZdG ZdH ZdI ZdJ ZdK ZdL ZdM ZdN ZdO ZdP ZdQ ZdR ZdS ZdT ZdU ZddVe#ee%jD                  f   dWe e   d&e%jD                  fdXZddZed[e e   d\e e   fd]Zd^e#ee'jL                  jL                  f   d&e'jL                  jL                  fd_Zd^e'jL                  d`eWfdaZdd^ee'jL                  jL                     dbed&efdcZedd        ZddeefdfZddgefdhZddiee%jD                     djed&efdkZd&e%jD                  fdlZi Zdm Zdn ZddoeWdpe e   dqe e   fdrZddsZ G dt du      Zdv Zdw Zdx Zdy Z e?       rdYdYdYddYdzZeEj                  jv                  eEj                  jv                  deEj                  jv                  ddzZeEj                  jz                  eEj                  jz                  d{ d| d dzZeEj                  j~                  eEj                  j~                  eEj~                  eEj                  j~                  eEj~                  dzZeEj                  j                   eJeEj                  d}d      ddddzZeEj                  j                   eJeEj                  d}d      ddddzZeEj                  j                   eJeEj                  d~d      d d d dzZeEj                  j                   eJeEj                  dd      ddddzZdedeeef   fdZdedeWfdZdefdZdefdZdefdZdefdZdefdZdefdZdefdZ e?       rdeeef   defdZdej                  v rej                  d   Z eeӫ      j                         s edeӛ       	 edeӐj                  d       Z ej                  e׫      Z	 eؐj                  Zdej                  v re`ek7  rde` deڛ dZedz  Z eeܫ      eZ` eed        eed        eed        eed        eed        eed        eed       e"e#edf   e#eWdf   f   Ze j                  d&efd       Zereeef   ZneZ e?       rid dlmZ d dlmZmZmZmZmZ 	 ddeEj                  j                  dedede eW   d&e!e   f
dZ	 ddeEj                  j                  dedede eW   d&ef
dZ G d de      Zy# e^$ rZ_ e^de[ de_       e_dZ_[_ww xY w# eb$ rZ_ ebde`       e_dZ_[_ww xY w# e$ rZ_ edeӛ       e_dZ_[_ww xY w# e$ r	  ed      w xY w)    N)UserDict)contextmanager)BytesIOStringIO)Path)	TYPE_CHECKINGAnyCallableDictListOptionalSetTupleUnion)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                     t               st        d      t        j                  | |g|i |s>J d| |z
  j	                         j                          d| |z
  j	                          d       y)Nz3PyTorch needs to be installed to use this function.zMax diff is absolute z. Diff tensor is .T)r#   
ValueErrortorchallcloseabsmax)abargskwargss       g/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/utils/testing_utils.pytorch_all_closer@      sp    NOO>>!Q000d-q1ukkm.?.?.A-BBSUVYZUZT_T_TaSbbcddu    c                     t        j                  | |      t        |       t        |      z  z  }d|j                         z
  }|S )N      ?)npdotr   mean)r;   r<   
similaritydistances       r?    numpy_cosine_similarity_distancerI      s9    1a47!23JZ__&&HOrA   c                 n   | j                         |j                         }} | j                         D ]$  \  }}t        |t              st	        |      | |<   & |j                         D ]$  \  }}t        |t              st	        |      ||<   & | D ]  }||vr y| |   ||   k7  s y |D ]  }|| vs y y)NFT)copyitems
isinstancesetsorted)dict1dict2keyvalues       r?   check_if_dicts_are_equalrT      s    ::<5Ekkm '
UeS!E#J' kkm '
UeS!E#J'  e:s#	  e rA   c           	         |rt        j                  d       t        j                  j	                  d      }t        j
                  |       st        j                  |       } |r| ddd dd df   } t        | j                         j                         j                         j                  t         j                              j                  dd      }|j                  d	| d
      }|j                  d      \  }}	}
|
j                         d   }
t        |d      5 }t!        dj#                  ||	|
|g      |       d d d        y # 1 sw Y   y xY w)Ni'  )	thresholdPYTEST_CURRENT_TESTr   
 tensorz = np.arrayz::r;   file)r7   set_printoptionsosenvironget	is_tensor
from_numpystrdetachr1   flattentofloat32replacesplitopenprintjoin)r\   limit_to_slicesmax_torch_printfilenameexpected_tensor_name	test_name
tensor_str
output_str	test_file
test_classtest_fnfs               r?   print_tensor_testrz      s     0

45I??6"!!&)23R(V]]_((*22477FGOOPTVXYJ ##H1E0Fk.RSJ%.__T%:"Iz7mmoa G	h	 OdiiJDEANO O Os   !EEc                 n   t        j                         d   d   }t        j                  j	                  t        j                  j                  |            }|j                  d      s1t        j                  j                  |      }|j                  d      s1| 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endswithr   as_posix)append_pathcaller__file__	tests_dirs      r?   get_tests_dirr      s     ]]_Q'*N ?@I  )GGOOI.	   ) I{+4466rA   returnc                 R    | j                         } | dv ry| dv ry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nory   falseoff0r   zinvalid truth value )lowerr6   )rS   s    r?   str_to_boolr      s:    
 KKME44	7	7/w788rA   c                     	 t         j                  |    }	 t        |      }|S # t        $ r t        d|  d      w xY w# t        $ r |}Y |S w xY w)NzIf set, z must be yes or no.)r`   ra   r   r6   KeyError)rR   defaultrS   _values       r?   parse_flag_from_envr      sp    B

3	B 'F M  	Bxu,?@AA	B   Ms   ? # <AARUN_SLOW)r   RUN_NIGHTLYRUN_COMPILEc                    |t         }d}| D ]  }||z  }	 g }t        |      D ]$  }|j                  |j                         |z         & t	        j
                  |t        j                        j                  |       j                         S )zCreates a random float32 tensorr   )datadtype)	
global_rngrangeappendrandomr7   r\   floatview
contiguous)shapescalerngname
total_dimsdimvalues_s           r?   floats_tensorr      s    
{J c
 F: ,cjjlU*+, <<V5;;7<<UCNNPPrA   c                 B     t        j                  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_cases    r?   slowr   	  s     @8?	JJrA   c                 B     t        j                  t        d      |       S )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   s    r?   nightlyr     s!     F813DEiPPrA   c                 B     t        j                  t        d      |       S )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   s    r?   is_torch_compiler     s!     L813JKIVVrA   c                 J     t        j                  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   s    r?   require_torchr   '  s$     N8135LMiXXrA   c                 f     t        j                  t               xr 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   s    r?   require_torch_2r   .  s6     t813W8Hw8WYrs rA   c                       fd}|S )zPDecorator marking a test that requires torch with a specific version or greater.c                 r    t               xr t        d      } t        j                  |d       |       S )Nr   z>test requires torch with the version greater than or equal to r#   r$   r   r   r   correct_torch_versiontorch_versions     r?   	decoratorz6require_torch_version_greater_equal.<locals>.decorator:  sH     2 4 ^9I$P]9^
x""!%cdqcr#s

 	rA    r   r   s   ` r?   #require_torch_version_greater_equalr   7       rA   c                       fd}|S )zMDecorator marking a test that requires torch with a specific version greater.c                 r    t               xr t        d      } t        j                  |d       |       S )N>z2test requires torch with the version greater than r   r   s     r?   r   z0require_torch_version_greater.<locals>.decoratorF  sG     2 4 ]9I#}9]
x""!%WXeWf#g

 	rA   r   r   s   ` r?   require_torch_version_greaterr   C  r   rA   c                 `     t        j                  t               xr	 t        dk(  d      |       S )z8Decorator marking a test that requires CUDA and PyTorch.r0   ztest requires PyTorch+CUDAr   r   r#   torch_devicer   s    r?   require_torch_gpur   O  s0    m813N8NPlm rA   c                       fd}|S )Nc                     t         j                  j                         r5t               }t	        j
                  t        |      t              k(  d      S y )Nz/Test not supported for this compute capability.)r7   r0   is_availabler3   r   r   r   )r   current_compute_capabilityexpected_compute_capabilitys     r?   r   z3require_torch_cuda_compatibility.<locals>.decoratorW  sK    ::""$)I)K&&&01U;V5WWA  %rA   r   )r   r   s   ` r?    require_torch_cuda_compatibilityr   V  s     rA   c                 `     t        j                  t               xr	 t        dk7  d      |       S )zJDecorator marking a test that requires an accelerator backend and PyTorch.r1   z!test requires accelerator+PyTorchr   r   s    r?   require_torch_acceleratorr   c  s0    s813M8MOrs rA   c                     t               s t        j                  d      |       S ddl} t        j                  |j
                  j                         dkD  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   skipr7   r   r0   device_countr   r7   s     r?   require_torch_multi_gpur   j  sR     5x}}45i@@\8uzz6681<>[\]fggrA   c                     t               s t        j                  d      |       S ddl} t        j                  |j
                  j                         dkD  xs |j                  j                         dkD  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   r7   r   r0   r   r)   r   s     r?   require_torch_multi_acceleratorr   x  sr    
 5x}}45i@@8

!A%E)?)?)AA)EGu rA   c                 T     t        j                  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   s    r?   #require_torch_accelerator_with_fp16r     (    u87EGtu rA   c                 T     t        j                  t        t              d      |       S )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   s    r?   #require_torch_accelerator_with_fp64r     r   rA   c                 h   t               s t        j                  d      |       S ddl}|j                  j                         s t        j                  d      |       S |j                  j                  d      }|j                  dz  } t        j                  |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   r7   r0   r   get_device_propertiestotal_memoryr   r,   )r   r7   device_propertiesr   s       r?   require_big_gpu_with_torch_cudar     s    
 5x}}45i@@::""$:x}}9:9EE

88;$11W=L8&*L^L\\f(g rA   c                 F   ddl }|j                  j                  |       } t               s t	        j
                  d      |       S ddl}|j                  j                         s5|j                  j                         s t	        j
                  d      |       S |j                  j                         r|j                  j                  d      }n|j                  j                  d      }|j                  dz  } t	        j                  |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   r7   r0   r   r)   r   r   r   r,   )r   r   r7   r   r   s        r?   require_big_acceleratorr     s    
 ++I6I5x}}45i@@JJ##%)?)?)A:x}}9:9EEyy!II;;A>!JJ<<Q?$11W=L8&
=n=MZX  rA   c                 l     t        j                  t               xr 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   s    r?   'require_torch_accelerator_with_trainingr     s7    8H!:<!H9  rA   c                 H     t        j                  t        dk7  d      |       S )z9Decorator marking a test to skip if torch_device is 'mps'r2   ztest requires non 'mps' devicer   r   r   r   s    r?   skip_mpsr     s#    W8|u46VWXabbrA   c                 J     t        j                  t               d      |       S )zv
    Decorator marking a test that requires JAX & Flax. These tests are skipped when one / both are not installed
    ztest requires JAX & Flax)r   r   r   r   s    r?   require_flaxr    s%     P8024NOPYZZrA   c                 J     t        j                  t               d      |       S )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   s    r?   require_compelr    s$    
 N8246LMiXXrA   c                 J     t        j                  t               d      |       S )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   s    r?   require_onnxruntimer    s%     Q8024OPQZ[[rA   c                 J     t        j                  t               d      |       S )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   s    r?   require_note_seqr    %     R8468PQR[\\rA   c                 H     t        j                  t        dk7  d      |       S )z
    Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no
    hardware accelerator available.
    r1   z$test requires a hardware acceleratorr   r   s    r?   require_acceleratorr    s&    
 ^8|u46\]^ghhrA   c                 J     t        j                  t               d      |       S )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   s    r?   require_torchsder    r	  rA   c                 B     t        j                  t        d      |       S )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   s    r?   require_peft_backendr    s!    
 O8/1MNyYYrA   c                 J     t        j                  t               d      |       S )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   s    r?   require_timmr    s$     J8024HI)TTrA   c                 J     t        j                  t               d      |       S )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   s    r?   require_bitsandbytesr    s%     Z88:<XYZcddrA   c                 J     t        j                  t               d      |       S )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   s    r?   require_quantor    s%     V8:<>TUV_``rA   c                 J     t        j                  t               d      |       S )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   s    r?   require_accelerater    s%     V868:TUV_``rA   c                       fd}|S )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               xre t        j                  t        j                  t        j                  j                  d            j
                        t        j                        kD  } t        j                  |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_versions     r?   r   z/require_peft_version_greater.<locals>.decorator)  s~    02  (w}}MM),,44V<=JJ8
MM,'8(
x"" $]^j]k"l

 	rA   r   )r!  r   s   ` r?   require_peft_version_greaterr"  #  s     rA   c                       fd}|S )z
    Decorator marking a test that requires transformers with a specific version, this would require some specific
    versions of PEFT and transformers.
    c                 $   t               xre t        j                  t        j                  t        j                  j                  d            j
                        t        j                        kD  } t        j                  |d       |       S )Nr+   z9test requires transformers with the version greater than )r'   r   r  r  r  r  r   r   )r   correct_transformers_versiontransformers_versions     r?   r   z7require_transformers_version_greater.<locals>.decorator:  s    '@'B (0w}}MM),,44^DERRH
MM./H0$
x""(GH\G]^
  	rA   r   )r&  r   s   ` r?   $require_transformers_version_greaterr'  4  s     rA   c                       fd}|S )Nc                 &   t               xre t        j                  t        j                  t        j                  j                  d            j
                        t        j                        kD  } t        j                  |d d      |       S )N
acceleratez7Test requires accelerate with the version greater than r5   )r   r   r  r  r  r  r   r   )r   correct_accelerate_versionaccelerate_versions     r?   r   z5require_accelerate_version_greater.<locals>.decoratorG  s    %<%> &.7==MM),,44\BCPPD
MM,-D."
x""&*abtauuv(w

 	rA   r   )r,  r   s   ` r?   "require_accelerate_version_greaterr-  F       rA   c                       fd}|S )Nc                 &   t               xre t        j                  t        j                  t        j                  j                  d            j
                        t        j                        kD  } t        j                  |d d      |       S )Nbitsandbytesz9Test requires bitsandbytes with the version greater than r5   )r   r   r  r  r  r  r   r   )r   correct_bnb_versionbnb_versions     r?   r   z7require_bitsandbytes_version_greater.<locals>.decoratorS  s    79 'gmmMM),,44^DERR?
MM+&?'
x""#\]h\iij!k

 	rA   r   )r3  r   s   ` r?   $require_bitsandbytes_version_greaterr4  R  r.  rA   c                       fd}|S )Nc                    t        j                  t        j                  t        j                  j                  d            j                        t        j                        kD  } t        j                  |d d      |       S )Nhuggingface_hubz<Test requires huggingface_hub with the version greater than r5   )r   r  r  r  r  r   r   )r   correct_hf_hub_versionhf_hub_versions     r?   r   z1require_hf_hub_version_greater.<locals>.decorator_  sx    !(MM),,445FGHUU"
MM.)"*
x"""&bcqbrrs$t

 	rA   r   )r9  r   s   ` r?   require_hf_hub_version_greaterr:  ^  r.  rA   c                       fd}|S )Nc                 &   t               xre t        j                  t        j                  t        j                  j                  d            j
                        t        j                        k\  } t        j                  |d d      |       S )Nggufz1Test requires gguf with the version greater than r5   )r   r   r  r  r  r  r   r   )r   correct_gguf_versiongguf_versions     r?   r   z8require_gguf_version_greater_or_equal.<locals>.decoratork  s    02  )w}}MM),,44V<=JJ8
]]<(8)
x"" $UVbUccd"e

 	rA   r   )r?  r   s   ` r?   %require_gguf_version_greater_or_equalr@  j  r.  rA   c                       fd}|S )Nc                 &   t               xre t        j                  t        j                  t        j                  j                  d            j
                        t        j                        k\  } t        j                  |d d      |       S )Ntorchaoz0Test requires torchao with version greater than r5   )r%   r   r  r  r  r  r   r   )r   correct_torchao_versiontorchao_versions     r?   r   z;require_torchao_version_greater_or_equal.<locals>.decoratorw      "6"8 #,W]]MM),,44Y?@MM>
]]?+>,
x""#'WXgWhhi%j

 	rA   r   )rE  r   s   ` r?   (require_torchao_version_greater_or_equalrG  v  r.  rA   c                       fd}|S )Nc                 &   t               xre t        j                  t        j                  t        j                  j                  d            j
                        t        j                        k\  } t        j                  |d d      |       S )Nmodeloptz1Test requires modelopt with version greater than r5   )r   r   r  r  r  r  r   r   )r   correct_nvidia_modelopt_versionmodelopt_versions     r?   r   z<require_modelopt_version_greater_or_equal.<locals>.decorator  s    *F*H +-W]]MM),,44Z@ANNN
]]+,N-'
x""+/`aq`rrs-t

 	rA   r   )rL  r   s   ` r?   )require_modelopt_version_greater_or_equalrM    r.  rA   c                       fd}|S )Nc                 &   t               xre t        j                  t        j                  t        j                  j                  d            j
                        t        j                        k\  } t        j                  |d d      |       S )Nkernelsz0Test requires kernels with version greater than r5   )r   r   r  r  r  r  r   r   )r   correct_kernels_versionkernels_versions     r?   r   z;require_kernels_version_greater_or_equal.<locals>.decorator  rF  rA   r   )rR  r   s   ` r?   (require_kernels_version_greater_or_equalrS    r.  rA   c                 D     t        j                  t         d      |       S )zJ
    Decorator marking a test that will be skipped after PEFT backend
    z%test skipped in favor of PEFT backendr  r   s    r?   deprecate_after_peft_backendrU    s%     ^8#335\]^ghhrA   c                  Z    t         j                  } | j                  | j                  }}||fS N)sysversion_infomajorminor)sys_inforZ  r[  s      r?   get_python_versionr]    s(    H>>8>>5E%<rA   arry
local_pathc                    t        | t              r|Rt        || j                  d      d   | j                  d      d   | j                  d      d         j	                         S | j                  d      s| j                  d      rUt        j                  | t              }|j                          t        j                  t        |j                              } | S t        j                  j!                  |       rt        j                  |       } | S t#        d|  d	      t        | t        j$                        r	 | S t#        d
      )N/rY   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.)rM   re   r   rk   r   
startswithrequestsrb   r   raise_for_statusrD   loadr   contentr`   r   isfiler6   ndarray)r^  r_  responses      r?   
load_numpyrr    s   $!
DJJsOB$7C9LdjjY\o^`Nabkkmm__Y'4??:+F||D2KLH%%'7778#3#345D K WW^^D!774=D K [\`[aauv  
D"**	% K 
 	
rA   Turlmap_locationweights_onlyc                     t        j                  | t              }|j                          t	        j
                  t        |j                        ||      }|S )Nrf  )rt  ru  )rk  rb   r   rl  r7   rm  r   rn  )rs  rt  ru  rq  r^  s        r?   load_ptrw    sB    ||C)BCH::gh../lYefDKrA   imagec                 R   t        | t              r| j                  d      s| j                  d      rDt        j                  j                  t        j                  | dt              j                        } nt        j                  j                  |       r t        j                  j                  |       } nAt        d|  d      t        | t        j                  j                        r| } nt        d      t        j                  j                  |       } | 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.
    rd  re  T)streamrg  rh  ri  zdIncorrect format used for image. Should be an url linking to an image, a local path, or a PIL image.RGB)rM   re   rj  PILImagerl   rk  rb   r   rawr`   r   ro  r6   ImageOpsexif_transposeconvert)rx  s    r?   
load_imager    s     %I&%*:*::*FIINN8<<dLe#f#j#jkEWW^^E"IINN5)E[\a[bbvw  
E399??	+r
 	
 LL''.EMM% ELrA   
batch_sizec                    | j                   \  }}d ||fD        \  }}| j                  ||ft        j                  j                        } t        j                  |       j                  t
        j                        dz  } t        j                  | d    j                  dddd      g|z        } t        j                  |       } d| z  d	z
  S )
Nc              3   ,   K   | ]  }||d z  z
    yw)   Nr   ).0xs     r?   	<genexpr>z#preprocess_image.<locals>.<genexpr>  s     &!AAI&s   )resampleg     o@r      r      g       @rC   )sizeresizer|  r}  LANCZOSrD   arrayastyperi   vstack	transposer7   rd   )rx  r  whs       r?   preprocess_imager    s    ::DAq&1v&DAqLL!Q#))*;*;L<EHHUO""2::.6EIIuT{,,Q1a89JFGEU#E;rA   output_gif_pathc                     | t        j                  d      j                  }| d   j                  |d| dd  ddd       |S )	Nz.gifsuffixr   Tr   Fd   )save_allappend_imagesoptimizedurationloop)tempfileNamedTemporaryFiler   save)rx  r  s     r?   export_to_gifr    sS    "55VDII	!HMMABi   rA   c              #   ^   K   t        j                  |       }| |j                          y wrW  )ioBufferedWriterflush)raw_fry   s     r?   buffered_writerr     s$     
% A
GGGIs   +-output_ply_pathc           	         | t        j                  d      j                  }| j                  j	                         j                         j                         }| j                  j                         j                         }t        j                  dD cg c];  }| j                  |   j	                         j                         j                         = c}d      }t        t        |d            5 }|j                  d       |j                  d	       |j                  t        d
t        |       dd             |j                  d       |j                  d       |j                  d       |3|j                  d       |j                  d       |j                  d       |9|j                  t        dt        |       dd             |j                  d       |j                  d       ||dz  j!                         j#                  t$              }t'        |j)                         |j)                               D cg c]  \  }}g || }}}t+        j,                  d      }	|D ]   }
|j                   |	j.                  |
        " nHt+        j,                  d      }	|j)                         D ]   }|j                   |	j.                  |        " |U|j)                         D ]-  }|j                   |	j.                  t        |      g|        / t+        j,                  d      }	ddd       |S c c}w c c}}w # 1 sw Y   |S xY w)z&
    Write a PLY file for a mesh.
    Nz.plyr  r{  r   axiswbs   ply
s    format binary_little_endian 1.0
zelement vertex rZ   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@z<3f3Bz<3fz<B3I)r  r  r   vertsrf   r1   numpyfacesrD   r~   vertex_channelsr  rl   writebyteslenroundr  intziptoliststructStructpack)meshr  coordsr  r  rgbry   coordverticesformatitemvertextris                r?   export_to_plyr    s    "55VDIIZZ $$&,,.FJJNN""$E
((ERqD((+22488:@@BRYZ
[C	ot4	5 $+		45	F}B7AB	%&	%&	%&?GG+,GG-.GG,-GGEM#e*R8'BCGG=>	 ?='')005C #&MMOJJL#E3 %#H  ]]7+F  ,T*+, ]]5)F --/ .V,-. ||~ 5CH3s345]]6*FI$+J O S(%$+J s'   A L<2EMMCMMMoutput_obj_pathc                    | t        j                  d      j                  }| j                  j	                         j                         j                         }| j                  j                         j                         }t        j                  dD cg c];  }| j                  |   j	                         j                         j                         = c}d      }t        |j                         |j                               D cg c]  \  }} dj                  g ||  }}}|j                         D 	cg c]B  }	dj                  t        |	d   dz         t        |	d   dz         t        |	d	   dz               D }}	|D 
cg c]  }
d
|
z   	 c}
|z   }t        |d      5 }|j!                  dj#                  |             d d d        y c c}w c c}}w c c}	w c c}
w # 1 sw Y   y xY w)Nz.objr  r{  r   r  z{} {} {} {} {} {}z
f {} {} {}r   r  zv r  rZ   )r  r  r   r  rf   r1   r  r  rD   r~   r  r  r  r  re   rl   
writelinesrn   )r  r  r  r  r  vertex_colorsr  colorr  r  r  combined_datary   s                r?   export_to_objr  :  s   "55VDIIJJ##%++-EJJNN""$EHHV[\QRd2215<<>BBDJJL\cdeMGJ5<<>[h[o[o[qGr7Cue"""2E2E2H  `e_k_k_mnX[\  SVaZ#c!fqj/3s1vPQz?SnEn19:vTF]:UBM	os	# /q	TYY}-./ / ] o:/ /s&   A GG;AGG &!G%%G.video_framesoutput_video_pathc                    t               rdd l}n$t        t        d   d   j	                  d            | t        j                  d      j                  } |j                  d }| d   j                  \  }}}|j                  ||d||f	      }t        t        |             D ]2  }|j                  | |   |j                        }	|j                  |	       4 |S )
Nr   opencvr   export_to_videoz.mp4r  mp4vr  )fps	frameSize)r   cv2ImportErrorr   r  r  r  r   VideoWriter_fourccr   VideoWriterr   r  cvtColorCOLOR_RGB2BGRr  )
r  r  r  fourccr  r  cvideo_writeriimgs
             r?   r  r  N  s    *84Q7>>?PQRR $77vFKK#S##V,F1o##GAq!??#4f!PQSTv?VL3|$%  ll<?C,=,=>3  rA   c                     d}| j                  d      sN| j                  d      s=t        j                  j                  |t        j
                  j                  |             } t        |       S )NzEhttps://huggingface.co/datasets/fusing/diffusers-testing/resolve/mainrd  re  )rj  r`   r   rn   urllibr  quoterr  )r   base_urls     r?   load_hf_numpyr  _  sL    VH??9%dooj.Iww||Hfll&8&8&>?drA   c                 V    d}|t         vr| j                  |ddd       dt         |<   yy)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options     r?   pytest_addoption_sharedr  n  sC     F**f	 	 	
 )*f% +rA   c           
         ddl m} t        |      sd}| j                  }|j	                         }|j
                  j                  }| j                  }d}t        |      j                  dd       dD ci c]  }|| d| d	| d
 }	}g }
| j                  j                         D ]'  }|D ]   }t        |d      s|
j                  |       " ) |
r|
j                  d d       t        |	d   d      5 }d}|j!                  d       t#        |
      D ]s  \  }}|j$                  |k  r%|j!                  t        |
      |z
   d| d        n<|j!                  |j$                  dd|j&                  dd|j(                   d       u ddd       d }d|j
                  _        t        |	d   d      5 } |||      | _        | j-                          ddd       t        |	d   d      5 } |||      | _         ||        ddd       d|j
                  _        t        |	d   d      5 } |||      | _        | j-                          ddd       t        |	d    d      5 } |||      | _        | j/                          ddd       t        |	d!   d      5 } |||      | _        | j1                          | j1                          ddd       d"| _        t        |	d#   d      5 } |||      | _        | j3                          ddd       t        |	d$   d      5 } |||      | _        | j5                          ddd       t        |	d%   d      5 } |||      | _        | j7                          ddd       || _        || _        ||j
                  _        yc c}w # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   {xY w# 1 sw Y   RxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w)&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|   reportsT)parentsexist_ok)		durationserrorsfailures_longfailures_shortfailures_linepassesstatssummary_shortwarningsra  r   z.txtr  c                     | j                   S rW  )r  )r  s    r?   <lambda>z.pytest_terminal_summary_main.<locals>.<lambda>  s
     rA   )rR   reverser  r  g?zslowest durations
z durations < z secs were omittedz02.2fzs z<8 rZ   Nc           	      d   | j                  d      }|sy | j                  dd       |D ]  }| j                  |      }| j                  d|dd       t        j                  dd|j
                  d	t        j                  t        j                  z        }| j                  j                  |        y )
Nfailed=zFAILURES SHORT STACKr   T)redboldz.*_ _ _ (_ ){10,}_ _ r[   r   )

getreports	write_sep_getfailureheadlineresublongreprtextMS_twline)trr  repmsglongreprs        r?   summary_failures_shortz<pytest_terminal_summary_main.<locals>.summary_failures_short  s    --)
S01 	"C((-CLLct$L7vv6C<L<LaQSQUQUXZX\X\Q\]HFFKK!	"rA   autor  r  r  r  r  r  wPpsxXEfr  r  r  )_pytest.configr  r  configget_terminal_writerr  tbstylereportcharsr   mkdirr  r   hasattrr   sortrl   r  	enumerater  whennodeidr  summary_failuressummary_errorssummary_warningssummary_passesshort_test_summarysummary_stats)r  idr  r  orig_writerorig_tbstyleorig_reportcharsdirkreport_filesdlistreplistr  ry   durations_minr  r  s                    r?   pytest_terminal_summary_mainr4    s   ( 6r7YYF,,.K==((L~~
CIOOD4O0

 	
cU!B4q4  L $ E88??$ " 	"CsJ'S!	"" 

+T
:,{+S1 	OQ MGG)*#E* O3<<-/GGs5zA~.mM?J\]^3<<.b"Qszzl"MN	O	O"( #FMM	l?+S	1 Q'2

 
l+,c	2 #a'2r"# #FMM	l?+S	1 Q'2
 
l8$c	* a'2
 
l:&	, '2


  BN	l8$c	* a'2
 
l?+S	1  Q'2
  
l7#S	) Q'2

 BF%BN(FMM}2	O 	O< 
# #
        ss   4N4BN4N'*N4)OO/O"O(O4P N$'N14N>OOO%(O14O= P	max_attemptswait_before_retrydescriptionc                       f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                 0    t        j                         r^t         j                  j	                               D ]6  \  }}t        |      s|j                  d      s$t         | |             8  S t        j                          fd       }|S )Ntestc            	         d}|k  r		  | i |S  | i |S # t         $ r]}dxs j                  d| d d| }t        |t        j                         t        j                         |dz  }Y d }~nd }~ww xY w|k  rx)Nr   z[FLAKY] z failed on attempt ra  z: r]   )	Exception__name__rm   rX  stderrtimesleep)	r=   r>   retry_counterrr  r7  r5  objr6  s	        r?   wrapperz,is_flaky.<locals>.decorator.<locals>.wrapper  s    K,
%/// ''' ! %";#>#,,"A B--8M<.3%Q  #CJJ/(4

#451$K% ,s    	B AA;;B )
r}   isclasslist__dict__rL   callablerj  setattr	functoolswraps)rC  	attr_name
attr_valuerD  r   r7  r5  r6  s   `   r?   r   zis_flaky.<locals>.decorator  s    ??3)-cll.@.@.B)C C%	:J'I,@,@,HCIj,ABC J 
		( 
	(" rA   r   )r5  r6  r7  r   s   ```@r?   is_flakyrN    s    < rA   c                 L   |)t        t        j                  j                  dd            }d}t	        j
                  |      }|j                  d      }|j                  d      }|j                  ||       |j                  ||||f      }|j                          	 |j                  |      }	|j                          |j                  |       	d   | j                  |	d           yy# t        $ r+}
|j                          | j                  |
       Y d}
~
]d}
~
ww xY w)	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   rf  )targetr=   error)r  r`   ra   rb   multiprocessingget_contextQueueJoinableQueueputProcessstart	task_doner<  	terminatefailrn   )r   target_funcinputsrg  start_methohdctxinput_queueoutput_queueprocessresultses              r?   run_test_in_subprocessrg  3  s    bjjnn%5s;<M

%
%m
4C))A,K$$Q'L OOFGO,kkKw3WkXGMMO""7"3  LLL!w#''*+- $  qs   "C/ /	D#8!DD#c                   (    e Zd ZdZd Zd Zd Zd Zy)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                     || _         t               | _        t        j                  | j                        | _        d| _        y )Nr[   )loggerr   r  loggingStreamHandlershout)selfrk  s     r?   __init__zCaptureLogger.__init__s  s/    *''0rA   c                 P    | j                   j                  | j                         | S rW  )rk  
addHandlerrn  rp  s    r?   	__enter__zCaptureLogger.__enter__y  s    tww'rA   c                     | j                   j                  | j                         | j                  j	                         | _        y rW  )rk  removeHandlerrn  r  getvaluero  )rp  excs     r?   __exit__zCaptureLogger.__exit__}  s,    !!$''*77##%rA   c                 "    d| j                    dS )Nz
captured: rZ   )ro  rt  s    r?   __repr__zCaptureLogger.__repr__  s    DHH:R((rA   N)r=  
__module____qualname____doc__rq  ru  rz  r|  r   rA   r?   ri  ri  ^  s    (&)rA   ri  c                  F    ddl m}  t        j                  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_utilsr  rk  warning)_enable_full_determinisms    r?   r  r    s%    
 Q
NN	n $%%rA   c                  F    ddl m}  t        j                  d        |        S )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.)r  r  rk  r  )_disable_full_determinisms    r?   r  r    s"    R
NN	n %&&rA   c                 .   t               sydd l} |j                  |       } 	  |j                  d|j                        j                  |       } |j                  ||      }y# t        $ r'}| j                  dk(  rt        d|       Y d }~yd }~ww xY w)NFr   r  r  r   Tr0   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#   r7   devicezerosfloat16rh   mulr<  typer6   r  r7   r  r   rf  s        r?   r   r         U\\&!FEKKemm477?EIIaO ;;&  ^  _`  ^a  b     A A$ $	B-BBc                 .   t               sydd l} |j                  |       } 	  |j                  d|j                        j                  |       } |j                  ||      }y# t        $ r'}| j                  dk(  rt        d|       Y d }~yd }~ww xY w)NFr   r  r  Tr0   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#   r7   r  r  float64rh   r  r<  r  r6   r  s        r?   r   r     r  r  )r0   r)   r1   r2   r   c                       yNr   r   r   rA   r?   r   r         rA   c                       yr  r   r   rA   r?   r   r     r  rA   reset_peak_memory_statsmax_memory_allocatedsynchronizer  dispatch_tablec                 T    | |vr |d   |i |S ||    }t        |      s|S  ||i |S )Nr   )rH  )r  r  r=   r>   fns        r?   _device_agnostic_dispatchr    sI    ^#(~i($9&99		B B<	tvrA   seedc                 J    ddl m} t        j                  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.)r  r  rk  r  )r  r  _backend_manual_seeds      r?   r  r    s&    H
NN	_  --rA   c                 H    ddl m} t        j                  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.)r  r  rk  r  )r  _backend_synchronizes     r?   r  r    $    H
NN	_  ''rA   c                 H    ddl m} t        j                  d        ||       S )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.)r  r  rk  r  )r  _backend_empty_caches     r?   r  r  '  r  rA   c                 H    ddl m} t        j                  d        ||       S )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.)r  r  rk  r  )r  _backend_device_counts     r?   r  r  1  s$    J
NN	_ !((rA   c                 H    ddl m} t        j                  d        ||       S )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.)r  r  rk  r  )r   _backend_reset_peak_memory_statss     r?   r  r  ;  s$    `
NN	_ ,F33rA   c                 H    ddl m} t        j                  d        ||       S )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.)r  r  rk  r  )r  #_backend_reset_max_memory_allocateds     r?   r  r  E  s$    f
NN	_ /v66rA   c                 H    ddl m} t        j                  d        ||       S )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.)r  r  rk  r  )r  _backend_max_memory_allocateds     r?   r  r  O  s$    Z
NN	_ )00rA   c                 H    ddl m} t        j                  d        ||       S )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.)r  r   rk  r  )r  _backend_supports_trainings     r?   r   r   [  s$    T
NN	_ &f--rA   device_fn_dictattribute_namec                     	 t        t        |      }|| t        <   y # t        $ r%}d| vrt        d| dt         d      |Y d }~y d }~ww xY w)Nr   `z` not found in 'z)' and no default fallback function found.)getattrdevice_spec_moduler   AttributeErrordevice_spec_path)r  r  spec_fnrf  s       r?   update_mapping_from_specr  h  sb    		0.AG+2N<( 	.$''78H7IIrs /	s    	A
AA
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                      t         st        r/ddl} | j                  j	                         \  }}t        rd|fS d|fS t
        r/ddl} | j                  j	                         d   }d}||z  dz	  }d|fS t        dfS )	z,
    Get environment device properties.
    r   Nrocmr0   architecturel           r)   )IS_CUDA_SYSTEMIS_ROCM_SYSTEMr7   r0   get_device_capabilityIS_XPU_SYSTEMr)   r   )r7   rZ  r   archgen_maskgens         r?   r   r     s    
 ::335qE?"E?"	 yy..0@%h2%s|d##rA   )_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           
         t               }dt        dt        ffd}|dk(  r|t        d      g }| j                         D ]  \  }}t	        |t
        j                  j                  t
        j                  j                  f      s|j                  |        Vt        dt        |      |      D ]=  }	||	|	|z    }
|
s| d|	 d|	t        |
      z   dz
   }|j                   ||             ?  |D ]0  } |j                   || j                  j                   d	             2 |S |d
k(  r| j                         D ]-  \  }}t	        |t               s|j                   ||             / | j                         D ch c]  \  }}t	        |t               s| }}}t#        | |      }t%        | |      }||z   }|rli }t'        | j                               }|D ].  \  }}t)        ||      }||vrg ||<   ||   j                  |       0 |D ]  }|j                   ||              |j                   |t*                     |S t        d|       c c}}w )Ngroup_idr   c                 b    t        |       }t        j                  j                  d| d      S )Ngroup_z.safetensors)r  r`   r   rn   )r  
short_hashr  s     r?   get_hashed_filenamez<_get_expected_safetensors_files.<locals>.get_hashed_filename  s,    ,X6J77<< 4zl,6WXXrA   block_levelzCnum_blocks_per_group must be provided for 'block_level' offloading.r   r   r   _unmatched_group
leaf_levelzUnsupported offload_type: )rN   re   r6   named_childrenrM   r7   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  smmodules_with_group_offloading
parametersbuffersall_orphansparent_to_tensorsmodule_dicttensor_namer   parent_names    `                    r?   _get_expected_safetensors_filesr    s    	Y# 	Y# 	Y =(#+ !fgg !##)#8#8#: 
Fi!)ehh.A.A588CVCV-WX%,,V4q#i.2FG FA&/A8L4L&MO* "&q1Q_1E-E-I,JKH"&&':8'DEF
F , h""#6&:J:J:S:S9TTd7e#fghF A \)#)#7#7#9 Bii)HI"&&':4'@AB &,%9%9%;-!rz"Nm?n-) - LFTqrJEfNklG$w.K$&!"6#7#7#9:&1 GNK"D[R]"^K"*;;9;)+6%k299+F	G $5 IK"&&':;'GHI 23FGH
  9,HII--s   IIc                    t         j                  j                  |      syt        | |||      }t	        t        j
                  t         j                  j                  |d                  }||z
  }||z
  }| xr | }|||fS )N)FNNz*.safetensors)r`   r   isdirr  rN   globrn   )	r  r  r  r  r  actual_filesmissing_filesextra_files
is_corrects	            r?    _check_safetensors_serializationr    s     ww}}12$8(,8L
 499RWW\\2F%XYZ&5"^3&&:{?
;55rA   c                   h    e Zd ZdefdZededefd       Zededede	fd       Z
d
dedefdZd Zy	)Expectationsr   c                 4    | j                  t                     S )zX
        Find best matching expectation based on environment device properties.
        )find_expectationr   rt  s    r?   get_expectationzExpectations.get_expectation  s     $$%:%<==rA   rR   c                 &    t        d | D              S )Nc              3   $   K   | ]  }|d u  
 y wrW  r   )r  ps     r?   r  z*Expectations.is_default.<locals>.<genexpr>%  s     *19*s   )allrR   s    r?   
is_defaultzExpectations.is_default#  s    *c***rA   otherc                     | \  }}|\  }}d}||k(  r|dz  }n|dv r	|dv r|dz  }||k(  r||dz  }t         j                  |      r|dz  }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  )r0   r     r  r   )r  r  r  )rR   r  device_typerZ  other_device_typeother_majorscores          r?   r  zExpectations.score'  s      #e+0(	K++VOE,,1BFV1VUNEKK$;TME""5)SLE5zrA   c                     t        | j                  j                         fd      \  }}t        j	                  |      dk(  rt        d       |S )zU
        Find best matching expectation based on provided device properties.
        c                 6    t         j                  | d         S r  )r  r  )r  rR   s    r?   r   z/Expectations.find_expectation.<locals>.<lambda>F  s    LDVDVWZ\]^_\`Da rA   r  r   z"No matching expectation found for )r:   r   rL   r  r  r6   )rp  rR   
result_keyresults    `  r?   r
  zExpectations.find_expectationB  sO      #499??#4:abVc:.!3A#GHHrA   c                     | j                    S rW  )r   rt  s    r?   r|  zExpectations.__repr__M  s    ))rA   N)NN)r=  r}  r~  r	   r  staticmethodDevicePropertiesboolr  r  r  r
  r|  r   rA   r?   r  r    su    > > +( +T + + # ,<   4	$4 	 	rA   r  )NNztest_corrections.txtexpected_slicerW  )F)rC   NN)NT)   NNr  )rJ  r  r  importlib.metadatar}   r  rl  rT  r`   r   r  r  rX  r  r?  r   urllib.parser  collectionsr   
contextlibr   r   r   pathlibr   typingr   r	   r
   r   r   r   r   r   r   r  rD   	PIL.Imager|  PIL.ImageOpsrk  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(   r7   hipr  r0   r  r  r  Randomr   r=  rk  r  r  r  r  _required_peft_version_required_transformers_versionr  r  getenvr,   ra   backendimport_moduler   ModuleNotFoundErrorrf  r   r  RuntimeErrorinfor   r)   __version__is_torch_higher_equal_than_1_12r  backendsmps_backend_registeredr2   r  r3   r@   rI   rT   rz   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-  r4  r:  r@  rG  rM  rS  rU  r]  re   rp  rr  r!  rw  r}  r  r  r  r  r  r  r  r  r  r  r4  r   rN  rg  ri  r  r  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  r  r  r  r  r  r  r  r   r  r  is_filer6   indeximport_namer  DEVICE_NAMEdevice_namer  r  r   	lru_cacher   DevicePropertiesUserDictdiffusers.hooks._commonr   diffusers.hooks.group_offloadingr  r  r  r  r  r  Moduler  r  r  r   rA   r?   <module>rS     s
        	   	  	  
       %    X X X       0     *   ]]&&d2N]]''t3NEMM5$7tCMNNMV]]_
	H	 b +, GMM)$$,,V45BB2GMM%2  ";!< "GMM)$$,,^<=JJBGMM&B  *L.L YRYY/45  2::-**56	'	''0A "**,zz"9:	\*A
 	/~>?::""$!LYY##% L L*7'--GMM%++,99+
W]]6"+#' +%,U^^U%C"%;@R@R@_@_@a5htL=2 #)O4.9# 9  &j%@(F (F Q KQWY			h(:c
[Y\]i]ZUeaa"$							iU3

?+ # RTR\R\ 4 HSM QU eC01 ciioo >CII 3 ciioo.  PS   0 0f/ /($rzz"2 s VY "2::   *&~)D,3 ,x ,\deh\i ,`(.V$) $)N&',. )-d4PUbf g 

&&yy$$yy$$ 

''yy%% 

&&yy$$  yy$$$$ 

22uyy";TB'# 

55uyy";TB*& 

//uyy"8$?$  

&&uyy-6c 4X;N . .3 .( (( () )4C 47s 71 1.c . 
c8m1D 
VY 
 $rzz1::&BC$%--/bcsbtuvv	t*+J-=-C-CE-JKK 5Y44[A	S,88K #bjj0\[5PST`Saa}  J  ~K  KN  OC``CS/!" 	!!46FG !46FG !57HI !:<OP !@B^_ !CEde !=?XY sDy)5d+;;<  $/ $ $0 '(8#(=>'G  /3	BB!B B 'sm	B
 
SBP /3	66!6 6 'sm	6
 
6(2+ 2A. # 	%=gY G778c; 	  	deqdrs	h(  	tXYiXjklrss	t  	S !QRR	SsT   c c, d *d c)c$$c),d1c==dd
ddd,