
    +h=                         S SK Jr  S SKJrJrJr  S SKrSSKJrJ	r	  SSK
Jr  SSKJr  SS	KJr  S
SKJrJrJr  \ " S S\5      5       r " S S\\5      rg)    )	dataclass)OptionalTupleUnionN   )ConfigMixinregister_to_config)
BaseOutput)apply_forward_hook   )
ModelMixin   )DecoderOutputDecoderTinyEncoderTinyc                   8    \ rS rSr% Sr\R                  \S'   Srg)AutoencoderTinyOutput   zt
Output of AutoencoderTiny encoding method.

Args:
    latents (`torch.Tensor`): Encoded outputs of the `Encoder`.

latents N)	__name__
__module____qualname____firstlineno____doc__torchTensor__annotations____static_attributes__r       h/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/models/autoencoders/autoencoder_tiny.pyr   r      s     \\r    r   c                      ^  \ rS rSrSrSr\               S(S\S\S\\S4   S\\S4   S	\	S
\	S\S\S\\S4   S\\S4   S\S\
S\S\
S\
4U 4S jjj5       rS\R                  S\R                  4S jrS\R                  S\R                  4S jrS)S jrS)S jrS*S\SS4S jjrS)S jrS\R                  S\R                  4S jrS\R                  S\R                  4S  jr\S*S\R                  S!\S\\\\R                     4   4S" jj5       r\ S+S\R                  S#\\R8                     S!\S\\\\R                     4   4S$ jj5       r S*S%\R                  S!\S\\\\R                     4   4S& jjrS'r U =r!$ ),AutoencoderTiny)   a/  
A tiny distilled VAE model for encoding images into latents and decoding latent representations into images.

[`AutoencoderTiny`] is a wrapper around the original implementation of `TAESD`.

This model inherits from [`ModelMixin`]. Check the superclass documentation for its generic methods implemented for
all models (such as downloading or saving).

Parameters:
    in_channels (`int`, *optional*, defaults to 3): Number of channels in the input image.
    out_channels (`int`,  *optional*, defaults to 3): Number of channels in the output.
    encoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`):
        Tuple of integers representing the number of output channels for each encoder block. The length of the
        tuple should be equal to the number of encoder blocks.
    decoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`):
        Tuple of integers representing the number of output channels for each decoder block. The length of the
        tuple should be equal to the number of decoder blocks.
    act_fn (`str`, *optional*, defaults to `"relu"`):
        Activation function to be used throughout the model.
    latent_channels (`int`, *optional*, defaults to 4):
        Number of channels in the latent representation. The latent space acts as a compressed representation of
        the input image.
    upsampling_scaling_factor (`int`, *optional*, defaults to 2):
        Scaling factor for upsampling in the decoder. It determines the size of the output image during the
        upsampling process.
    num_encoder_blocks (`Tuple[int]`, *optional*, defaults to `(1, 3, 3, 3)`):
        Tuple of integers representing the number of encoder blocks at each stage of the encoding process. The
        length of the tuple should be equal to the number of stages in the encoder. Each stage has a different
        number of encoder blocks.
    num_decoder_blocks (`Tuple[int]`, *optional*, defaults to `(3, 3, 3, 1)`):
        Tuple of integers representing the number of decoder blocks at each stage of the decoding process. The
        length of the tuple should be equal to the number of stages in the decoder. Each stage has a different
        number of decoder blocks.
    latent_magnitude (`float`, *optional*, defaults to 3.0):
        Magnitude of the latent representation. This parameter scales the latent representation values to control
        the extent of information preservation.
    latent_shift (float, *optional*, defaults to 0.5):
        Shift applied to the latent representation. This parameter controls the center of the latent space.
    scaling_factor (`float`, *optional*, defaults to 1.0):
        The component-wise standard deviation of the trained latent space computed using the first batch of the
        training set. This is used to scale the latent space to have unit variance when training the diffusion
        model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
        diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
        / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
        Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) paper. For this
        Autoencoder, however, no such scaling factor was used, hence the value of 1.0 as the default.
    force_upcast (`bool`, *optional*, default to `False`):
        If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
        can be fine-tuned / trained to a lower range without losing too much precision, in which case
        `force_upcast` can be set to `False` (see this fp16-friendly
        [AutoEncoder](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)).
