
    bi*                         d dl Z d dlmZmZmZmZmZmZ d dlZddl	m
Z
 ddlmZmZ erddlmZ  G d d	e      Z G d
 d      Z	 	 	 	 ddej$                  dej$                  dedee   dededefdZy)    N)TYPE_CHECKINGDictListOptionalTupleUnion   )register_to_config   )BaseGuidancerescale_noise_cfg)
BlockStatec                   @    e Zd ZdZddgZe	 	 	 	 	 	 	 	 ddedee   dededed	ed
edef fd       Z		 ddddee
eeeeeef   f   f      ded   fdZddej"                  deej"                     dej"                  fdZedefd       Zedefd       ZdefdZ xZS )AdaptiveProjectedGuidancea  
    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	                     t         	|   ||       || _        || _        || _        || _        || _        || _        d | _        y N)	super__init__r   r   r   r   r   r   momentum_buffer)
selfr   r   r   r   r   r   r   r   	__class__s
            h/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/guiders/adaptive_projected_guidance.pyr   z"AdaptiveProjectedGuidance.__init__9   sK     	%,4X13V0 0(@%#    datar   input_fieldsreturnc                 Z   || j                   }| j                  dk(  r&| j                  t        | j                        | _        | j
                  dk(  rdgnddg}g }t        | j
                        D ]7  }| j                  ||||   | j                  |         }|j                  |       9 |S )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_inputsz(AdaptiveProjectedGuidance.prepare_inputsO   s     --L::?88D'5d6_6_'`$#22a7aVt**+ 	,A,,\4qAQSWSjSjklSmnJ
+	, r#   c           	         d }| j                         s|}nCt        ||| j                  | j                  | j                  | j
                  | j                        }| j                  dkD  rt        ||| j                        }|i fS )N        )	_is_apg_enablednormalized_guidancer   r   r   r   r   r   r   )r    r   r   preds       r"   forwardz!AdaptiveProjectedGuidance.forward_   s    ##%D&##$$88--D   3&$T9d6K6KLDRxr#   c                      | j                   dk(  S Nr   )_count_prepared)r    s    r"   is_conditionalz(AdaptiveProjectedGuidance.is_conditionalt   s    ##q((r#   c                 4    d}| j                         r|dz  }|S r<   )r7   )r    r+   s     r"   r+   z(AdaptiveProjectedGuidance.num_conditionsx   s#    !aNr#   c                    | j                   syd}| j                  ^t        | j                  | j                  z        }t        | j                  | j                  z        }|| j
                  cxk  xr |k  nc }d}| j                  r!t        j                  | j                  d      }n t        j                  | j                  d      }|xr | S )NFTr6         ?)
_enabled_num_inference_stepsint_start_stopr)   r   mathiscloser   )r    is_within_rangeskip_start_stepskip_stop_stepis_closes        r"   r7   z)AdaptiveProjectedGuidance._is_apg_enabled   s    }}$$0!$++0I0I"IJO d.G.G!GHN-LnLO((||D$7$7=H||D$7$7=H/x</r#   )g      @Ng      .@rA   r6   Fr6   rA   r   )__name__
__module____qualname____doc__r.   r
   floatr   boolr   r   strr   r   r   r4   torchTensorr:   propertyr>   rD   r+   r7   __classcell__)r!   s   @r"   r   r      sP   4 &}5 !$@D59"%).$$ /7uo$ .3	$
 $  $ #'$ $ $ $, dh 08c5eTWY\T\oI]C^>^9_0`	l	  HU\\<R ^c^j^j * ) ) )   0 0r#   r   c                   8    e Zd ZdefdZdej                  fdZy)r*   momentumc                      || _         d| _        y )Nr   rY   running_average)r    rY   s     r"   r   zMomentumBuffer.__init__   s      r#   update_valuec                 J    | j                   | j                  z  }||z   | _        y r   r[   )r    r]   new_averages      r"   updatezMomentumBuffer.update   s#    mmd&:&::+k9r#   N)rM   rN   rO   rQ   r   rT   rU   r`    r#   r"   r*   r*      s    ! !:5<< :r#   r*   r   r   r   r   r   norm_thresholdr   c                    | |z
  }t        dt        |j                              D cg c]  }|  }	}||j                  |       |j                  }|dkD  rGt        j                  |      }
|j                  d|	d      }t        j                  |
||z        }||z  }|j                         | j                         }}t
        j                  j                  j                  ||	      }||z  j                  |	d      |z  }||z
  }|j                  |      |j                  |      }}|||z  z   }|r| n|}|||z  z   }|S c c}w )Nr   r   r	   T)pdimkeepdim)re   )re   rf   )r,   lenshaper`   r\   rT   	ones_likenormminimumdoublenn
functional	normalizesumtype_as)r   r   r   r   r   rb   r   diffr2   re   ones	diff_normscale_factorv0v1v0_parallelv0_orthogonaldiff_paralleldiff_orthogonalnormalized_updater9   s                        r"   r8   r8      sI    {"DQDJJ0
1!A2
1C
1"t$..t$IIsDI9	}}T>I+EFl"[[]I,,.B				&	&rs	&	3B7--C-6;K$M%0%8%8%>@U@UVZ@[?M'#*==09kD.#444DK- 2s   
E)NrA   r6   F)rG   typingr   r   r   r   r   r   rT   configuration_utilsr
   guider_utilsr   r   "modular_pipelines.modular_pipeliner   r   r*   rU   rQ   rR   r8   ra   r#   r"   <module>r      s     D D  4 9 ?s0 s0l: : 15%* ||     n-	 
 
    # r#   