
    biy                        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Zd dlmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddlm Z  ddl!m"Z"m#Z#  e       rd dl$m%c m&Z' dZ(ndZ( ejR                  e*      Z+dZ,	 	 	 	 dde-de-de.de.fdZ/	 	 	 	 d dee-   deee0ejb                  f      deee-      deee.      fdZ2 G d de"e      Z3 G d de3      Z4y)!    N)AnyCallableDictListOptionalTupleUnion)Gemma2PreTrainedModelGemmaTokenizerGemmaTokenizerFast   )VaeImageProcessor)Lumina2LoraLoaderMixin)AutoencoderKL)Lumina2Transformer2DModel)FlowMatchEulerDiscreteScheduler)	deprecateis_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipelineImagePipelineOutputTFa:  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import Lumina2Pipeline

        >>> pipe = Lumina2Pipeline.from_pretrained("Alpha-VLLM/Lumina-Image-2.0", torch_dtype=torch.bfloat16)
        >>> # Enable memory optimizations.
        >>> pipe.enable_model_cpu_offload()

        >>> prompt = "Upper body of a young woman in a Victorian-era outfit with brass goggles and leather straps. Background shows an industrial revolution cityscape with smoky skies and tall, metal structures"
        >>> image = pipe(prompt).images[0]
        ```
base_seq_lenmax_seq_len
base_shift	max_shiftc                 <    ||z
  ||z
  z  }|||z  z
  }| |z  |z   }|S N )image_seq_lenr   r   r   r   mbmus           g/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/lumina2/pipeline_lumina2.pycalculate_shiftr'   @   s;     
Z	K,$>?AQ%%A		Q	BI    num_inference_stepsdevice	timestepssigmasc                    ||t        d      |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS  | j                  |fd	|i| | j                  }||fS )a  
    Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
    custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

    Args:
        scheduler (`SchedulerMixin`):
            The scheduler to get timesteps from.
        num_inference_steps (`int`):
            The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
            must be `None`.
        device (`str` or `torch.device`, *optional*):
            The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
        timesteps (`List[int]`, *optional*):
            Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
            `num_inference_steps` and `sigmas` must be `None`.
        sigmas (`List[float]`, *optional*):
            Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
            `num_inference_steps` and `timesteps` must be `None`.

    Returns:
        `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
        second element is the number of inference steps.
    zYOnly one of `timesteps` or `sigmas` can be passed. Please choose one to set custom valuesr+   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r+   r*   r,   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r,   r*   r*   r!   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r+   len)	schedulerr)   r*   r+   r,   kwargsaccepts_timestepsaccept_sigmass           r&   retrieve_timestepsr;   N   s   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	 	M)FMfM''	!)n ))) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	 	GvfGG''	!)n ))) 	 	 3MFMfM''	)))r(   c            5           e Zd ZdZg ZddgZdZdedede	de
d	eeef   f
 fd
Z	 	 d9deeee   f   deej&                     dedeej,                  ej,                  f   fdZ	 	 	 	 	 	 	 	 	 	 d:deeee   f   dedeeee   f   dedeej&                     deej,                     deej,                     deej,                     deej,                     dee   dedeej,                  ej,                  ej,                  ej,                  f   fdZd Z	 	 	 	 	 	 d;dZd Zd Zd  Zd! Zd<d"Z e!d#        Z"e!d$        Z#e!d%        Z$e!d&        Z% ejL                          e'e(      dddd'd(dddddddddd)ddddgdd*ddfdeeee   f   d+ee   d,ee   d-ed.e)deeee   f   d/ee)   dee   d0eeejT                  eejT                     f      deej,                     deej,                     deej,                     deej,                     deej,                     d1ee   d2ed3ee+ee,f      d4ee-eee+gdf      d5ee   dee   d6e)d7ededee.ef   f0d8              Z/ xZ0S )=Lumina2Pipelinea  
    Pipeline for text-to-image generation using Lumina-T2I.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
    library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)

    Args:
        vae ([`AutoencoderKL`]):
            Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
        text_encoder ([`Gemma2PreTrainedModel`]):
            Frozen Gemma2 text-encoder.
        tokenizer (`GemmaTokenizer` or `GemmaTokenizerFast`):
            Gemma tokenizer.
        transformer ([`Transformer2DModel`]):
            A text conditioned `Transformer2DModel` to denoise the encoded image latents.
        scheduler ([`SchedulerMixin`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
    latentsprompt_embedsztext_encoder->transformer->vaetransformerr7   vaetext_encoder	tokenizerc                    t         |           | j                  |||||       d| _        t	        | d      r,| j
                   | j
                  j                  j                  nd| _        | j                  | j                  z  | _	        d| _
        t        | j                  dz        | _        t        | dd       d	| j                  _        y y )
N)rA   rB   rC   r@   r7      r@      zYou are an assistant designed to generate superior images with the superior degree of image-text alignment based on textual prompts or user prompts.r   )vae_scale_factorrC   right)super__init__register_modulesrG   hasattrr@   configsample_sizedefault_sample_sizedefault_image_sizesystem_promptr   image_processorgetattrrC   padding_side)selfr@   r7   rA   rB   rC   r5   s         r&   rJ   zLumina2Pipeline.__init__   s     	%# 	 	
 !" t]+0@0@0L ##// 	 
 #'":":T=R=R"R t0$BWBWZ[B[\4d+7*1DNN' 8r(   N   promptr*   max_sequence_lengthreturnc                 P   |xs | j                   }t        |t              r|gn|}| j                  |d|dd      }|j                  j                  |      }| j                  |dd      j                  j                  |      }|j                  d   |j                  d   k\  rXt        j                  ||      sB| j                  j                  |d d |dz
  df         }t        j                  d	| d
