o
    Giv                  
   @   sB  d dl Z d dlmZmZ d dlZd dlZd dlmZm	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mZ dd	lmZ d
dlmZ ddlmZ e r[d dlm  mZ dZndZe e!Z"dZ#				d#de$de$de%de%fddZ&				d$de$dB de'ej(B dB de)e$ dB de)e% dB fdd Z*G d!d" d"eZ+dS )%    N)AnyCallable)Qwen2TokenizerFast
Qwen3Model   )VaeImageProcessor)AutoencoderKLOvisImageTransformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipeline   )OvisImagePipelineOutputTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import OvisImagePipeline

        >>> pipe = OvisImagePipeline.from_pretrained("AIDC-AI/Ovis-Image-7B", torch_dtype=torch.bfloat16)
        >>> pipe.to("cuda")
        >>> prompt = 'A creative 3D artistic render where the text "OVIS-IMAGE" is written in a bold, expressive handwritten brush style using thick, wet oil paint. The paint is a mix of vibrant rainbow colors (red, blue, yellow) swirling together like toothpaste or impasto art. You can see the ridges of the brush bristles and the glossy, wet texture of the paint. The background is a clean artist's canvas. Dynamic lighting creates soft shadows behind the floating paint strokes. Colorful, expressive, tactile texture, 4k detail.'
        >>> image = pipe(prompt, negative_prompt="", num_inference_steps=50, guidance_scale=5.0).images[0]
        >>> image.save("ovis_image.png")
        ```
            ?ffffff?base_seq_lenmax_seq_len
base_shift	max_shiftc                 C   s,   || ||  }|||  }| | | }|S N )image_seq_lenr   r   r   r   mbmur   r   f/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/pipelines/ovis_image/pipeline_ovis_image.pycalculate_shift8   s   r"   num_inference_stepsdevice	timestepssigmasc                 K   s  |dur|durt d|dur>dtt| jj v }|s(t d| j d| jd||d| | j}t	|}||fS |durpdtt| jj v }|sZt 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.
    NzYOnly 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_sigmasr   r   r!   retrieve_timestepsF   s2   r4   c                '       sB  e Zd ZdZdZg ZddgZdedede	de
d	ef
 fd
dZ	dBdeee B fddZ				dCdeee B dedejdB dejdB fddZ			dDdeee B dejdB dedejdB fddZ					dEddZedd Zedd Zedd Z	dBd d!Zed"d# Zed$d% Zed&d' Z ed(d) Z!ed*d+ Z"e# e$e%dd,d-ddd.ddddddd/d0dddgd1fdeee B d2eee B d3e&d4edB d5edB d6ed7ee& dB dedB d8ej'eej' B dB dejdB dejdB d9ejdB d:edB d;e(d<e)ee*f dB d=e+eegdf dB d>ee d?ef$d@dAZ,  Z-S )FOvisImagePipelinea  
    The Ovis-Image pipeline for text-to-image generation.

    Reference: https://github.com/AIDC-AI/Ovis-Image

    Args:
        transformer ([`OvisImageTransformer2DModel`]):
            Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
        scheduler ([`FlowMatchEulerDiscreteScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKL`]):
            Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
        text_encoder ([`Qwen3Model`]):
            Text encoder of class
            [Qwen3Model](https://huggingface.co/docs/transformers/en/model_doc/qwen3#transformers.Qwen3Model).
        tokenizer (`Qwen2TokenizerFast`):
            Tokenizer of class
            [Qwen2TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/qwen2#transformers.Qwen2TokenizerFast).
    ztext_encoder->transformer->vaelatentsprompt_embedsr0   vaetext_encoder	tokenizertransformerc                    sz   t    | j|||||d t| dd r dt| jjjd  nd| _t	| jd d| _
d| _d| _d	| j | _d
| _d S )N)r8   r9   r:   r;   r0   r8   r   r      )vae_scale_factorzDescribe the image by detailing the color, quantity, text, shape, size, texture, spatial relationships of the objects and background:    r      )super__init__register_modulesgetattrr/   r8   configblock_out_channelsr=   r   image_processorsystem_promptuser_prompt_begin_idtokenizer_max_lengthdefault_sample_size)selfr0   r8   r9   r:   r;   r.   r   r!   rA      s   
(
zOvisImagePipeline.__init__Npromptc                 C   sV   t |tr|gn|}g }|D ]}d| j| dg}| jj|dddd}|| q|S )Nuser)rolecontentFT)tokenizeadd_generation_promptenable_thinking)
isinstancestrrG   r:   apply_chat_templateappend)rK   rM   messageseach_promptmessager   r   r!   _get_messages   s   zOvisImagePipeline._get_messagesr   num_images_per_promptr$   dtypec                 C   s   |p| j }|p
| jj}| |}t|}| j|dd| jddd}|j|}|j	|}	| j||	d}
|
j
}||	d  }|d d | jd d d f }|j\}}}|d|d}||| |d	}|S )
N
max_lengthTptF)padding
truncationr^   return_tensorsadd_special_tokens)	input_idsattention_mask).Nr   )_execution_devicer9   r]   r[   r/   r:   rI   rd   tore   last_hidden_staterH   shaperepeatview)rK   rM   r\   r$   r]   rX   
batch_sizetokensrd   re   outputsr7   _seq_lenr   r   r!   _get_ovis_prompt_embeds   s2   

z)OvisImagePipeline._get_ovis_prompt_embedsc                 C   s   |p| j }|du r| j|||d}| jdur| jjn| jj}t|jd d}|d t|jd dddf  |d< |d t|jd dddf  |d< |j	||d}||fS )a'  

        Args:
            prompt (`str`, *optional*):
                prompt to be encoded
            device: (`torch.device`):
                torch device
            num_images_per_prompt (`int`):
                number of images that should be generated per prompt
            prompt_embeds (`torch.FloatTensor`, *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.
        N)rM   r$   r\   r   r   .r   .r   r$   r]   )
rg   rr   r9   r]   r;   torchzerosrj   arangerh   )rK   rM   r$   r\   r7   r]   text_idsr   r   r!   encode_prompt   s   
((zOvisImagePipeline.encode_promptc	           	   	      sB  | j d  dks| j d  dkr$td j d  d| d| d |d urEt fdd|D sEtd	 j d
 fdd|D  |d urX|d urXtd| d| d|d u rd|d u rdtd|d ur{t|ts{t|ts{tdt	| |d ur|d urtd| d| d|d ur|dkrtd| d S d S )Nr   r   z-`height` and `width` have to be divisible by z	 but are z and z(. Dimensions will be resized accordinglyc                 3   s    | ]}| j v V  qd S r   _callback_tensor_inputs.0krK   r   r!   	<genexpr>$  s    

z1OvisImagePipeline.check_inputs.<locals>.<genexpr>z2`callback_on_step_end_tensor_inputs` has to be in z, but found c                    s   g | ]	}| j vr|qS r   r{   r}   r   r   r!   
<listcomp>(  s    z2OvisImagePipeline.check_inputs.<locals>.<listcomp>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'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: r   z8`max_sequence_length` cannot be greater than 256 but is )
r=   loggerwarningallr'   r|   rT   rU   listtype)	rK   rM   heightwidthnegative_promptr7   negative_prompt_embeds"callback_on_step_end_tensor_inputsmax_sequence_lengthr   r   r!   check_inputs  s:   $zOvisImagePipeline.check_inputsc           	      C   s|   t ||d}|d t |d d d f  |d< |d t |d d d f  |d< |j\}}}||| |}|j||dS )Nr   rs   rt   ru   )rv   rw   rx   rj   reshaperh   )	rm   r   r   r$   r]   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelsr   r   r!   _prepare_latent_image_ids?  s   ""z+OvisImagePipeline._prepare_latent_image_idsc                 C   sR   |  |||d d|d d} | dddddd} | ||d |d  |d } | S )Nr   r      r   r      )rl   permuter   )r6   rm   num_channels_latentsr   r   r   r   r!   _pack_latentsM  s   zOvisImagePipeline._pack_latentsc                 C   s   | j \}}}dt||d   }dt||d   }| ||d |d |d dd} | dddddd} | ||d ||} | S )Nr   r   r   r   r   r   )rj   intrl   r   r   )r6   r   r   r=   rm   num_patcheschannelsr   r   r!   _unpack_latentsU  s    z!OvisImagePipeline._unpack_latentsc	                 C   s   dt || jd   }dt || jd   }||||f}	|d ur6| ||d |d ||}
|j||d|
fS t|trNt||krNtdt| d| dt|	|||d}| 	|||||}| ||d |d ||}
||
fS )Nr   ru   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.)	generatorr$   r]   )
r   r=   r   rh   rT   r   r/   r'   r   r   )rK   rm   r   r   r   r]   r$   r   r6   rj   r   r   r   r!   prepare_latentse  s    z!OvisImagePipeline.prepare_latentsc                 C      | j S r   )_guidance_scaler   r   r   r!   guidance_scale     z OvisImagePipeline.guidance_scalec                 C   r   r   )_joint_attention_kwargsr   r   r   r!   joint_attention_kwargs  r   z(OvisImagePipeline.joint_attention_kwargsc                 C   r   r   )_num_timestepsr   r   r   r!   num_timesteps  r   zOvisImagePipeline.num_timestepsc                 C   r   r   )_current_timestepr   r   r   r!   current_timestep  r   z"OvisImagePipeline.current_timestepc                 C   r   r   )
_interruptr   r   r   r!   	interrupt  r   zOvisImagePipeline.interrupt g      @2   pilTr   r   r   r   r   r#   r&   r   r   output_typereturn_dictr   callback_on_step_endr   r   c           )      C   sF  |p| j | j }|p| j | j }| j||||||||d || _d| _d| _|dur2t|tr2d}n|dur@t|tr@t	|}n|j
d }| j}|dk}| j||||d\}}|rd| j||||d\}}| jjjd }| || ||||j||	|
\}
}|du rtdd| |n|}t| jjd	r| jjjrd}|
j
d }t|| jjd
d| jjdd| jjdd| jjdd}t| j||||d\}}tt	||| jj  d}t	|| _| jdu ri | _| jd | j|d}t |D ]\}} | j!rq| | _| "|
j
d #|
j}!| j$d | j|
|!d |||ddd }"W d   n	1 s-w   Y  |rc| j$d | j|
|!d |||ddd }#W d   n	1 sVw   Y  |#||"|#   }"|
j}$| jj%|"| |
ddd }
|
j|$krt&j'j() r|
#|$}
|duri }%|D ]
}&t* |& |%|&< q|| || |%}'|'+d|
}
|'+d|}|t	|d ks|d |kr|d | jj dkr|,  t-rt./  qW d   n	1 sw   Y  d| _|dkr|
}(n'| 0|
||| j}
|
| j1jj2 | j1jj3 }
| j1j4|
ddd }(| j5j6|(|d}(| 7  |s|(fS t8|(dS )aO  
        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
                not greater than `1`).
            guidance_scale (`float`, *optional*, defaults to 1.0):
                True classifier-free guidance (guidance scale) is enabled when `guidance_scale` > 1 and
                `negative_prompt` is provided.
            height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
                The height in pixels of the generated image. This is set to 1024 by default for the best results.
            width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
                The width in pixels of the generated image. This is set to 1024 by default for the best results.
            num_inference_steps (`int`, *optional*, defaults to 50):
                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.
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            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.FloatTensor`, *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 be generated by sampling using the supplied random `generator`.
            prompt_embeds (`torch.FloatTensor`, *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.FloatTensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            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.flux.FluxPipelineOutput`] instead of a plain tuple.
            joint_attention_kwargs (`dict`, *optional*):
                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.
            max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.

        Examples:

        Returns:
            [`~pipelines.ovis_image.OvisImagePipelineOutput`] or `tuple`:
            [`~pipelines.ovis_image.OvisImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
            returning a tuple, the first element is a list with the generated images.
        )r   r7   r   r   r   NFr   r   )rM   r7   r$   r\   r   g      ?use_flow_sigmasbase_image_seq_lenr   max_image_seq_lenr   r   r   r   r   )r&   r    )totalcondi  )hidden_statestimestepencoder_hidden_statestxt_idsimg_idsr   uncond)r   r6   r7   latent)r   )images)9rJ   r=   r   r   r   r   rT   rU   r   r/   rj   rg   rz   r;   rD   in_channelsr   r]   nplinspacehasattrr0   r   r"   getr4   maxorderr   r   set_begin_indexprogress_bar	enumerater   expandrh   cache_contextsteprv   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   r8   scaling_factorshift_factordecoderF   postprocessmaybe_free_model_hooksr   ))rK   rM   r   r   r   r   r#   r&   r\   r   r6   r7   r   r   r   r   r   r   r   rm   r$   do_classifier_free_guidancery   negative_text_idsr   r   r   r    r%   num_warmup_stepsr   itr   
noise_predneg_noise_predlatents_dtypecallback_kwargsr   callback_outputsimager   r   r!   __call__  s  \

	




	

68

zOvisImagePipeline.__call__r   )Nr   NN)Nr   N)NNNNN).__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr|   r
   r   r   r   r	   rA   rU   r   r[   r   rv   r$   r]   rr   FloatTensorrz   r   staticmethodr   r   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGfloat	Generatorbooldictr   r   r   __classcell__r   r   rL   r!   r5      s    



*

)
+



#







	
r5   )r   r   r   r   )NNNN),r)   typingr   r   numpyr   rv   transformersr   r   rF   r   modelsr   r	   
schedulersr
   utilsr   r   r   utils.torch_utilsr   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr   r   r   r   r   r"   rU   r$   r   r4   r5   r   r   r   r!   <module>   s^   





;