
    +h*                         S SK r S SKJrJrJrJrJrJr  S SKrSSK	J
r
  SSKJrJr  \(       a  SSKJr   " S S	\5      r " S
 S5      r    SS\R$                  S\R$                  S\S\\   S\S\S\4S jjrg)    N)TYPE_CHECKINGDictListOptionalTupleUnion   )register_to_config   )BaseGuidancerescale_noise_cfg)
BlockStatec                   \  ^  \ rS rSrSrSS/r\        SS\S\\   S\S\S	\S
\	S\S\4U 4S jjj5       r
 SSSS\\\\\\\\4   4   4      S\S   4S jjrSS\R$                  S\\R$                     S\R$                  4S jjr\S\	4S j5       r\S\4S j5       rS\	4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
    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_uncondguidance_scale$adaptive_projected_guidance_momentum#adaptive_projected_guidance_rescaleetaguidance_rescaleuse_original_formulationstartstopc	                 z   > [         T	U ]  Xx5        Xl        X l        X0l        X@l        XPl        X`l        S U l        g N)	super__init__r   r   r   r   r   r   momentum_buffer)
selfr   r   r   r   r   r   r   r   	__class__s
            g/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/guiders/adaptive_projected_guidance.pyr   "AdaptiveProjectedGuidance.__init__9   s=     	%,4X13V0 0(@%#    datar   input_fieldsreturnc                 b   Uc  U R                   nU R                  S:X  a'  U R                  b  [        U R                  5      U l        U R
                  S:X  a  S/OSS/n/ n[        U R
                  5       H6  nU R                  X!X5   U R                  U   5      nUR                  U5        M8     U$ )Nr   r   )
_input_fields_stepr   MomentumBufferr    num_conditionsrange_prepare_batch_input_predictionsappend)r!   r&   r'   tuple_indicesdata_batchesi
data_batchs          r#   prepare_inputs(AdaptiveProjectedGuidance.prepare_inputsO   s     --L::?88D'5d6_6_'`$#22a7aVt**+A,,\AQSWSjSjklSmnJ
+ , r%   c           	         S nU R                  5       (       d  UnOC[        UUU R                  U R                  U R                  U R
                  U R                  5      nU R                  S:  a  [        X1U R                  5      nU0 4$ )N        )	_is_apg_enablednormalized_guidancer   r    r   r   r   r   r   )r!   r   r   preds       r#   forward!AdaptiveProjectedGuidance.forward_   s    ##%%D&##$$88--D   3&$Td6K6KLDRxr%   c                      U R                   S:H  $ Nr   )_count_prepared)r!   s    r#   is_conditional(AdaptiveProjectedGuidance.is_conditionalt   s    ##q((r%   c                 >    SnU R                  5       (       a  US-  nU$ r@   )r:   )r!   r-   s     r#   r-   (AdaptiveProjectedGuidance.num_conditionsx   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(       + $ )NFTr9         ?)
_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   )g      @Ng      .@rG   r9   Fr9   rG   r   )__name__
__module____qualname____firstlineno____doc__r0   r
   floatr   boolr   r   strr   r   r   r6   torchTensorr=   propertyrB   rJ   r-   r:   __static_attributes____classcell__)r"   s   @r#   r   r      sU   4 &}5 !$@D59"%).$$ /7uo$ .3	$
 $  $ #'$ $ $ $, dh 08c5eTWY\T\oI]C^>^9_0`	l	  HU\\<R ^c^j^j * ) ) )   0 0 0r%   r   c                   D    \ rS rSrS\4S jrS\R                  4S jrSr	g)r,      momentumc                     Xl         SU l        g )Nr   rc   running_average)r!   rc   s     r#   r   MomentumBuffer.__init__   s      r%   update_valuec                 H    U R                   U R                  -  nX-   U l        g r   re   )r!   rh   new_averages      r#   updateMomentumBuffer.update   s!    mmd&:&::+9r%   re   N)
rT   rU   rV   rW   rY   r   r\   r]   rk   r_    r%   r#   r,   r,      s    ! !:5<< :r%   r,   r   r   r   r    r   norm_thresholdr   c                    X-
  n[        S[        UR                  5      5       Vs/ s H  o* PM     n	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                  5       U R                  5       p[
        R                  R                  R                  XS9nX-  R                  U	SS9U-  nX-
  nUR                  U5      UR                  U5      nnUUU-  -   nU(       a  U OUnUUU-  -   nU$ s  snf )Nr   r   r	   T)pdimkeepdim)rq   )rq   rr   )r.   lenshaperk   rf   r\   	ones_likenormminimumdoublenn
functional	normalizesumtype_as)r   r   r   r    r   rn   r   diffr4   rq   ones	diff_normscale_factorv0v1v0_parallelv0_orthogonaldiff_paralleldiff_orthogonalnormalized_updater<   s                        r#   r;   r;      s<    "DQDJJ0
10!20C
1"t$..t$IIsDI9	}}TI+EF"[[]I,,.				&	&r	&	3B7--C-6;K$M%0%8%8%>@U@UVZ@[?M'#*==09kD.#444DK- 2s   D<)NrG   r9   F)rM   typingr   r   r   r   r   r   r\   configuration_utilsr
   guider_utilsr   r   "modular_pipelines.modular_pipeliner   r   r,   r]   rY   rZ   r;   rm   r%   r#   <module>r      s     D D  4 9 ?s0 s0l: : 15%* ||     n-	 
 
    # r%   