|        |j                  j                  |      }| j                  ||d      }	|	j                  d   }	| j                  | j                  j                  }
n%| j                   | j                   j                  }
nd }
|	j                  |
|      }	|	j                  \  }}}|	|fS )N
max_lengthTpt)paddingr[   
truncationreturn_tensorslongest)r]   r_      z]The following part of your input was truncated because Gemma can only handle sequences up to z	 tokens: )attention_maskoutput_hidden_states)dtyper*   )_execution_device
isinstancestrrC   	input_idstoshapetorchequalbatch_decodeloggerwarningrc   rB   hidden_statesrf   r@   )rU   rW   r*   rX   text_inputstext_input_idsuntruncated_idsremoved_textprompt_attention_maskr?   rf   _seq_lens                r&   _get_gemma_prompt_embedsz(Lumina2Pipeline._get_gemma_prompt_embeds   s    1411'4&&nn * % 
 %..11&9..SW.Xbbeeflm  $(<(<R(@@UcetIu>>66qJ]`aJadfJfGf7ghLNN'(	,A
 !, : : = =f E))+@W[ * 
 &33B7(%%++E)$$**EE%((uV(D%++7A333r(   Trb   do_classifier_free_guidancenegative_promptnum_images_per_promptnegative_prompt_embedsrw   negative_prompt_attention_maskrQ   c                    || j                   }t        |t              r|gn|}|t        |      }n|j                  d   }|
| j
                  }
||D cg c]
  }|
dz   |z    }}|| j                  |||      \  }}|j                  \  }}}|j                  d|d      }|j                  ||z  |d      }|j                  |d      }|j                  ||z  d      }|r|||nd}t        |t              r||gz  n|}|:t        |      t        |      ur$t        dt        |       dt        |       d	      t        |t              r|g}n/|t        |      k7  r!t        d
| dt        |       d| d| d	      | j                  |||      \  }}	|j                  \  }}}|j                  d|d      }|j                  ||z  |d      }|	j                  |d      }	|	j                  ||z  d      }	||||	fS c c}w )a  
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
                instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
                Lumina-T2I, this should be "".
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                whether to use classifier free guidance or not
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                number of images that should be generated per prompt
            device: (`torch.device`, *optional*):
                torch device to place the resulting embeddings on
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. For Lumina-T2I, it's should be the embeddings of the "" string.
            max_sequence_length (`int`, defaults to `256`):
                Maximum sequence length to use for the prompt.
        r   z <Prompt Start> )rW   r*   rX   rb   ra    z?`negative_prompt` should be the same type to `prompt`, but got z != .z`negative_prompt`: z has batch size z, but `prompt`: zT. Please make sure that passed `negative_prompt` matches the batch size of `prompt`.)rg   rh   ri   r6   rl   rQ   rz   repeatviewtype	TypeErrorr.   )rU   rW   r{   r|   r}   r*   r?   r~   rw   r   rQ   rX   
batch_sizepry   rx   s                   r&   encode_promptzLumina2Pipeline.encode_prompt   s   L >++F'4&&VJ&,,Q/J  ..MFLMm&881<MFM 373P3P$7 4Q 40M0 "/!4!4
GQ%,,Q0EqI%**:8M+MwXZ[ 5 < <=RTU V 5 : ::H];]_a b '+A+I1@1LoRTO AK?\_@`jO+<<fuO!d6l$:O&OUVZ[jVkUl mV~Q(  OS1#2"3s?33 )/)::J3K_J` ax/
| <33 
 FJEbEb&$7 Fc FB"$B &<%A%A"J%;%B%B1F[]^%_"%;%@%@NcAcelnp%q"-K-R-RShjk-l*-K-P-P22B.* 35KMkkkg Ns   G?c                 V   dt        t        j                  | j                  j                        j
                  j                               v }i }|r||d<   dt        t        j                  | j                  j                        j
                  j                               v }|r||d<   |S )Neta	generator)r/   r0   r1   r7   stepr3   r4   )rU   r   r   accepts_etaextra_step_kwargsaccepts_generators         r&   prepare_extra_step_kwargsz)Lumina2Pipeline.prepare_extra_step_kwargsV  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  r(   c           
          | j                   dz  z  dk7  s| j                   dz  z  dk7  r"t        d j                   dz   d| d| d      |	Lt         fd|	D              s8t        d j                   d	|	D cg c]  }| j                  vs| c}       ||t        d
| d| d      ||t        d      |7t	        |t
              s't	        |t              st        dt        |             ||t        d
| d| d      ||t        d| d| d      ||t        d      ||t        d      ||~|j                  |j                  k7  r&t        d|j                   d|j                   d      |j                  |j                  k7  r&t        d|j                   d|j                   d      |
|
dkD  rt        d|
       y y c c}w )Nr   r   z-`height` and `width` have to be divisible by z	 but are z and r   c              3   :   K   | ]  }|j                   v   y wr    )_callback_tensor_inputs).0krU   s     r&   	<genexpr>z/Lumina2Pipeline.check_inputs.<locals>.<genexpr>y  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z and `negative_prompt_embeds`: z'Cannot forward both `negative_prompt`: zEMust provide `prompt_attention_mask` when specifying `prompt_embeds`.zWMust provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` z`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but got: `prompt_attention_mask` z% != `negative_prompt_attention_mask` i   z8`max_sequence_length` cannot be greater than 512 but is )	rG   r.   allr   rh   ri   listr   rl   )rU   rW   heightwidthr|   r?   r~   rw   r   "callback_on_step_end_tensor_inputsrX   r   s   `           r&   check_inputszLumina2Pipeline.check_inputsg  s    T**Q./14AVAVYZAZ8[_`8`?@U@UXY@Y?ZZcdjckkpqvpwwxy  .9# F
