
    bi72                         d dl Z d dlmZ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 ddlmZ ddlmZmZ erdd	lmZ  G d
 de      Zy)    N)TYPE_CHECKINGAnyDictListOptionalTupleUnion   )register_to_config)HookRegistryLayerSkipConfig)_apply_layer_skip_hook   )BaseGuidancerescale_noise_cfg)
BlockStatec                       e Zd ZdZg dZe	 	 	 	 	 	 	 	 	 	 ddededededeee	e
e	   f      d	eee
e   eeef   f   d
edededef fd       Zdej$                  j&                  ddfdZdej$                  j&                  dd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j0                  deej0                     deej0                     dej0                  fdZedefd       Zede	fd       ZdefdZdefdZ xZS )"SkipLayerGuidancea  
    Skip Layer Guidance (SLG): https://github.com/Stability-AI/sd3.5

    Spatio-Temporal Guidance (STG): https://huggingface.co/papers/2411.18664

    SLG was introduced by StabilityAI for improving structure and anotomy coherence in generated images. It works by
    skipping the forward pass of specified transformer blocks during the denoising process on an additional conditional
    batch of data, apart from the conditional and unconditional batches already used in CFG
    ([~guiders.classifier_free_guidance.ClassifierFreeGuidance]), and then scaling and shifting the CFG predictions
    based on the difference between conditional without skipping and conditional with skipping predictions.

    The intution behind SLG can be thought of as moving the CFG predicted distribution estimates further away from
    worse versions of the conditional distribution estimates (because skipping layers is equivalent to using a worse
    version of the model for the conditional prediction).

    STG is an improvement and follow-up work combining ideas from SLG, PAG and similar techniques for improving
    generation quality in video diffusion models.

    Additional reading:
    - [Guiding a Diffusion Model with a Bad Version of Itself](https://huggingface.co/papers/2406.02507)

    The values for `skip_layer_guidance_scale`, `skip_layer_guidance_start`, and `skip_layer_guidance_stop` are
    defaulted to the recommendations by StabilityAI for Stable Diffusion 3.5 Medium.

    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.
        skip_layer_guidance_scale (`float`, defaults to `2.8`):
            The scale parameter for skip layer guidance. Anatomy and structure coherence may improve with higher
            values, but it may also lead to overexposure and saturation.
        skip_layer_guidance_start (`float`, defaults to `0.01`):
            The fraction of the total number of denoising steps after which skip layer guidance starts.
        skip_layer_guidance_stop (`float`, defaults to `0.2`):
            The fraction of the total number of denoising steps after which skip layer guidance stops.
        skip_layer_guidance_layers (`int` or `List[int]`, *optional*):
            The layer indices to apply skip layer guidance to. Can be a single integer or a list of integers. If not
            provided, `skip_layer_config` must be provided. The recommended values are `[7, 8, 9]` for Stable Diffusion
            3.5 Medium.
        skip_layer_config (`LayerSkipConfig` or `List[LayerSkipConfig]`, *optional*):
            The configuration for the skip layer guidance. Can be a single `LayerSkipConfig` or a list of
            `LayerSkipConfig`. If not provided, `skip_layer_guidance_layers` must be provided.
        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.01`):
            The fraction of the total number of denoising steps after which guidance starts.
        stop (`float`, defaults to `0.2`):
            The fraction of the total number of denoising steps after which guidance stops.
    	pred_condpred_uncondpred_cond_skipNguidance_scaleskip_layer_guidance_scaleskip_layer_guidance_startskip_layer_guidance_stopskip_layer_guidance_layersskip_layer_configguidance_rescaleuse_original_formulationstartstopc                    t         |   |	|
       || _        || _        || _        || _        || _        || _        d|cxk  rdk  sn t        d| d      ||cxk  rdk  sn t        d| d      ||t        d      ||t        d      |Ut        |t              r|g}t        |t              st        dt        |       d      |D cg c]  }t        |d	
       }}t        |t              rt        j                  |      }t        |t              r|g}t        |t              st        dt        |       d      t        t!        t#        |      d       t              r"|D cg c]  }t        j                  |       }}|| _        t'        t)        | j$                              D cg c]  }d| 	 c}| _        y c c}w c c}w c c}w )N              ?zHExpected `skip_layer_guidance_start` to be between 0.0 and 1.0, but got .zGExpected `skip_layer_guidance_stop` to be between 0.0 and 1.0, but got zjEither `skip_layer_guidance_layers` or `skip_layer_config` must be provided to enable Skip Layer Guidance.zPOnly one of `skip_layer_guidance_layers` or `skip_layer_config` can be provided.zNExpected `skip_layer_guidance_layers` to be an int or a list of ints, but got auto)fqnz[Expected `skip_layer_config` to be a LayerSkipConfig or a list of LayerSkipConfig, but got SkipLayerGuidance_)super__init__r   r   r   r   r   r    
ValueError
isinstanceintlisttyper   dict	from_dictnextiterr   rangelen_skip_layer_hook_names)selfr   r   r   r   r   r   r   r    r!   r"   layerconfigi	__class__s                 `/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/guiders/skip_layer_guidance.pyr+   zSkipLayerGuidance.__init__Z   s:    	%,)B&)B&(@% 0(@%0636Z[tZuuvw  *-ELLYZrYsstu  &-2C2K|  &16G6Sopp%14c:.H-I*8$? dei  kE  fF  eG  GH  I  Rl lF!C l l'. / 9 9:K L'9!2 3+T2mnr  tE  oF  nG  GH  I  T"34d;TBQb cv!:!:6!B c c!2INsSWSiSiOjIk&lA);A3'?&l#! !m !d 'ms   G
0G5Gdenoiserreturnc                     | xj                   dz  c_         | j                         rT| j                  rG| j                   dkD  r7t        | j                  | j
                        D ]  \  }}t        |||        y y y y )Nr   )name)_count_prepared_is_slg_enabledis_conditionalzipr7   r   r   )r8   r>   rA   r:   s       r=   prepare_modelsz SkipLayerGuidance.prepare_models   su    !!d&9&9d>R>RUV>V #D$?$?AWAW X Df&xdCD ?W&9!    c                     | j                         rW| j                  rJ| j                  dkD  r:t        j                  |      }| j
                  D ]  }|j                  |d        y y y y )Nr   T)recurse)rC   rD   rB   r   check_if_exists_or_initializer7   remove_hook)r8   r>   registry	hook_names       r=   cleanup_modelsz SkipLayerGuidance.cleanup_models   sh    !d&9&9d>R>RUV>V#AA(KH!88 >	$$Y$=> ?W&9!rG   datar   input_fieldsc                 D   || j                   }| j                  dk(  rdg}dg}n4| j                  dk(  rddg}| j                         rddgnddg}ng d}g d}g }t        | j                        D ]-  }| j	                  ||||   ||         }|j                  |       / |S )	Nr   r   r   r
   r   r   )r   r   r   r   )_input_fieldsnum_conditions_is_cfg_enabledr5   _prepare_batchappend)r8   rO   rP   tuple_indicesinput_predictionsdata_batchesr;   
