Diffusers documentation
Qwen-Image 2.1
Qwen-Image 2.1
Qwen-Image 2.1은 프롬프트와 조건 이미지를 Qwen3-VL 모델과 함께 인코딩한 후, 단일 스트림 블록-인과적(block-causal) 트랜스포머를 사용하여 대상 이미지를 디노이즈합니다. 블록-인과적 어텐션, 어텐션 프로세서 및 causal_condition에 대한 자세한 내용은 QwenImage21Transformer2DModel을 참조하세요.
기본값은 Qwen이 권장하는 값인 40단계와 가이던스 없음입니다. negative_prompt를 true_cfg_scale > 1과 함께 전달하면 classifier-free guidance가 활성화되며, 이는 단계당 작업량을 두 배로 증가시킵니다.
import torch
from diffusers import QwenImage21Pipeline
pipe = QwenImage21Pipeline.from_pretrained("Qwen/Qwen-Image-2.1", dtype=torch.bfloat16).to("cuda")
# Text-to-image
image = pipe("A capybara wearing a wizard hat, oil painting").images[0]
image.save("t2i.png")
# Image-conditioned editing
edited = pipe("Move it to a snowy mountain top", image=image).images[0]
edited.save("edit.png")여러 조건 이미지
image에 리스트를 전달하면 모든 항목이 결합된 시퀀스에서 각자의 블록이 됩니다. Qwen3-VL 인코더는 이를 비전 컨텍스트로 인식하고, VAE는 해당 잠재 토큰을 기여합니다. 블록 인과적 어텐션은 각 블록 내부에서는 양방향 어텐션을 허용하면서, 후속 블록과 대상 이미지가 이전 블록에 어텐션할 수 있게 합니다. 따라서 전달하는 순서가 모델이 읽는 순서가 됩니다.
edited = pipe("Put the flowers from the first image into the second scene", image=[flowers, scene]).images[0]flex_attention으로 더 빠른 attention
기본 QwenImage21AttnProcessor는 각 prefix 세그먼트마다 attention 호출을 한 번씩 실행하여 block-causal prefill을 수행합니다. 컴파일이 필요하지 않으며 모든 PyTorch 빌드에서 작동합니다. QwenImage21FlexAttnProcessor는 동일한 마스크를 flex_attention 호출 하나로 표현하며, 모델이 컴파일된 후에는 더 빠릅니다.
flex 프로세서로 전환할 때 모델을 컴파일하세요. 컴파일되지 않은
flex_attention은 fp32로 전체 어텐션 점수 행렬을 생성하여, 고해상도에서 훨씬 느려지고 메모리가 부족해집니다.
from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21FlexAttnProcessor
pipe.transformer.set_attn_processor(QwenImage21FlexAttnProcessor())
pipe.transformer.compile()단일 파일 체크포인트 로드
import torch
from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel
transformer = QwenImage21Transformer2DModel.from_single_file(
"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/blob/main/diffusion_models/qwen_image_2.1_bf16.safetensors",
dtype=torch.bfloat16,
)
pipe = QwenImage21Pipeline.from_pretrained("Qwen/Qwen-Image-2.1", transformer=transformer, dtype=torch.bfloat16).to(
"cuda"
)샘플링 시그마
모델 작성자는 파이프라인 설정에서 sample_sigmas를 사용하여 기본 샘플링 그리드를 구성할 수 있습니다. 공개된 체크포인트를 로드하면 해당 체크포인트의 기본 그리드 및 스케줄러 설정이 자동으로 복원됩니다.
런타임에서 다른 그리드를 실험하려면 sigmas를 파이프라인 호출에 전달하세요:
# Use the checkpoint's default sampling grid.
image = pipe(prompt).images[0]
# Override the default grid for this call.
image = pipe(prompt, sigmas=[1.0, 0.8, 0.5, 0.2]).images[0]위의 사용자 정의 그리드는 API를 보여줍니다. 생성 품질은 체크포인트와 그리드에 따라 달라집니다. Sigma 목록에는 스케줄러가 추가하는 최종 sigma가 제외됩니다. 명시적으로 지정된 sigmas는 구성된 sample_sigmas를 덮어쓰며, 이 두 목록 중 어느 것이든 num_inference_steps 대신 단계 수를 결정합니다. 둘 다 제공되지 않으면 파이프라인은 num_inference_steps를 사용하여 스케줄을 생성합니다. 스케줄러는 구성된 처리를 두 그리드 중 어느 것에든 적용합니다.
모듈형
Qwen-Image 2.1은 모듈형 파이프라인으로도 사용할 수 있습니다. 동일한 블록이 텍스트-이미지 생성과 이미지 조건 생성을 수행하며, 하나 이상의 이미지에 조건을 걸려면 image를 전달합니다. Classifier-free guidance는 true_cfg_scale 호출 인수가 아닌 guider 구성 요소를 통해 설정되며, prefix KV 캐시는 기본적으로 활성화되어 있습니다(use_kv_cache=False로 비활성화할 수 있음).
import torch
from diffusers import ClassifierFreeGuidance, ModularPipeline
pipe = ModularPipeline.from_pretrained("Qwen/Qwen-Image-2.1")
pipe.load_components(dtype=torch.bfloat16)
pipe.to("cuda")
image = pipe(prompt="A capybara wearing a wizard hat, oil painting").images[0]
# Turn classifier-free guidance on for an edit.
pipe.update_components(guider=ClassifierFreeGuidance(guidance_scale=4.0))
edited = pipe(prompt="Move it to a snowy mountain top", negative_prompt="blurry", image=image).images[0]Turbo 체크포인트는 자체 블록(QwenImage21TurboAutoBlocks)에 매핑됩니다. guider 없이 실행되며, negative_prompt를 받지 않고, 체크포인트에 포함된 시그마 그리드를 샘플링합니다. ModularPipeline.from_pretrained는 체크포인트 설정의 sample_sigmas 항목에서 Turbo 블록을 선택하므로, 별도의 구성이 필요하지 않습니다:
import torch
from diffusers import ModularPipeline
pipe = ModularPipeline.from_pretrained("Qwen/Qwen-Image-2.1-Turbo")
pipe.load_components(dtype=torch.bfloat16)
pipe.to("cuda")
image = pipe(prompt="A capybara wearing a wizard hat, oil painting").images[0]QwenImage21Pipeline
클래스 diffusers.QwenImage21Pipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLQwenImage21text_encoder: Qwen3VLForConditionalGenerationprocessor: Qwen3VLProcessortransformer: QwenImage21Transformer2DModelsample_sigmas: list[float] | None = None )
매개변수
- scheduler (FlowMatchEulerDiscreteScheduler) — 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
- vae (AutoencoderKLQwenImage21) — 이미지를 64채널 잠재 공간으로 변환하고 역변환하는 변분 오토인코더.
- text_encoder (
Qwen3VLForConditionalGeneration) — 텍스트/이미지 결합 임베딩을 생성하는 Qwen3-VL 모델. - processor (
Qwen3VLProcessor) — 채팅 템플릿을 구성하고 프롬프트 및 조건 이미지를 토큰화하는 프로세서입니다. - transformer (QwenImage21Transformer2DModel) — Latents를 디노이즈하는 단일 스트림 블록 인과적 transformer입니다.
- sample_sigmas (
list[float], 선택 사항) — 모델 작성자가 설정한 기본 샘플링 시그마이며, 최종 시그마는 제외됩니다. 이 목록의 길이는 디노이징 단계 수를 결정합니다. 런타임에서 다른 그리드를 실험하려면sigmas를__call__에 전달하세요.
Qwen-Image 2.1을 활용한 텍스트-이미지 생성 및 이미지 조건부 생성
Prompt과 condition image는 Qwen3-VL 모델에 의해 함께 인코딩되므로, condition image는 인코더가 해당 이미지를 위해 예약한 vision 슬롯을 차지하며, transformer는 하나의 교차된 텍스트/이미지 시퀀스를 확인합니다.
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonenegative_prompt: str | list[str] = Nonetrue_cfg_scale: float = 1.0height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 40sigmas: list[float] | None = Nonenum_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']output_resolution: int = 1024use_kv_cache: bool = True ) → ~pipelines.qwenimage.QwenImagePipelineOutput or tuple
매개변수
- prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하는 프롬프트입니다. 임베딩을 직접 제공하려면 대신prompt_embeds를 전달하세요. - image (
PipelineImageInput, 선택 사항) — PIL 이미지 또는 numpy 배열 형태의 하나 이상의 조건 이미지입니다. 텍스트 인코더에 의해 비전 컨텍스트로, VAE에 의해 노이즈 앞에 붙는 잠재 토큰으로 인코딩됩니다. 리스트는 배치 내 모든 프롬프트가 공유하는 이미지 한 세트를 의미하며, 프롬프트당 하나의 항목을 의미하지 않습니다. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 유도하지 않을 프롬프트입니다.true_cfg_scale이 1보다 크지 않으면 무시됩니다. - true_cfg_scale (
float, 선택 사항, 기본값 1.0) — Classifier-free guidance scale입니다.true_cfg_scale > 1과 negative prompt를 함께 사용하면 활성화됩니다. Qwen-Image 2.1은 guidance 없이 샘플링하도록 설계되어 기본값이 1.0입니다. - height (
int, 선택 사항) — 생성된 이미지의 픽셀 단위 높이입니다. 생략할 경우 조건 이미지의 종횡비(aspect ratio)에서 유도됩니다. - width (
int, 선택 사항) — 생성된 이미지의 픽셀 단위 너비. 생략하면 조건 이미지의 종횡비에서 유도됩니다. - num_inference_steps (
int, 선택 사항, 기본값 40) — 디노이징 단계 수.sigmas또는 파이프라인에 구성된sample_sigmas가 사용되면 무시됩니다. 해당 스케줄의 길이가 단계 수를 결정합니다. - sigmas (
list[float], 선택 사항) — 이 호출에서 시도할 샘플링 시그마 목록으로, 최종 시그마는 제외됩니다. 파이프라인에 설정된sample_sigmas를 오버라이드하며 디노이징 단계 수를 결정합니다. 스케줄러는 이 값들에 대해 설정된 처리 과정을 적용합니다. - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성되는 이미지의 수. - generator (
torch.Generator또는list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 Generator입니다. - latents (
torch.Tensor, 선택 사항) — 미리 생성된 노이즈가 포함된 latents. - prompt_embeds (
torch.Tensor, 선택 사항) — 프롬프트 인코딩을 건너뛰는 사전 생성된 텍스트 임베딩입니다.prompt_embeds_mask를 함께 전달해야 합니다. - prompt_embeds_mask (
torch.Tensor, 선택 사항) —prompt_embeds의 유효한 위치를 표시하는 Bool 마스크입니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) —negative_prompt대신 사용되는 사전 생성된 negative text embeddings입니다.negative_prompt_embeds_mask를 함께 전달해야 합니다. - negative_prompt_embeds_mask (
torch.Tensor, 선택 사항) —negative_prompt_embeds의 유효한 위치를 표시하는 Bool 마스크입니다. - output_type (
str, 선택 사항, 기본값"pil") — 출력 형식,"pil","np","pt"또는"latent". - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신~pipelines.qwenimage.QwenImagePipelineOutput를 반환할지 여부. - attention_kwargs (
dict, 선택 사항) — attention processor로 전달됩니다. - callback_on_step_end (
Callable, 선택 사항) — 각 디노이징 단계의 끝에서 호출됩니다. - callback_on_step_end_tensor_inputs (
list[str], 선택 사항, 기본값["latents"]) —callback_on_step_end에 전달할 디노이징 루프의 텐서입니다. 파이프라인의_callback_tensor_inputs에 나열되어 있어야 합니다. - output_resolution (
int, 선택 사항, 기본값 1024) —height/width를 유도하고 조건 이미지를 리사이즈하는 데 사용되는 목표 측면 길이입니다. - use_kv_cache (
bool, 선택 사항, 기본값은True) — 첫 번째 단계 이후 텍스트 및 조건 이미지의 키와 값을 캐시합니다.causal_condition가 해당 토큰을t = 0, 으로 변조하여 활성화가 단계에 독립적이 되므로 유효합니다. 이 설정을 전환해도 저정밀도에서 비트 단위로 동일한 이미지를 재현하지 않습니다. 캐싱은 디코딩 단계가 프리필 단계와 다른 시퀀스 레이아웃으로 어텐션을 수행하게 하므로, 두 단계가 다른 방식으로 타일링되고 다른 반올림에 도달합니다. 두 설정 모두 fp32 기준값과 동일한 허용 오차 내에서 일치합니다. 첫 번째 블록의 1-ULP 차이는 32개 블록과 모든 샘플러 단계를 통해 증폭되므로, 두 설정은 동일하게 유효하지만 시각적으로 구별되는 샘플을 생성합니다. 샘플을 고정하려면 이 플래그를 고정하세요.이 옵션을 전환해도 저정밀도에서 동일한 이미지를 비트 단위로 재현하지 않습니다. 캐싱을 사용하면 디코딩 단계가 프리필 단계와 다른 시퀀스 레이아웃으로 어텐션을 수행하므로, 두 단계는 타일링 방식이 달라지고 서로 다른 반올림 결과를 얻습니다. 두 결과 모두 fp32 기준값과 동일한 허용 오차 범위 내에서 일치합니다. 첫 번째 블록에서 발생하는 1-ULP 차이는 32개의 블록과 모든 샘플러 단계를 거치면서 증폭되므로, 두 설정은 모두 유효하지만 시각적으로 구별되는 샘플을 생성합니다. 이 플래그를 고정하면 샘플을 고정할 수 있습니다.
반환값
~pipelines.qwenimage.QwenImagePipelineOutput 또는 tuple
return_dict가 True인 경우 ~pipelines.qwenimage.QwenImagePipelineOutput, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 리스트인 tuple
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> import torch
>>> from diffusers import QwenImage21Pipeline
>>> pipe = QwenImage21Pipeline.from_pretrained("Qwen/Qwen-Image-2.1", dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A capybara wearing a wizard hat, reading a book by candlelight, oil painting"
>>> image = pipe(prompt).images[0]
>>> image.save("qwenimage21.png")encode_prompt
< source >( prompt: str | list[str]image: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_mask: typing.Optional[torch.Tensor] = Noneimage_pad_mask: typing.Optional[torch.Tensor] = None )
QwenImagePipelineOutput
클래스 diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarray )
Stable Diffusion 파이프라인의 출력 클래스입니다.
QwenImage21ModularPipeline
클래스 diffusers.QwenImage21ModularPipeline
< source >( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )
Qwen-Image 2.1용 ModularPipeline.
QwenImage21AutoBlocks
Qwen-Image 2.1을 사용한 텍스트-이미지 변환 및 이미지 조건 생성을 위한 Auto Modular 파이프라인.
- 텍스트-이미지 생성의 경우
prompt만 제공하면 됩니다 - 이미지 조건 생성을 위해
prompt와image(이미지 하나 또는 목록)를 제공해야 합니다
지원되는 워크플로:
text2image:prompt필수image_conditioned:prompt,image필수
구성 요소:
image_processor (VaeImageProcessor) text_encoder (Qwen3VLForConditionalGeneration) processor
(Qwen3VLProcessor) vae (AutoencoderKLQwenImage21) scheduler (FlowMatchEulerDiscreteScheduler) guider
(ClassifierFreeGuidance) transformer (QwenImage21Transformer2DModel)
입력:
image (Image | list, 선택 사항):
디노이징을 위한 참조 이미지입니다. 단일 이미지 또는 이미지 목록일 수 있습니다.
output_resolution (int, 선택 사항, 기본값 1024):
출력 크기를 유도하고 조건 이미지를 리사이즈하는 데 사용되는 목표 측면 길이입니다.
prompt (str):
이미지 생성을 안내하는 프롬프트입니다.
negative_prompt (str, 선택 사항):
이미지 생성을 안내하지 않을 프롬프트입니다.
generator (Generator, 선택 사항):
결정론적 생성을 위한 Torch 생성기입니다.
num_images_per_prompt (int, 선택 사항, 기본값 1):
프롬프트당 생성할 이미지의 수입니다.
height (int, 선택 사항):
생성된 이미지의 픽셀 단위 높이입니다.
width (int, 선택 사항):
생성된 이미지의 픽셀 단위 너비입니다.
image_latents (list, 선택 사항):
각 조건 이미지의 정규화된 잠긴 변수(latents)입니다. vae_encoder 단계에서 생성할 수 있습니다.
latents (Tensor):
이미지 생성을 위한 사전 생성된 노이즈 잠긴 변수입니다.
num_inference_steps (int):
디노이징 단계의 수입니다.
sigmas (list, 선택 사항):
디노이징 프로세스를 위한 사용자 지정 시그마입니다.
use_kv_cache (bool, 선택 사항, 기본값 True):
첫 번째 단계 이후 텍스트 및 조건 이미지의 키와 값을 캐시합니다. causal_condition이 t = 0부터 해당 토큰을 변조하여 활성화가 단계에 독립적이 되므로 유효합니다. 이를 전환해도 감소된 정밀도에서는 비트 단위로 동일한 이미지를 재현하지 않습니다.
attention_kwargs (dict, 선택 사항):
어텐션 프로세서에 대한 추가 kwargs입니다.
*denoiser_input_fields (None,선택 사항):
디노이저의 조건부 모델 입력입니다. 예: prompt_embeds, negative_prompt_embeds 등.
output_type (str,선택 사항*, 기본값 pil):
출력 형식: ‘pil’, ‘np’, ‘pt’.
출력:
images (list):
생성된 이미지.
QwenImage21TurboModularPipeline
클래스 diffusers.QwenImage21TurboModularPipeline
< source >( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )
가이던스 없이 몇 단계 만에 샘플링하는 가속 체크포인트인 Qwen-Image 2.1 Turbo용 ModularPipeline입니다.
QwenImage21TurboAutoBlocks
Qwen-Image 2.1 Turbo를 사용하여 텍스트-이미지 생성 및 이미지 조건 생성을 위한 Auto Modular pipeline입니다. Qwen-Image 2.1 Turbo는 guidance 없이 몇 단계 만에 포함된 sigma grid를 샘플링하는 가속화된 checkpoint입니다.
- 텍스트-이미지 생성의 경우
prompt만 제공하면 됩니다 - 이미지 조건 생성을 위해
prompt와image(이미지 하나 또는 목록)를 제공해야 합니다
지원되는 워크플로:
text2image:prompt필수image_conditioned:prompt,image필수
구성 요소:
image_processor (VaeImageProcessor) text_encoder (Qwen3VLForConditionalGeneration) processor
(Qwen3VLProcessor) vae (AutoencoderKLQwenImage21) scheduler (FlowMatchEulerDiscreteScheduler)
transformer (QwenImage21Transformer2DModel)
Configs:
sample_sigmas (기본값: None): sigmas가 전달되지 않을 때 사용되는, 체크포인트에 포함된 샘플링 그리드
입력:
image (Image | list, 선택 사항):
디노이징을 위한 참조 이미지입니다. 단일 이미지 또는 이미지 목록일 수 있습니다.
output_resolution (int, 선택 사항, 기본값 1024):
출력 크기를 유도하고 조건 이미지를 리사이즈하는 데 사용되는 목표 측면 길이입니다.
prompt (str):
이미지 생성을 안내하는 프롬프트입니다.
generator (Generator, 선택 사항):
결정론적 생성을 위한 Torch generator입니다.
num_images_per_prompt (int, 선택 사항, 기본값 1):
프롬프트당 생성할 이미지의 수입니다.
height (int, 선택 사항):
생성된 이미지의 픽셀 단위 높이입니다.
width (int, 선택 사항):
생성된 이미지의 픽셀 단위 너비입니다.
image_latents (list, 선택 사항):
각 조건 이미지의 정규화된 latents입니다. vae_encoder 단계에서 생성할 수 있습니다.
latents (Tensor):
이미지 생성을 위한 사전 생성된 노이즈 latents입니다.
num_inference_steps (int):
디노이징 단계의 수입니다.
sigmas (list, 선택 사항):
디노이징 프로세스를 위한 사용자 정의 sigmas입니다.
use_kv_cache (bool, 선택 사항, 기본값 True):
첫 번째 단계 이후 텍스트 및 조건 이미지의 키와 값을 캐시합니다. causal_condition이 t = 0부터 해당 토큰을 변조하여 활성화가 단계에 독립적이 되므로 유효합니다. 이를 토글해도 감소된 정밀도에서는 비트 단위로 동일한 이미지를 재현하지 않습니다.
attention_kwargs (dict, 선택 사항):
attention 프로세서에 대한 추가 kwargs입니다.
*denoiser_input_fields (None,선택 사항):
디노이저의 조건부 모델 입력입니다. 예: prompt_embeds, negative_prompt_embeds 등.
output_type (str,선택 사항*, 기본값 pil):
출력 형식: ‘pil’, ‘np’, ‘pt’.
출력:
images (list):
생성된 이미지.