7YF
 C
 DTEaEaDbbn  |^  pHvw  bc  ko  kG  kG  bGpq  pH  oI  J  -";08N}o ^0 0  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa"8"D0 9*++]_ 
 &+A+M9/9J K*++]_ 
 $)>)Fdee!-2P2Xvww$)?)K""&<&B&BB --:-@-@,A B.445Q8 
 %**.L.R.RR 55J5P5P4Q R6<<=Q@  */BS/HWXkWlmnn 0I*_ pHs   ;GGc                 8    | j                   j                          y)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.
        N)rA   enable_slicingrU   s    r&   enable_vae_slicingz"Lumina2Pipeline.enable_vae_slicing      
 	!r(   c                 8    | j                   j                          y)z
        Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rA   disable_slicingr   s    r&   disable_vae_slicingz#Lumina2Pipeline.disable_vae_slicing  s    
 	  "r(   c                 8    | j                   j                          y)a  
        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)rA   enable_tilingr   s    r&   enable_vae_tilingz!Lumina2Pipeline.enable_vae_tiling  s     	 r(   c                 8    | j                   j                          y)z
        Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rA   disable_tilingr   s    r&   disable_vae_tilingz"Lumina2Pipeline.disable_vae_tiling  r   r(   c	                 D   dt        |      | j                  dz  z  z  }dt        |      | j                  dz  z  z  }||||f}	t        |t              r)t	        |      |k7  rt        dt	        |       d| d      |t        |	|||      }|S |j                  |      }|S )Nr   z/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.)r   r*   rf   )intrG   rh   r   r6   r.   r   rk   )
