
    
3jc)                        S SK Jr  S SKrS SKJr  S SKrSSKJr  SSKJ	r	J
r
Jr  \(       a  SSKJr   " S	 S
\	5      r " S S5      r     S               SS jjrg)    )annotationsN)TYPE_CHECKING   )register_to_config   )BaseGuidanceGuiderOutputrescale_noise_cfg)
BlockStatec                     ^  \ rS rSrSrSS/r\          S                   SU 4S jjj5       rSS jr      SS jr	SSS jjr
\SS	 j5       r\SS
 j5       rSS jrSrU =r$ )AdaptiveProjectedGuidance   a  
Adaptive Projected Guidance (APG): https://huggingface.co/papers/2410.02416

Args:
    guidance_scale (`float`, defaults to `7.5`):
        The scale parameter for classifier-free guidance. Higher values result in stronger conditioning on the text
        prompt, while lower values allow for more freedom in generation. Higher values may lead to saturation and
        deterioration of image quality.
    adaptive_projected_guidance_momentum (`float`, defaults to `None`):
        The momentum parameter for the adaptive projected guidance. Disabled if set to `None`.
    adaptive_projected_guidance_rescale (`float`, defaults to `15.0`):
        The rescale factor applied to the noise predictions. This is used to improve image quality and fix
    adaptive_projected_guidance_norm_dim (`int` or `tuple[int]`, *optional*):
        Dimension(s) over which to compute the APG norm and projection. If omitted, all non-batch dimensions are
        used, preserving the original behavior.
    guidance_rescale (`float`, defaults to `0.0`):
        The rescale factor applied to the noise predictions. This is used to improve image quality and fix
        overexposure. Based on Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
        Flawed](https://huggingface.co/papers/2305.08891).
    use_original_formulation (`bool`, defaults to `False`):
        Whether to use the original formulation of classifier-free guidance as proposed in the paper. By default,
        we use the diffusers-native implementation that has been in the codebase for a long time. See
        [~guiders.classifier_free_guidance.ClassifierFreeGuidance] for more details.
    start (`float`, defaults to `0.0`):
        The fraction of the total number of denoising steps after which guidance starts.
    stop (`float`, defaults to `1.0`):
        The fraction of the total number of denoising steps after which guidance stops.
	pred_condpred_uncondc                   > [         TU ]  XU
5        Xl        X l        X0l        X@l        XPl        X`l        Xpl        S U l	        g N)
super__init__guidance_scale$adaptive_projected_guidance_momentum#adaptive_projected_guidance_rescale$adaptive_projected_guidance_norm_dimetaguidance_rescaleuse_original_formulationmomentum_buffer)selfr   r   r   r   r   r   r   startstopenabled	__class__s              g/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/guiders/adaptive_projected_guidance.pyr   "AdaptiveProjectedGuidance.__init__>   sE     	g.,4X13V04X1 0(@%#    c                (   U R                   S:X  a'  U R                  b  [        U R                  5      U l        U R                  S:X  a  S/OSS/n/ n[        X R                  5       H(  u  pEU R                  XU5      nUR                  U5        M*     U$ Nr   r   )	_stepr   MomentumBufferr   num_conditionszip_input_predictions_prepare_batchappend)r   datatuple_indicesdata_batches	tuple_idxinput_prediction
data_batchs          r"   prepare_inputs(AdaptiveProjectedGuidance.prepare_inputsW   s    ::?88D'5d6_6_'`$#22a7aV+.}>U>U+V'I,,T>NOJ
+ ,W r$   c                (   U R                   S:X  a'  U R                  b  [        U R                  5      U l        U R                  S:X  a  S/OSS/n/ n[        X0R                  5       H(  u  pVU R                  X!XV5      nUR                  U5        M*     U$ r&   )	r'   r   r(   r   r)   r*   r+   _prepare_batch_from_block_stater-   )r   r.   input_fieldsr/   r0   r1   r2   r3   s           r"   prepare_inputs_from_block_state9AdaptiveProjectedGuidance.prepare_inputs_from_block_stateb   s     ::?88D'5d6_6_'`$#22a7aV+.}>U>U+V'I==lR[nJ
+ ,W r$   c           
     2   S nU R                  5       (       d  UnON[        UUU R                  U R                  U R                  U R
                  U R                  U R                  5      nU R                  S:  a  [        X1U R                  5      n[        X1US9$ )N        )predr   r   )_is_apg_enablednormalized_guidancer   r   r   r   r   r   r   r
   r	   )r   r   r   r=   s       r"   forward!AdaptiveProjectedGuidance.forwardo   s    ##%%D&##$$88--99	D   3&$Td6K6KLDTTr$   c                     U R                   S:H  $ Nr   )_count_prepared)r   s    r"   is_conditional(AdaptiveProjectedGuidance.is_conditional   s    ##q((r$   c                >    SnU R                  5       (       a  US-  nU$ rC   )r>   )r   r)   s     r"   r)   (AdaptiveProjectedGuidance.num_conditions   s&    !!aNr$   c                   U R                   (       d  gSnU R                  bb  [        U R                  U R                  -  5      n[        U R                  U R                  -  5      nX R
                  s=:*  =(       a    U:  Os  nSnU R                  (       a"  [        R                  " U R                  S5      nO![        R                  " U R                  S5      nU=(       a    U(       + $ )NFTr<         ?)
_enabled_num_inference_stepsint_start_stopr'   r   mathiscloser   )r   is_within_rangeskip_start_stepskip_stop_stepis_closes        r"   r>   )AdaptiveProjectedGuidance._is_apg_enabled   s    }}$$0!$++0I0I"IJO d.G.G!GHN-LLnLO((||D$7$7=H||D$7$7=H/x</r$   )r   r   r   r   r   r   r   r   )
g      @Ng      .@NrJ   r<   Fr<   rJ   T)r   floatr   zfloat | Noner   rW   r   int | tuple[int, ...] | Noner   rW   r   rW   r   boolr   rW   r   rW   r    rY   )r.   z,dict[str, tuple[torch.Tensor, torch.Tensor]]returnlist['BlockState'])r.   z'BlockState'r8   z dict[str, str | tuple[str, str]]rZ   r[   r   )r   torch.Tensorr   ztorch.Tensor | NonerZ   r	   )rZ   rY   )rZ   rM   )__name__
__module____qualname____firstlineno____doc__r+   r   r   r4   r9   r@   propertyrE   r)   r>   __static_attributes____classcell__)r!   s   @r"   r   r      s   : &}5 !$=A59MQ"%).$$ /;$ .3	$
 /K$ $  $ #'$ $ $ $ $0	 0P	U, ) )  0 0r$   r   c                  2    \ rS rSrSS jrSS jrS	S jrSrg)