Tin_channelsout_channelsencoder_block_out_channels.decoder_block_out_channelsact_fnupsample_fnlatent_channelsupsampling_scaling_factornum_encoder_blocksnum_decoder_blockslatent_magnitudelatent_shiftforce_upcastscaling_factorshift_factorc           
        > [         TU ]  5         [        U5      [        U	5      :w  a  [        S5      e[        U5      [        U
5      :w  a  [        S5      e[	        UUU	UUS9U l        [        UUU
UUUUS9U l        Xl        Xl	        Xl
        SU l        SU l        SU-  U l        SU l        SU l        U R                  U R                  -  U l        U R#                  US	9  U R#                  SS
9  g )NzQ`encoder_block_out_channels` should have the same length as `num_encoder_blocks`.zQ`decoder_block_out_channels` should have the same length as `num_decoder_blocks`.)r%   r&   
num_blocksblock_out_channelsr)   )r%   r&   r5   r6   r,   r)   r*   Fr   g      ?i   )r6   )r1   )super__init__len
ValueErrorr   encoderr   decoderr/   r0   r2   use_slicing
use_tilingspatial_scale_factortile_overlap_factortile_sample_min_sizetile_latent_min_sizer	   )selfr%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   	__class__s                   r!   r8   AutoencoderTiny.__init__a   s   & 	)*c2D.EEpqq)*c2D.EEpqq"#()9
 #'%)9&?#
 !1(,  %&|O!#( $'!$($=$=AZAZ$Z!3MNU3r    xreturnc                     UR                  SU R                  -  5      R                  U R                  5      R	                  SS5      $ )zraw latents -> [0, 1]r   r   r   )divr/   addr0   clamprC   rF   s     r!   scale_latentsAutoencoderTiny.scale_latents   s;    uuQ.../33D4E4EFLLQPQRRr    c                 p    UR                  U R                  5      R                  SU R                  -  5      $ )z[0, 1] -> raw latentsr   )subr0   mulr/   rL   s     r!   unscale_latentsAutoencoderTiny.unscale_latents   s-    uuT&&'++A0E0E,EFFr    Nc                     SU l         g)z
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
TNr=   rC   s    r!   enable_slicingAutoencoderTiny.enable_slicing   s    
  r    c                     SU l         g)z
Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
decoding in one step.
FNrU   rV   s    r!   disable_slicingAutoencoderTiny.disable_slicing   s    
 !r    r>   c                     Xl         g)z
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
processing larger images.
N)r>   )rC   r>   s     r!   enable_tilingAutoencoderTiny.enable_tiling   s	     %r    c                 &    U R                  S5        g)z
Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
decoding in one step.
FN)r]   rV   s    r!   disable_tilingAutoencoderTiny.disable_tiling   s    
 	5!r    c                 8   U R                   nU R                  n[        X0R                  -  5      nX4-
  n[	        SUR
                  S   U5      n[	        SUR
                  S   U5      n[        R                  " [        R                  " [        R                  " X2-  5      XB-  S-
  -  /S-  SS95      nUR                  SS5      R                  UR                  5      n[        R                  " UR
                  S   SUR
                  S   U-  UR
                  S   U-  UR                  S	9n	U H  n
U H  nUS
XU-   2XU-   24   nU	S
X-  X-   U-  2X-  X-   U-  24   nU R                  U5      nUR
                  S   UR
                  S   nnU
S:X  a  [        R                  " US   5      OUS   nUS:X  a  [        R                  " US   5      OUS   nUU-  nUS
SU2SU24   US
SU2SU24   nnUR!                  UU-  SU-
  U-  -   5        M     M     U	$ )  Encode a batch of images using a tiled encoder.

When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
steps. This is useful to keep memory use constant regardless of image size. To avoid tiling artifacts, the
tiles overlap and are blended together to form a smooth output.

Args:
    x (`torch.Tensor`): Input batch of images.

Returns:
    `torch.Tensor`: Encoded batch of images.
r   r   r   ijindexing   device.N)r?   rA   intr@   rangeshaper   stackmeshgridarangerK   tork   zerosr;   	ones_likecopy_rC   rF   sf	tile_size
blend_sizetraverse_sizetitjblend_masksoutijtile_intile_outtilehwblend_mask_iblend_mask_j
blend_masks                       r!   _tiled_encodeAutoencoderTiny._tiled_encode   s/    &&--	 %=%==>
!. 1aggbk=11aggbk=1 kkNNELL8JOa<OPQTUU`de
 "''1-00: kk!''!*a):AGGBK2<MVWV^V^_AC]!2AI4EEFsAGq}.C$CQWPQP]bdOdEdde||G,zz"~tzz"~1BCq&u{1~>kZ[nBCq&u{1~>kZ[n)L8
#'RaR!#4jbqb"1"6MjzD0A
Nh3NNO   
r    c                    U R                   nU R                  n[        X0R                  -  5      nX4-
  n[	        SUR
                  S   U5      n[	        SUR
                  S   U5      n[        R                  " [        R                  " [        R                  " X2-  5      XB-  S-
  -  /S-  SS95      nUR                  SS5      R                  UR                  5      n[        R                  " UR
                  S   SUR
                  S   U-  UR
                  S   U-  UR                  S	9n	U H  n
U H  nUS
XU-   2XU-   24   nU	S
X-  X-   U-  2X-  X-   U-  24   nU R                  U5      nUR
                  S   UR
                  S   nnU
S:X  a  [        R                  " US   5      OUS   nUS:X  a  [        R                  " US   5      OUS   nUU-  S
SU2SU24   nUR!                  UU-  SU-
  U-  -   5        M     M     U	$ )rc   r   rd   re   r   r   rf   rg   r   rj   .N)r?   rB   rl   r@   rm   rn   r   ro   rp   rq   rK   rr   rk   rs   r<   rt   ru   rv   s                       r!   _tiled_decodeAutoencoderTiny._tiled_decode   s    &&--	 %=%==>
!. 1aggbk=11aggbk=1 kkNNELL8JOa<OPQTUU`de
 "''1-00: kk!''!*ar)91772;;KTUT\T\]AC]!2AI4EEFsAFamr-A$A16Q]^`L`C``a||G,zz"~tzz"~1BCq&u{1~>kZ[nBCq&u{1~>kZ[n*\93BQB;G
zD0A
Nh3NNO   
r    return_dictc                    U R                   (       a{  UR                  S   S:  ah  UR                  S5       Vs/ s H5  o0R                  (       a  U R	                  U5      OU R                  U5      PM7     nn[        R                  " U5      nO3U R                  (       a  U R	                  U5      OU R                  U5      nU(       d  U4$ [        US9$ s  snf )Nr   r   )r   )	r=   rn   splitr>   r   r;   r   catr   )rC   rF   r   x_sliceoutputs        r!   encodeAutoencoderTiny.encode!  s    
Qijipipqrisis^e""7+DLLQXDYYis   YYv&F.2ooT''*4<<PQ?F9$V44   <C	generatorc                    U R                   (       a{  UR                  S   S:  ah  UR                  S5       Vs/ s H5  o@R                  (       a  U R	                  U5      OU R                  U5      PM7     nn[        R                  " U5      nO3U R                  (       a  U R	                  U5      OU R                  U5      nU(       d  U4$ [        US9$ s  snf )Nr   r   sample)	r=   rn   r   r>   r   r<   r   r   r   )rC   rF   r   r   r   r   s         r!   decodeAutoencoderTiny.decode0  s     
Qijipipqrisis^e""7+DLLQXDYYis   YYv&F.2ooT''*4<<PQ?F9F++r   r   c                 4   U R                  U5      R                  nU R                  U5      R                  S5      R	                  5       R                  5       nU R                  US-  5      nU R                  U5      R                  nU(       d  U4$ [        US9$ )z
Args:
    sample (`torch.Tensor`): Input sample.
    return_dict (`bool`, *optional*, defaults to `True`):
        Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
   g     o@r   )
r   r   rM   mul_round_byterR   r   r   r   )rC   r   r   enc
scaled_encunscaled_encdecs          r!   forwardAutoencoderTiny.forwardA  s     kk&!)) '',11#6==?DDF
 ++J,>?kk,'..6MC((r    )r<   r;   r/   r0   r2   r?   rB   r@   rA   r=   r>   )r   r   @   r   r   r   r   relunearestri   r   )r   r   r   r   )r   r   r   r   r   g      ?Fg      ?g        )rG   N)T)NT)"r   r   r   r   r    _supports_gradient_checkpointingr	   rl   r   strfloatboolr8   r   r   rM   rR   rW   rZ   r]   r`   r   r   r   r   r   r   r   	Generatorr   r   r   r   __classcell__)rD   s   @r!   r#   r#   )   s{   3j (,$ 6F6F$ )*.:.: !!" #!!9494 94 %*#s(O	94
 %*#s(O94 94 94 94 $'94 "#s(O94 "#s(O94 94 94 94 94  !94 94vSu|| S SG G%,, G !% % %".u|| . .`-u|| - -^ 5 54 55I^`efkfrfr`sIsCt 5 5 `d,,*25??*C,Y],	}eELL11	2, ,& !)) ) 
}eELL11	2	) )r    r#   )dataclassesr   typingr   r   r   r   configuration_utilsr   r	   utilsr
   utils.accelerate_utilsr   modeling_utilsr   vaer   r   r   r   r#   r   r    r!   <module>r      sP     " ) )  B  8 ' 8 8 	J 	 	q)j+ q)r    