rU   r   num_channels_latentsr   r   rf   r*   r   r>   rl   s
             r&   prepare_latentszLumina2Pipeline.prepare_latents  s     c&kd&;&;a&?@ASZD$9$9A$=>?165Ai&3y>Z+GA#i.AQ R&<'gi 
 ?"5IfTYZG  jj(Gr(   c                     | j                   S r    _guidance_scaler   s    r&   guidance_scalezLumina2Pipeline.guidance_scale  s    ###r(   c                     | j                   S r    )_attention_kwargsr   s    r&   attention_kwargsz Lumina2Pipeline.attention_kwargs  s    %%%r(   c                      | j                   dkD  S )Nrb   r   r   s    r&   r{   z+Lumina2Pipeline.do_classifier_free_guidance  s    ##a''r(   c                     | j                   S r    )_num_timestepsr   s    r&   num_timestepszLumina2Pipeline.num_timesteps  s    """r(      g      @pil      ?r   r   r)   r   r,   r   output_typereturn_dictr   callback_on_step_endr   cfg_trunc_ratiocfg_normalizationc                 
   |xs | j                   | j                  z  }|xs | j                   | j                  z  }|| _        || _        | j	                  ||||||||||
       |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                  }| j                  || j                  |||||||||      \  }}}}| j                  j                  j                  }| j!                  ||z  ||||j"                  ||	|
      }
|t%        j&                  dd|z  |      n|}|
j                  d   }t)        || j*                  j                  j-                  dd      | j*                  j                  j-                  d	d
      | j*                  j                  j-                  dd      | j*                  j                  j-                  dd            }t/        | j*                  ||||      \  }}t1        t        |      || j*                  j2                  z  z
  d      }t        |      | _        | j7                  |      5 }t9        |      D ]  \  } }!| dz   |z  |kD  }"d|!| j*                  j                  j:                  z  z
  }#|#j=                  |
j                  d         }#| j                  |
|#||d| j>                        d   }$| j                  rl|"sj| j                  |
|#||d| j>                        d   }%|%||$|%z
  z  z   }&|r;tA        jB                  |$dd      }'tA        jB                  |&dd      }(|&|'|(z  z  }&n|$}&|
j"                  })|& }&| j*                  jE                  |&|!|
d      d   }
|
j"                  |)k7  r9t@        jF                  jH                  jK                         r|
jM                  |)      }
|Hi }*|D ]  }+tO               |+   |*|+<     || | |!|*      },|,jQ                  d|
      }