data_batchs           r=   prepare_inputsz SkipLayerGuidance.prepare_inputs   s     --L!#CM!,  A%FM040D0D0Fm,[ZjLk  &M Nt**+ 	,A,,\4qAQSdefSghJ
+	, rG   r   r   r   c                    d }| j                         s| j                         s|}n| j                         s(||z
  }| j                  r|n|}|| j                  |z  z   }nt| j                         s(||z
  }| j                  r|n|}|| j                  |z  z   }n<||z
  }||z
  }| j                  r|n|}|| j                  |z  z   | j                  |z  z   }| j
                  dkD  rt        ||| j
                        }|i fS )Nr$   )rT   rC   r    r   r   r   r   )r8   r   r   r   predshift
shift_skips          r=   forwardzSkipLayerGuidance.forward   s    ##%d.B.B.DD%%'.E $ = =9>D$885@@D%%'+E $ = =9;D$--55D+E"^3J $ = =9;D$--558V8VYc8ccD  3&$T9d6K6KLDRxrG   c                 B    | j                   dk(  xs | j                   dk(  S )Nr      )rB   )r8   s    r=   rD   z SkipLayerGuidance.is_conditional   s#    ##q(ED,@,@A,EErG   c                 ^    d}| j                         r|dz  }| j                         r|dz  }|S )Nr   )rT   rC   )r8   rS   s     r=   rS   z SkipLayerGuidance.num_conditions   s9    !aN!aNrG   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 )NFTr$   r%   )
_enabled_num_inference_stepsr.   _start_stop_stepr    mathiscloser   )r8   is_within_rangeskip_start_stepskip_stop_stepis_closes        r=   rT   z!SkipLayerGuidance._is_cfg_enabled   s    }}$$0!$++0I0I"IJO d.G.G!GHN-LnLO((||D$7$7=H||D$7$7=H/x</rG   c                 B   | j                   syd}| j                  ^t        | j                  | j                  z        }t        | j                  | j                  z        }|| j
                  cxk  xr |k  nc }t        j                  | j                  d      }|xr | S )NFTr$   )	re   rf   r.   r   r   ri   rj   rk   r   )r8   rl   rm   rn   is_zeros        r=   rC   z!SkipLayerGuidance._is_slg_enabled   s    }}$$0!$"@"@4C\C\"\]O !>!>AZAZ!Z[N-

K^KO,,t==sC.w;.rG   )
g      @gffffff@g{Gz?g?NNr$   Fr$   r%   )N)NN) __name__
__module____qualname____doc___input_predictionsr   floatr   r	   r.   r   r   r   strr   boolr+   torchnnModulerF   rN   r   r[   Tensorr`   propertyrD   rS   rT   rC   __classcell__)r<   s   @r=   r   r      s   7r H !$+.+/*-FJ[_"%).=m=m $)=m $)	=m
 #(=m %-U3S	>-B$C=m !$2GcSVh!WX=m  =m #'=m =m =m =m~Duxx D4 D>uxx >4 > dh 08c5eTWY\T\oI]C^>^9_0`	l	4 /315	<< ell+ !.	
 
: F F F   0 0$/ /rG   r   )rj   typingr   r   r   r   r   r   r	   rz   configuration_utilsr   hooksr   r   hooks.layer_skipr   guider_utilsr   r   "modular_pipelines.modular_pipeliner   r    rG   r=   <module>r      s8     I I I  4 1 5 9 ?h/ h/rG   