Skip to content

Official repository for LTX-Video

Pipeline: Support prompt enhancement

Yoav HaCohene7ec4d044598
diff --git a/inference.py b/inference.py
index ad1f60b..105bf2a 100644
--- a/inference.py
+++ b/inference.py
@@ -3,14 +3,20 @@ import os
import random
from datetime import datetime
from pathlib import Path
-from typing import List, Optional, Union
+from diffusers.utils import logging
+from typing import Optional, List, Union
import imageio
import numpy as np
import torch
-from diffusers.utils import logging
from PIL import Image
-from transformers import T5EncoderModel, T5Tokenizer
+from transformers import (
+ T5EncoderModel,
+ T5Tokenizer,
+ AutoModelForCausalLM,
+ AutoProcessor,
+ AutoTokenizer,
+)
from ltx_video.models.autoencoders.causal_video_autoencoder import (
CausalVideoAutoencoder,
@@ -265,13 +271,13 @@ def main():
parser.add_argument(
"--decode_timestep",
type=float,
- default=0.05,
+ default=0.025,
help="Timestep for decoding noise",
)
parser.add_argument(
"--decode_noise_scale",
type=float,
- default=0.025,
+ default=0.0125,
help="Noise level for decoding noise",
)
@@ -328,6 +334,26 @@ def main():
help="Sampler to use for noise scheduling. Can be either 'uniform' or 'linear-quadratic'. If not specified, uses the sampler from the checkpoint.",
)
+ # Prompt enhancement
+ parser.add_argument(
+ "--prompt_enhancement_words_threshold",
+ type=int,
+ default=50,
+ help="Enable prompt enhancement only if input prompt has fewer words than this threshold. Set to 0 to disable enhancement completely.",
+ )
+ parser.add_argument(
+ "--prompt_enhancer_image_caption_model_name_or_path",
+ type=str,
+ default="MiaoshouAI/Florence-2-large-PromptGen-v2.0",
+ help="Path to the image caption model",
+ )
+ parser.add_argument(
+ "--prompt_enhancer_llm_model_name_or_path",
+ type=str,
+ default="unsloth/Llama-3.2-3B-Instruct",
+ help="Path to the LLM model, default is Llama-3.2-3B-Instruct, but you can use other models like Llama-3.1-8B-Instruct, or other models supported by Hugging Face",
+ )
+
args = parser.parse_args()
logger.warning(f"Running generation with arguments: {args}")
infer(**vars(args))
@@ -339,6 +365,9 @@ def create_ltx_video_pipeline(
text_encoder_model_name_or_path: str,
sampler: Optional[str] = None,
device: Optional[str] = None,
+ enhance_prompt: bool = False,
+ prompt_enhancer_image_caption_model_name_or_path: Optional[str] = None,
+ prompt_enhancer_llm_model_name_or_path: Optional[str] = None,
) -> LTXVideoPipeline:
ckpt_path = Path(ckpt_path)
assert os.path.exists(
@@ -367,6 +396,26 @@ def create_ltx_video_pipeline(
vae = vae.to(device)
text_encoder = text_encoder.to(device)
+ if enhance_prompt:
+ prompt_enhancer_image_caption_model = AutoModelForCausalLM.from_pretrained(
+ prompt_enhancer_image_caption_model_name_or_path, trust_remote_code=True
+ )
+ prompt_enhancer_image_caption_processor = AutoProcessor.from_pretrained(
+ prompt_enhancer_image_caption_model_name_or_path, trust_remote_code=True
+ )
+ prompt_enhancer_llm_model = AutoModelForCausalLM.from_pretrained(
+ prompt_enhancer_llm_model_name_or_path,
+ torch_dtype="bfloat16",
+ )
+ prompt_enhancer_llm_tokenizer = AutoTokenizer.from_pretrained(
+ prompt_enhancer_llm_model_name_or_path,
+ )
+ else:
+ prompt_enhancer_image_caption_model = None
+ prompt_enhancer_image_caption_processor = None
+ prompt_enhancer_llm_model = None
+ prompt_enhancer_llm_tokenizer = None
+
vae = vae.to(torch.bfloat16)
if precision == "bfloat16" and transformer.dtype != torch.bfloat16:
transformer = transformer.to(torch.bfloat16)
@@ -380,6 +429,10 @@ def create_ltx_video_pipeline(
"tokenizer": tokenizer,
"scheduler": scheduler,
"vae": vae,
+ "prompt_enhancer_image_caption_model": prompt_enhancer_image_caption_model,
+ "prompt_enhancer_image_caption_processor": prompt_enhancer_image_caption_processor,
+ "prompt_enhancer_llm_model": prompt_enhancer_llm_model,
+ "prompt_enhancer_llm_tokenizer": prompt_enhancer_llm_tokenizer,
}
pipeline = LTXVideoPipeline(**submodel_dict)
@@ -415,6 +468,9 @@ def infer(
conditioning_start_frames: Optional[List[int]] = None,
sampler: Optional[str] = None,
device: Optional[str] = None,
+ prompt_enhancement_words_threshold: int = 50,
+ prompt_enhancer_image_caption_model_name_or_path: str = "MiaoshouAI/Florence-2-large-PromptGen-v2.0",
+ prompt_enhancer_llm_model_name_or_path: str = "unsloth/Llama-3.2-3B-Instruct",
**kwargs,
):
if kwargs.get("input_image_path", None):
@@ -476,12 +532,26 @@ def infer(
f"Padded dimensions: {height_padded}x{width_padded}x{num_frames_padded}"
)
+ prompt_word_count = len(prompt.split())
+ enhance_prompt = (
+ prompt_enhancement_words_threshold > 0
+ and prompt_word_count < prompt_enhancement_words_threshold
+ )
+
+ if prompt_enhancement_words_threshold > 0 and not enhance_prompt:
+ logger.info(
+ f"Prompt has {prompt_word_count} words, which exceeds the threshold of {prompt_enhancement_words_threshold}. Prompt enhancement disabled."
+ )
+
pipeline = create_ltx_video_pipeline(
ckpt_path=ckpt_path,
precision=precision,
text_encoder_model_name_or_path=text_encoder_model_name_or_path,
sampler=sampler,
device=kwargs.get("device", get_device()),
+ enhance_prompt=enhance_prompt,
+ prompt_enhancer_image_caption_model_name_or_path=prompt_enhancer_image_caption_model_name_or_path,
+ prompt_enhancer_llm_model_name_or_path=prompt_enhancer_llm_model_name_or_path,
)
conditioning_items = (
@@ -549,6 +619,7 @@ def infer(
mixed_precision=(precision == "mixed_precision"),
offload_to_cpu=offload_to_cpu,
device=device,
+ enhance_prompt=enhance_prompt,
).images
# Crop the padded images to the desired resolution and number of frames
diff --git a/ltx_video/pipelines/pipeline_ltx_video.py b/ltx_video/pipelines/pipeline_ltx_video.py
index d4b4d72..01b23e8 100644
--- a/ltx_video/pipelines/pipeline_ltx_video.py
+++ b/ltx_video/pipelines/pipeline_ltx_video.py
@@ -15,7 +15,13 @@ from diffusers.schedulers import DPMSolverMultistepScheduler
from diffusers.utils import deprecate, logging
from diffusers.utils.torch_utils import randn_tensor
from einops import rearrange
-from transformers import T5EncoderModel, T5Tokenizer
+from transformers import (
+ T5EncoderModel,
+ T5Tokenizer,
+ AutoModelForCausalLM,
+ AutoProcessor,
+ AutoTokenizer,
+)
from ltx_video.models.autoencoders.causal_video_autoencoder import (
CausalVideoAutoencoder,
@@ -30,6 +36,7 @@ from ltx_video.models.transformers.symmetric_patchifier import Patchifier
from ltx_video.models.transformers.transformer3d import Transformer3DModel
from ltx_video.schedulers.rf import TimestepShifter
from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
+from ltx_video.utils.prompt_enhance_utils import generate_cinematic_prompt
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@@ -208,8 +215,15 @@ class LTXVideoPipeline(DiffusionPipeline):
+ r"]{1,}"
) # noqa
- _optional_components = ["tokenizer", "text_encoder"]
- model_cpu_offload_seq = "text_encoder->transformer->vae"
+ _optional_components = [
+ "tokenizer",
+ "text_encoder",
+ "prompt_enhancer_image_caption_model",
+ "prompt_enhancer_image_caption_processor",
+ "prompt_enhancer_llm_model",
+ "prompt_enhancer_llm_tokenizer",
+ ]
+ model_cpu_offload_seq = "prompt_enhancer_image_caption_model->prompt_enhancer_llm_model->text_encoder->transformer->vae"
def __init__(
self,
@@ -219,6 +233,10 @@ class LTXVideoPipeline(DiffusionPipeline):
transformer: Transformer3DModel,
scheduler: DPMSolverMultistepScheduler,
patchifier: Patchifier,
+ prompt_enhancer_image_caption_model: AutoModelForCausalLM,
+ prompt_enhancer_image_caption_processor: AutoProcessor,
+ prompt_enhancer_llm_model: AutoModelForCausalLM,
+ prompt_enhancer_llm_tokenizer: AutoTokenizer,
):
super().__init__()
@@ -229,6 +247,10 @@ class LTXVideoPipeline(DiffusionPipeline):
transformer=transformer,
scheduler=scheduler,
patchifier=patchifier,
+ prompt_enhancer_image_caption_model=prompt_enhancer_image_caption_model,
+ prompt_enhancer_image_caption_processor=prompt_enhancer_image_caption_processor,
+ prompt_enhancer_llm_model=prompt_enhancer_llm_model,
+ prompt_enhancer_llm_tokenizer=prompt_enhancer_llm_tokenizer,
)
self.video_scale_factor, self.vae_scale_factor, _ = get_vae_size_scale_factor(
@@ -256,6 +278,7 @@ class LTXVideoPipeline(DiffusionPipeline):
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
prompt_attention_mask: Optional[torch.FloatTensor] = None,
negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
+ text_encoder_max_tokens: int = 256,
**kwargs,
):
r"""
@@ -296,8 +319,9 @@ class LTXVideoPipeline(DiffusionPipeline):
batch_size = prompt_embeds.shape[0]
# See Section 3.1. of the paper.
- # FIXME: to be configured in config not hardecoded. Fix in separate PR with rest of config
- max_length = 256 # TPU supports only lengths multiple of 128
+ max_length = (
+ text_encoder_max_tokens # TPU supports only lengths multiple of 128
+ )
if prompt_embeds is None:
assert (
self.text_encoder is not None
@@ -446,6 +470,7 @@ class LTXVideoPipeline(DiffusionPipeline):
negative_prompt_embeds=None,
prompt_attention_mask=None,
negative_prompt_attention_mask=None,
+ enhance_prompt=False,
):
if height % 8 != 0 or width % 8 != 0:
raise ValueError(
@@ -507,6 +532,20 @@ class LTXVideoPipeline(DiffusionPipeline):
f" {negative_prompt_attention_mask.shape}."
)
+ if enhance_prompt:
+ assert (
+ self.prompt_enhancer_image_caption_model is not None
+ ), "Image caption model must be initialized if enhance_prompt is True"
+ assert (
+ self.prompt_enhancer_image_caption_processor is not None
+ ), "Image caption processor must be initialized if enhance_prompt is True"
+ assert (
+ self.prompt_enhancer_llm_model is not None
+ ), "Text prompt enhancer model must be initialized if enhance_prompt is True"
+ assert (
+ self.prompt_enhancer_llm_tokenizer is not None
+ ), "Text prompt enhancer tokenizer must be initialized if enhance_prompt is True"
+
def _text_preprocessing(self, text):
if not isinstance(text, (tuple, list)):
text = [text]
@@ -642,6 +681,8 @@ class LTXVideoPipeline(DiffusionPipeline):
decode_noise_scale: Optional[List[float]] = None,
mixed_precision: bool = False,
offload_to_cpu: bool = False,
+ enhance_prompt: bool = False,
+ text_encoder_max_tokens: int = 256,
**kwargs,
) -> Union[ImagePipelineOutput, Tuple]:
"""
@@ -706,6 +747,10 @@ class LTXVideoPipeline(DiffusionPipeline):
If set to `True`, the requested height and width are first mapped to the closest resolutions using
`ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
the requested resolution. Useful for generating non-square images.
+ enhance_prompt (`bool`, *optional*, defaults to `False`):
+ If set to `True`, the prompt is enhanced using a LLM model.
+ text_encoder_max_tokens (`int`, *optional*, defaults to `256`):
+ The maximum number of tokens to use for the text encoder.
Examples:
@@ -765,6 +810,24 @@ class LTXVideoPipeline(DiffusionPipeline):
batch_size, num_conds, 2, skip_block_list
)
+ if enhance_prompt:
+ self.prompt_enhancer_image_caption_model = (
+ self.prompt_enhancer_image_caption_model.to(self._execution_device)
+ )
+ self.prompt_enhancer_llm_model = self.prompt_enhancer_llm_model.to(
+ self._execution_device
+ )
+
+ prompt = generate_cinematic_prompt(
+ self.prompt_enhancer_image_caption_model,
+ self.prompt_enhancer_image_caption_processor,
+ self.prompt_enhancer_llm_model,
+ self.prompt_enhancer_llm_tokenizer,
+ prompt,
+ conditioning_items,
+ max_new_tokens=text_encoder_max_tokens,
+ )
+
# 3. Encode input prompt
if self.text_encoder is not None:
self.text_encoder = self.text_encoder.to(self._execution_device)
@@ -784,6 +847,7 @@ class LTXVideoPipeline(DiffusionPipeline):
negative_prompt_embeds=negative_prompt_embeds,
prompt_attention_mask=prompt_attention_mask,
negative_prompt_attention_mask=negative_prompt_attention_mask,
+ text_encoder_max_tokens=text_encoder_max_tokens,
)
if offload_to_cpu and self.text_encoder is not None:
diff --git a/ltx_video/utils/prompt_enhance_utils.py b/ltx_video/utils/prompt_enhance_utils.py
new file mode 100644
index 0000000..9010517
--- /dev/null
+++ b/ltx_video/utils/prompt_enhance_utils.py
@@ -0,0 +1,226 @@
+import logging
+from typing import Union, List, Optional
+
+import torch
+from PIL import Image
+
+logger = logging.getLogger(__name__) # pylint: disable=invalid-name
+
+T2V_CINEMATIC_PROMPT = """You are an expert cinematic director with many award winning movies, When writing prompts based on the user input, focus on detailed, chronological descriptions of actions and scenes.
+Include specific movements, appearances, camera angles, and environmental details - all in a single flowing paragraph.
+Start directly with the action, and keep descriptions literal and precise.
+Think like a cinematographer describing a shot list.
+Do not change the user input intent, just enhance it.
+Keep within 150 words.
+For best results, build your prompts using this structure:
+Start with main action in a single sentence
+Add specific details about movements and gestures
+Describe character/object appearances precisely
+Include background and environment details
+Specify camera angles and movements
+Describe lighting and colors
+Note any changes or sudden events
+Do not exceed the 150 word limit!
+Output the enhanced prompt only.
+"""
+
+I2V_CINEMATIC_PROMPT = """You are an expert cinematic director with many award winning movies, When writing prompts based on the user input, focus on detailed, chronological descriptions of actions and scenes.
+Include specific movements, appearances, camera angles, and environmental details - all in a single flowing paragraph.
+Start directly with the action, and keep descriptions literal and precise.
+Think like a cinematographer describing a shot list.
+Keep within 150 words.
+For best results, build your prompts using this structure:
+Describe the image first and then add the user input. Image description should be in first priority! Align to the image caption if it contradicts the user text input.
+Start with main action in a single sentence
+Add specific details about movements and gestures
+Describe character/object appearances precisely
+Include background and environment details
+Specify camera angles and movements
+Describe lighting and colors
+Note any changes or sudden events
+Align to the image caption if it contradicts the user text input.
+Do not exceed the 150 word limit!
+Output the enhanced prompt only.
+"""
+
+
+def tensor_to_pil(tensor):
+ # Ensure tensor is in range [-1, 1]
+ assert tensor.min() >= -1 and tensor.max() <= 1
+
+ # Convert from [-1, 1] to [0, 1]
+ tensor = (tensor + 1) / 2
+
+ # Rearrange from [C, H, W] to [H, W, C]
+ tensor = tensor.permute(1, 2, 0)
+
+ # Convert to numpy array and then to uint8 range [0, 255]
+ numpy_image = (tensor.cpu().numpy() * 255).astype("uint8")
+
+ # Convert to PIL Image
+ return Image.fromarray(numpy_image)
+
+
+def generate_cinematic_prompt(
+ image_caption_model,
+ image_caption_processor,
+ prompt_enhancer_model,
+ prompt_enhancer_tokenizer,
+ prompt: Union[str, List[str]],
+ conditioning_items: Optional[List] = None,
+ max_new_tokens: int = 256,
+) -> List[str]:
+ prompts = [prompt] if isinstance(prompt, str) else prompt
+
+ if conditioning_items is None:
+ prompts = _generate_t2v_prompt(
+ prompt_enhancer_model,
+ prompt_enhancer_tokenizer,
+ prompts,
+ max_new_tokens,
+ T2V_CINEMATIC_PROMPT,
+ )
+ else:
+ if len(conditioning_items) > 1 or conditioning_items[0].media_frame_number != 0:
+ logger.warning(
+ "prompt enhancement does only support unconditional or first frame of conditioning items, returning original prompts"
+ )
+ return prompts
+
+ first_frame_conditioning_item = conditioning_items[0]
+ first_frames = _get_first_frames_from_conditioning_item(
+ first_frame_conditioning_item
+ )
+
+ assert len(first_frames) == len(
+ prompts
+ ), "Number of conditioning frames must match number of prompts"
+
+ prompts = _generate_i2v_prompt(
+ image_caption_model,
+ image_caption_processor,
+ prompt_enhancer_model,
+ prompt_enhancer_tokenizer,
+ prompts,
+ first_frames,
+ max_new_tokens,
+ I2V_CINEMATIC_PROMPT,
+ )
+
+ return prompts
+
+
+def _get_first_frames_from_conditioning_item(conditioning_item) -> List[Image.Image]:
+ frames_tensor = conditioning_item.media_item
+ return [
+ tensor_to_pil(frames_tensor[i, :, 0, :, :])
+ for i in range(frames_tensor.shape[0])
+ ]
+
+
+def _generate_t2v_prompt(
+ prompt_enhancer_model,
+ prompt_enhancer_tokenizer,
+ prompts: List[str],
+ max_new_tokens: int,
+ system_prompt: str,
+) -> List[str]:
+ messages = [
+ [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": f"user_prompt: {p}"},
+ ]
+ for p in prompts
+ ]
+
+ texts = [
+ prompt_enhancer_tokenizer.apply_chat_template(
+ m, tokenize=False, add_generation_prompt=True
+ )
+ for m in messages
+ ]
+ model_inputs = prompt_enhancer_tokenizer(texts, return_tensors="pt").to(
+ prompt_enhancer_model.device
+ )
+
+ return _generate_and_decode_prompts(
+ prompt_enhancer_model, prompt_enhancer_tokenizer, model_inputs, max_new_tokens
+ )
+
+
+def _generate_i2v_prompt(
+ image_caption_model,
+ image_caption_processor,
+ prompt_enhancer_model,
+ prompt_enhancer_tokenizer,
+ prompts: List[str],
+ first_frames: List[Image.Image],
+ max_new_tokens: int,
+ system_prompt: str,
+) -> List[str]:
+ image_captions = _generate_image_captions(
+ image_caption_model, image_caption_processor, first_frames
+ )
+
+ messages = [
+ [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": f"user_prompt: {p}\nimage_caption: {c}"},
+ ]
+ for p, c in zip(prompts, image_captions)
+ ]
+
+ texts = [
+ prompt_enhancer_tokenizer.apply_chat_template(
+ m, tokenize=False, add_generation_prompt=True
+ )
+ for m in messages
+ ]
+ model_inputs = prompt_enhancer_tokenizer(texts, return_tensors="pt").to(
+ prompt_enhancer_model.device
+ )
+
+ return _generate_and_decode_prompts(
+ prompt_enhancer_model, prompt_enhancer_tokenizer, model_inputs, max_new_tokens
+ )
+
+
+def _generate_image_captions(
+ image_caption_model,
+ image_caption_processor,
+ images: List[Image.Image],
+ system_prompt: str = "<DETAILED_CAPTION>",
+) -> List[str]:
+ image_caption_prompts = [system_prompt] * len(images)
+ inputs = image_caption_processor(
+ image_caption_prompts, images, return_tensors="pt"
+ ).to(image_caption_model.device)
+
+ with torch.inference_mode():
+ generated_ids = image_caption_model.generate(
+ input_ids=inputs["input_ids"],
+ pixel_values=inputs["pixel_values"],
+ max_new_tokens=1024,
+ do_sample=False,
+ num_beams=3,
+ )
+
+ return image_caption_processor.batch_decode(generated_ids, skip_special_tokens=True)
+
+
+def _generate_and_decode_prompts(
+ prompt_enhancer_model, prompt_enhancer_tokenizer, model_inputs, max_new_tokens: int
+) -> List[str]:
+ with torch.inference_mode():
+ outputs = prompt_enhancer_model.generate(
+ **model_inputs, max_new_tokens=max_new_tokens
+ )
+ generated_ids = [
+ output_ids[len(input_ids) :]
+ for input_ids, output_ids in zip(model_inputs.input_ids, outputs)
+ ]
+ decoded_prompts = prompt_enhancer_tokenizer.batch_decode(
+ generated_ids, skip_special_tokens=True
+ )
+
+ return decoded_prompts
diff --git a/pyproject.toml b/pyproject.toml
index e45f120..5452a4d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -18,10 +18,11 @@ classifiers = [
dependencies = [
"torch>=2.1.0",
"diffusers>=0.28.2",
- "transformers>=4.44.2",
+ "transformers>=4.47.2",
"sentencepiece>=0.1.96",
"huggingface-hub~=0.25.2",
- "einops"
+ "einops",
+ "timm"
]
[project.optional-dependencies]
diff --git a/tests/test_inference.py b/tests/test_inference.py
index 7a76695..cc6789e 100644
--- a/tests/test_inference.py
+++ b/tests/test_inference.py
@@ -63,7 +63,15 @@ def test_infer_runs_on_real_path(test_paths, conditioning_test_mode):
"prompt": "A young woman with wavy, shoulder-length light brown hair stands outdoors on a foggy day. She wears a cozy pink turtleneck sweater, with a serene expression and piercing blue eyes. A wooden fence and a misty, grassy field fade into the background, evoking a calm and introspective mood.",
"negative_prompt": "worst quality, inconsistent motion, blurry, jittery, distorted",
"offload_to_cpu": False,
+ "prompt_enhancement_max_words": 1000,
+ "prompt_enhancer_image_caption_model_name_or_path": "MiaoshouAI/Florence-2-large-PromptGen-v2.0",
+ "prompt_enhancer_llm_model_name_or_path": "unsloth/Llama-3.2-3B-Instruct",
}
+
+ infer(**{**conditioning_params, **test_paths, **params})
+
+ # test without prompt enhancement
+ params["prompt_enhancement_max_words"] = 0
infer(**{**conditioning_params, **test_paths, **params})
@@ -91,6 +99,9 @@ def test_pipeline_on_batch(test_paths):
device=device,
precision="bfloat16",
text_encoder_model_name_or_path=test_paths["text_encoder_model_name_or_path"],
+ enhance_prompt=True,
+ prompt_enhancer_image_caption_model_name_or_path="MiaoshouAI/Florence-2-large-PromptGen-v2.0",
+ prompt_enhancer_llm_model_name_or_path="unsloth/Llama-3.2-3B-Instruct",
)
params = {
@@ -153,3 +164,84 @@ def test_pipeline_on_batch(test_paths):
print(f"Mean absolute difference: {mad}")
assert torch.allclose(image2_not_same, image2_same)
+
+
+def test_prompt_enhancement(test_paths, monkeypatch):
+ # Create pipeline with prompt enhancement enabled
+ device = get_device()
+ pipeline = create_ltx_video_pipeline(
+ ckpt_path=test_paths["ckpt_path"],
+ device=device,
+ precision="bfloat16",
+ text_encoder_model_name_or_path=test_paths["text_encoder_model_name_or_path"],
+ enhance_prompt=True,
+ prompt_enhancer_image_caption_model_name_or_path="MiaoshouAI/Florence-2-large-PromptGen-v2.0",
+ prompt_enhancer_llm_model_name_or_path="unsloth/Llama-3.2-3B-Instruct",
+ )
+
+ original_prompt = "A cat sitting on a windowsill"
+
+ # Mock the pipeline's _encode_prompt method to verify the prompt being used
+ original_encode_prompt = pipeline.encode_prompt
+
+ prompts_used = []
+
+ def mock_encode_prompt(prompt, *args, **kwargs):
+ prompts_used.append(prompt[0] if isinstance(prompt, list) else prompt)
+ return original_encode_prompt(prompt, *args, **kwargs)
+
+ pipeline.encode_prompt = mock_encode_prompt
+
+ # Set up minimal parameters for a quick test
+ params = {
+ "seed": 42,
+ "num_inference_steps": 1,
+ "num_images_per_prompt": 1,
+ "guidance_scale": 2.5,
+ "do_rescaling": True,
+ "stg_scale": 1,
+ "rescaling_scale": 0.7,
+ "skip_layer_strategy": SkipLayerStrategy.AttentionValues,
+ "skip_block_list": [1, 2],
+ "image_cond_noise_scale": 0.15,
+ "height": 288,
+ "width": 512,
+ "num_frames": 1,
+ "frame_rate": 25,
+ "decode_timestep": 0.05,
+ "decode_noise_scale": 0.025,
+ "offload_to_cpu": False,
+ "output_type": "pt",
+ "is_video": False,
+ "vae_per_channel_normalize": True,
+ "mixed_precision": False,
+ }
+
+ # Run pipeline with prompt enhancement enabled
+ _ = pipeline(
+ prompt=original_prompt,
+ negative_prompt="worst quality",
+ enhance_prompt=True,
+ **params,
+ )
+
+ # Verify that the enhanced prompt was used
+ assert len(prompts_used) > 0
+ assert (
+ prompts_used[0] != original_prompt
+ ), f"Expected enhanced prompt to be different from original prompt, but got: {original_prompt}"
+
+ # Run pipeline with prompt enhancement disabled
+ prompts_used.clear()
+ _ = pipeline(
+ prompt=original_prompt,
+ negative_prompt="worst quality",
+ enhance_prompt=False,
+ **params,
+ )
+
+ # Verify that the original prompt was used
+ assert len(prompts_used) > 0
+ assert (
+ prompts_used[0] == original_prompt
+ ), f"Expected original prompt to be used, but got: {prompts_used[0]}"