|,jQ                  d|      }| t        |      dz
  k(  s'| dz   |kD  r/| dz   | j*                  j2                  z  dk(  r|jS                          tT        stW        jX                           	 ddd       |dk(  s|
| jZ                  j                  j\                  z  | jZ                  j                  j^                  z   }
| jZ                  ja                  |
d      d   }-| jb                  je                  |-|      }-n|
}-| jg                          |s|-fS ti        |-      S # 1 sw Y   xY w)u  
        Function invoked when calling the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            num_inference_steps (`int`, *optional*, defaults to 30):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            sigmas (`List[float]`, *optional*):
                Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
                their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
                will be used.
            guidance_scale (`float`, *optional*, defaults to 4.0):
                Guidance scale as defined in [Classifier-Free Diffusion
                Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
                of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
                `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
                the text `prompt`, usually at the expense of lower image quality.
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            height (`int`, *optional*, defaults to self.unet.config.sample_size):
                The height in pixels of the generated image.
            width (`int`, *optional*, defaults to self.unet.config.sample_size):
                The width in pixels of the generated image.
            eta (`float`, *optional*, defaults to 0.0):
                Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only
                applies to [`schedulers.DDIMScheduler`], will be ignored for others.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
                to make generation deterministic.
            latents (`torch.Tensor`, *optional*):
                Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor will ge generated by sampling using the supplied random `generator`.
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            prompt_attention_mask (`torch.Tensor`, *optional*): Pre-generated attention mask for text embeddings.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. For Lumina-T2I this negative prompt should be "". If not
                provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
            negative_prompt_attention_mask (`torch.Tensor`, *optional*):
                Pre-generated attention mask for negative text embeddings.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generate image. Choose between
                [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
            attention_kwargs:
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, *optional*):
                A function that calls at the end of each denoising steps during the inference. The function is called
                with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
                callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
                `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            system_prompt (`str`, *optional*):
                The system prompt to use for the image generation.
            cfg_trunc_ratio (`float`, *optional*, defaults to `1.0`):
                The ratio of the timestep interval to apply normalization-based guidance scale.
            cfg_normalization (`bool`, *optional*, defaults to `True`):
                Whether to apply normalization-based guidance scale.
            max_sequence_length (`int`, defaults to `256`):
                Maximum sequence length to use with the `prompt`.

        Examples:

        Returns:
            [`~pipelines.ImagePipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
                returned where the first element is a list with the generated images
        )r?   r~   rw   r   rX   r   Nrb   r   )	r|   r}   r*   r?   r~   rw   r   rX   rQ   r   base_image_seq_lenrV   max_image_seq_len   r         ?r   ffffff?)r,   r%   )totalF)rr   timestepencoder_hidden_statesencoder_attention_maskr   r   ra   T)dimkeepdim)r   r>   r?   latent)r   )images)5rO   rG   r   r   r   rh   ri   r   r6   rl   rg   r   r{   r@   rM   in_channelsr   rf   nplinspacer'   r7   getr;   maxorderr   progress_bar	enumeratenum_train_timestepsexpandr   rm   normr   backendsmpsis_availablerk   localspopupdateXLA_AVAILABLExm	mark_steprA   scaling_factorshift_factordecoderR   postprocessmaybe_free_model_hooksr   ).rU   rW   r   r   r)   r   r|   r,   r}   r   r>   r?   r~   rw   r   r   r   r   r   r   rQ   r   r   rX   r   r*   latent_channelsr"   r%   r+   num_warmup_stepsr   itdo_classifier_free_truncationcurrent_timestepnoise_pred_condnoise_pred_uncond
noise_pred	cond_norm
noise_normlatents_dtypecallback_kwargsr   callback_outputsimages.                                                 r&   __call__zLumina2Pipeline.__call__  sy   ^ K433d6K6KKI11D4I4II-!1 	'#9"7+I 3/Q 	 	
 *VS"9JJvt$<VJ&,,Q/J'' ,,+"7'#9"7+I 3'  
	
!"*  **11==&&..	
 TZSaS!&9"9;NOgma(NN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 *<NN*
&	& s9~0CdnnFZFZ0ZZ\]^!)n %89 =	#\!), <#112Q:M0MP_0_-#$q4>>+@+@+T+T'T#T #3#:#:7==;K#L "&"2"2")-*7+@ %%)%:%: #3 # # 33<Y(,(8(8&-!1.D/M$))-)>)> )9 ) )% "3^YjGj5k!kJ($)JJBPT$U	%*ZZ
D%Q
%/9z3I%J
!0J !(([
..--j!WRW-XYZ[==M1~~))668")**]";'3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNy<#=	#~ h&!?!??488??C_C__GHHOOGO?BE((44U4TEE 	##%8O"%00Y=	# =	#s   HT9/T99U)NrV   )
TNrb   NNNNNNrV   )NNNNNNr    )1__name__
__module____qualname____doc___optional_componentsr   model_cpu_offload_seqr   r   r   r
   r	   r   r   rJ   ri   r   r   rm   r*   r   r   Tensorrz   boolr   r   r   r   r   r   r   r   propertyr   r   r{   r   no_gradr   EXAMPLE_DOC_STRINGfloat	Generatorr   r   r   r   r   __classcell__r5   s   @r&   r=   r=      s   & (/:<2.2 32 	2
 ,2 );;<2D *.#&	+4c49n%+4 &+4 !	+4
 
u||U\\)	*+4b -115%&)-049=8<AE'+#&elc49n%el &*el sDI~.	el
  #el &el  -el !) 6el  (5el )1(>el  }el !el 
u||U\\5<<E	FelP!. #"'++/ FoP"#!"* $ $ & & ( ( # # U]]_12 )-# $#% #15"/0MQ*.049=8<AE%* 59KO9B'+!$"&#&1L1c49n%L1 }L1 	L1
 !L1 L1 sDI~.L1 UL1  (}L1 E%//43H"HIJL1 %,,'L1  -L1 !) 6L1  (5L1 )1(>L1  c]!L1" #L1$ #4S>2%L1& 'xc40@$0F'GH'L1( -1I)L1*  }+L1, -L1.  /L10 !1L12 
"E)	*3L1 3 L1r(   r=   c                   >     e Zd Zdededededeee	f   f
 fdZ
 xZS )Lumina2Text2ImgPipeliner@   r7   rA   rB   rC   c                 L    d}t        dd|       t        | 	  |||||       y )Nz`Lumina2Text2ImgPipeline` has been renamed to `Lumina2Pipeline` and will be removed in a future version. Please use `Lumina2Pipeline` instead.zDdiffusers.pipelines.lumina2.pipeline_lumina2.Lumina2Text2ImgPipelinez0.34)r@   r7   rA   rB   rC   )r   rI   rJ   )rU   r@   r7   rA   rB   rC   deprecation_messager5   s          r&   rJ   z Lumina2Text2ImgPipeline.__init__  s<     oXZ`buv#% 	 	
r(   )r   r   r   r   r   r   r
   r	   r   r   rJ   r  r  s   @r&   r
  r
    sH    
.
 3
 	

 ,
 );;<
 
r(   r
  )rV   r   r   r   )NNNN)5r0   typingr   r   r   r   r   r   r	   numpyr   rm   transformersr
   r   r   rR   r   loadersr   modelsr   'models.transformers.transformer_lumina2r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   pipeline_utilsr   r   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr   rp   r  r   r  r'   ri   r*   r;   r=   r
  r!   r(   r&   <module>r     s-    D D D   R R 0 - # P 9  . C ))MM			H	% & 

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vy	1')? y	1x
o 
r(   