
    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	 dd
ej"                  dej"                  dededej"                  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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 ) TangentialClassifierFreeGuidancea  
    Tangential Classifier Free Guidance (TCFG): https://huggingface.co/papers/2503.18137

    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.
        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guidance_rescaleuse_original_formulationstartstopc                 P    t         |   ||       || _        || _        || _        y N)super__init__r   r   r   )selfr   r   r   r   r   	__class__s         p/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/guiders/tangential_classifier_free_guidance.pyr   z)TangentialClassifierFreeGuidance.__init__5   s,     	%, 0(@%    datar   input_fieldsreturnc                     || 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num_conditionsrange_prepare_batch_input_predictionsappend)r   r    r!   tuple_indicesdata_batchesi
data_batchs          r   prepare_inputsz/TangentialClassifierFreeGuidance.prepare_inputsD   s     --L#22a7aVt**+ 	,A,,\4qAQSWSjSjklSmnJ
+	, r   c                     d }| j                         s|}n"t        ||| j                  | j                        }| j                  dkD  rt        ||| j                        }|i fS )N        )_is_tcfg_enablednormalized_guidancer   r   r   r   )r   r   r   preds       r   forwardz(TangentialClassifierFreeGuidance.forwardQ   s`    $$&D&y+t?R?RTXTqTqrD  3&$T9d6K6KLDRxr   c                      | j                   dk(  S Nr   )_num_outputs_prepared)r   s    r   is_conditionalz/TangentialClassifierFreeGuidance.is_conditional^   s    ))Q..r   c                 4    d}| j                         r|dz  }|S r6   )r1   )r   r%   s     r   r%   z/TangentialClassifierFreeGuidance.num_conditionsb   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 )NFTr0         ?)
_enabled_num_inference_stepsint_start_stop_stepr   mathiscloser   )r   is_within_rangeskip_start_stepskip_stop_stepis_closes        r   r1   z1TangentialClassifierFreeGuidance._is_tcfg_enabledi   s    }}$$0!$++0I0I"IJO d.G.G!GHN-LnLO((||D$7$7=H||D$7$7=H/x</r   )g      @r0   Fr0   r;   r   )__name__
__module____qualname____doc__r(   r
   floatboolr   r   r   strr   r   r   r.   torchTensorr4   propertyr8   r>   r%   r1   __classcell__)r   s   @r   r   r      s,   , &}5 !$"%).AA  A #'	A
 A A A dh 08c5eTWY\T\oI]C^>^9_0`	l	 HU\\<R ^c^j^j  / / /   0$ 0r   r   r   r   r   r   r"   c                 \   | j                   }t        j                  | |gd      j                         }|j	                  d      }t        j
                  j                  |d      \  }}}|j                         }	d|	d d df<   |j                  |j                  d      dd      j                         }
t        j                  |
|j                  dd            }t        j                  ||	      }|j                  |j                        j                  |      }|r| n|}| |z
  }|||z  z   }|S )	Nr   )dimr	   F)full_matricesr   )dtyperO   stackrL   flattenlinalgsvdclonereshapesizematmul	transposeshapeto)r   r   r   r   
cond_dtypepredsUSVhVh_modifieduncond_flatx_Vhx_Vh_Vr3   shifts                  r   r2   r2   |   s
    JKKK0a8>>@EMM!E||U;HAq"((*KK1%%k&6&6q&91bAGGIK<<R\\"b%9:D\\$,F..!2!2366zBK09kD#E.5((DKr   )F)rB   typingr   r   r   r   r   r   rO   configuration_utilsr
   guider_utilsr   r   "modular_pipelines.modular_pipeliner   r   rP   rL   rM   r2    r   r   <module>rs      sp     D D  4 9 ?]0| ]0B qv||*/,,HMim
\\r   