r(      c                    Xl         SU l        g )Nr   momentumrunning_average)r   ri   s     r"   r   MomentumBuffer.__init__   s      r$   c                H    U R                   U R                  -  nX-   U l        g r   rh   )r   update_valuenew_averages      r"   updateMomentumBuffer.update   s!    mmd&:&::+9r$   c           
        [        U R                  [        R                  5      (       Ga  [	        U R                  R
                  5      n[        R                  " 5          U R                  R                  5       R                  5       U R                  R                  5       R                  5       U R                  R                  5       R                  5       U R                  R                  5       R                  5       S.nSSS5        [	        S U 5       5      nU R                  U   n[        UR                  5       R                  5       R                  5       R!                  5       5      n[#        U5      S:  a  USS S-   nSR%                  WR'                  5        VVs/ s H  u  pgU SUS 3PM     snn5      nS	U R(                   S
U SU SU S3	$ SU R(                   SU R                   S3$ ! , (       d  f       N= fs  snnf )zj
Returns a string representation showing momentum, shape, statistics, and a slice of the running_average.
)meanstdminmaxNc              3  N   #    U  H  n[        S [        SU5      5      v   M     g 7f)N   )slicert   ).0dims     r"   	<genexpr>*MomentumBuffer.__repr__.<locals>.<genexpr>   s      !Les%c!Sk":":es   #%   z...z, =z.4fzMomentumBuffer(
  momentum=z
,
  shape=z,
  stats=[z],
  slice=z
)zMomentumBuffer(momentum=z, running_average=))
isinstancerj   torchTensortupleshapeno_gradrr   itemrs   rt   ru   strdetachrW   cpunumpylenjoinitemsri   )	r   r   statsslice_indicessliced_data	slice_strkv	stats_strs	            r"   __repr__MomentumBuffer.__repr__   s    d**ELL99$..445E  00557<<>//335::<//335::<//335::<	 ! "!Le!LLM..}=K K..0668<<>DDFGI9~#%dsOe3			ekkm"LmdaaS!C>m"LMI"mm_ - ' "%; '$+ &	 .dmm_<NtOcOcNddeff9 !" #Ms   B G2 H
2
H rh   N)ri   rW   )rm   r\   )rZ   r   )r]   r^   r_   r`   r   ro   r   rc    r$   r"   r(   r(      s    !:$gr$   r(   c                   X-
  nUc0  [        S[        UR                  5      5       V	s/ s H  o* PM     n
n	O$[        U[        5      (       a  U/n
O[        U5      n
Ub  UR                  U5        UR                  nUS:  aD  [        R                  " U5      nUR                  SU
SS9n[        R                  " XU-  5      nX-  nUR                  R                  S;   a<  UR                  5       R                  5       U R                  5       R                  5       pOUR                  5       U R                  5       p[        R                   R"                  R%                  XS9nX-  R'                  U
SS9U-  nUU-
  nUR)                  UR                  UR*                  S	9nUR)                  UR                  UR*                  S	9nUUU-  -   nU(       a  U OUnUUU-  -   nU$ s  sn	f )
Nr   r   r   T)prz   keepdim>   mpsnpu)rz   )rz   r   )devicedtype)ranger   r   r   rM   listro   rj   r   	ones_likenormminimumr   typer   doublenn
functional	normalizesumtor   )r   r   r   r   r   norm_thresholdr   norm_dimdiffirz   ones	diff_normscale_factorv0v1v0_parallelv0_orthogonaldiff_paralleldiff_orthogonalnormalized_updater=   s                         r"   r?   r?      s    "D C

O454ar45	Hc	"	"j8n"t$..t$IIsDI9	}}TI+EF"{{>)""$immo&<&<&>B	 0 0 2B				&	&r	&	3B7--C-6;K$MNN$++TZZNHM#&&dkk&LO'#*==09kD.#444DK= 6s   G!)NrJ   r<   FN)r   r\   r   r\   r   rW   r   zMomentumBuffer | Noner   rW   r   rW   r   rY   r   rX   )
__future__r   rP   typingr   r   configuration_utilsr   guider_utilsr   r	   r
   "modular_pipelines.modular_pipeliner   r   r(   r?   r   r$   r"   <module>r      s    #     4 G G ?B0 B0J-g -gh .2%*-1*** * +	*
 
* * #* +*r$   