Diffusers documentation

SANA-Sprint

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

SANA-Sprint

LoRA

NVIDIA, MIT HAN Lab, Hugging Face의 Junsong Chen, Shuchen Xue, Yuyang Zhao, Jincheng Yu, Sayak Paul, Junyu Chen, Han Cai, Enze Xie, Song Han이 발표한 SANA-Sprint: One-Step Diffusion with Continuous-Time Consistency Distillation

해당 논문의 초록은 다음과 같습니다:

이 논문은 초고속 텍스트-이미지(T2I) 생성을 위한 효율적인 확산 모델인 SANA-Sprint를 제시합니다. SANA-Sprint는 사전 학습된 기반 모델 위에 하이브리드 증류를 적용하여 구축되었으며, 추론 단계 수를 20단계에서 1~4단계로 크게 줄였습니다. 우리는 세 가지 핵심 혁신을 소개합니다. (1) 사전 학습된 flow-matching 모델을 연속 시간 일관성 증류(sCM)용으로 변환하는 학습 불필요(training-free) 접근법을 제안하여, 처음부터 수행해야 하는 비용이 높은 학습을 제거하고 높은 학습 효율을 달성했습니다. 우리의 하이브리드 증류 전략은 sCM과 잠재적 적대적 증류(LADD)를 결합합니다. sCM은 교사 모델과의 정렬을 보장하고, LADD는 단일 단계 생성의 충실도를 향상시킵니다. (2) SANA-Sprint는 1~4단계로 고품질 생성을 달성하는 통합된 단계 적응(step-adaptive) 모델로, 단계별 특정 학습을 제거하고 효율성을 높입니다. (3) SANA-Sprint에 ControlNet을 통합하여 실시간 인터랙티브 이미지 생성을 가능하게 하여, 사용자 상호작용에 대한 즉각적인 시각적 피드백을 제공합니다. SANA-Sprint는 속도-품질 트레이드오프에서 새로운 파레토 프런티어를 확립하며, 단 1단계로 7.59 FID와 0.74 GenEval을 달성하여 최첨단 성능을 보입니다. 이는 FLUX-schnell(7.94 FID / 0.71 GenEval)보다 우수할 뿐만 아니라 10배 빠릅니다(H100에서 0.1초 대 1.1초). 또한 H100에서 1024×1024 이미지에 대해 0.1초(T2I) 및 0.25초(ControlNet)의 지연 시간, RTX 4090에서 0.31초(T2I)의 지연 시간을 달성하여 뛰어난 효율성과 AI 기반 소비자 애플리케이션(AIPC)에 대한 잠재력을 보여줍니다. 코드와 사전 학습된 모델은 오픈소스로 공개될 예정입니다.

이 파이프라인은 lawrence-cj, shuchen Xue, Enze Xie가 기여했습니다. 원본 코드베이스는 여기에서 찾을 수 있습니다. 원본 가중치는 hf.co/Efficient-Large-Model에서 찾을 수 있습니다.

사용 가능한 모델:

모델권장 dtype
Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffuserstorch.bfloat16
Efficient-Large-Model/Sana_Sprint_0.6B_1024px_diffuserstorch.bfloat16

자세한 내용은 이 컬렉션을 참조하세요.

Note: 언급된 권장 dtype는 transformer 가중치에 대한 것입니다. 모델이 올바르게 작동하려면 텍스트 인코더는 torch.bfloat16로, VAE 가중치는 torch.bfloat16 또는 torch.float32로 유지되어야 합니다. 권장 dtype로 모델을 로드하는 방법은 아래 추론 예시를 참고하세요.

양자화

Quantization은 모델 가중치를 더 낮은 정밀도의 데이터 타입으로 저장하여 매우 큰 모델의 메모리 요구 사항을 줄이는 데 도움이 됩니다. 그러나 quantization은 비디오 모델에 따라 비디오 품질에 다양한 영향을 미칠 수 있습니다.

지원되는 양자화 백엔드와 사용 사례에 맞는 양자화 백엔드 선택에 대해 자세히 알아보려면 Quantization 개요를 참조하세요. 아래 예제는 bitsandbytes를 사용하여 추론을 위해 양자화된 SanaSprintPipeline을 로드하는 방법을 보여줍니다.

import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, SanaTransformer2DModel, SanaSprintPipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, AutoModel

quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = AutoModel.from_pretrained(
    "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers",
    subfolder="text_encoder",
    quantization_config=quant_config,
    dtype=torch.bfloat16,
)

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = SanaTransformer2DModel.from_pretrained(
    "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.bfloat16,
)

pipeline = SanaSprintPipeline.from_pretrained(
    "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers",
    text_encoder=text_encoder_8bit,
    transformer=transformer_8bit,
    dtype=torch.bfloat16,
    device_map="balanced",
)

prompt = "a tiny astronaut hatching from an egg on the moon"
image = pipeline(prompt).images[0]
image.save("sana.png")

max_timesteps 설정

사용자는 생성된 출력의 시각적 품질을 실험하기 위해 max_timesteps 값을 조정할 수 있습니다. 기본 max_timesteps 값은 추론 시간 검색 과정을 통해 얻었습니다. 자세한 내용은 논문을 참고하세요.

이미지에서 이미지로

SanaSprintImg2ImgPipeline은 이미지-이미지 생성을 위한 파이프라인입니다. 입력 이미지와 프롬프트를 받아, 해당 입력 이미지와 프롬프트를 기반으로 새로운 이미지를 생성합니다.

import torch
from diffusers import SanaSprintImg2ImgPipeline
from diffusers.utils.loading_utils import load_image

image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
)

pipe = SanaSprintImg2ImgPipeline.from_pretrained(
    "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", 
    dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = pipe(
    prompt="a cute pink bear", 
    image=image, 
    strength=0.5, 
    height=832, 
    width=480
).images[0]
image.save("output.png")

SanaSprintPipeline

클래스 diffusers.SanaSprintPipeline

< >

( tokenizer: GemmaTokenizertext_encoder: Gemma2PreTrainedModelvae: AutoencoderDCtransformer: SanaTransformer2DModelscheduler: DPMSolverMultistepScheduler )

SANA-Sprint를 사용한 텍스트-이미지 생성 파이프라인.

__call__

< >

( prompt: str | list[str] = Nonenum_inference_steps: int = 2timesteps: list = Nonemax_timesteps: float = 1.5708intermediate_timesteps: float = 1.3guidance_scale: float = 4.5num_images_per_prompt: int | None = 1height: int = 1024width: int = 1024eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueclean_caption: bool = Falseuse_resolution_binning: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 300complex_human_instruction: list = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '] ) → SanaPipelineOutput or tuple

매개변수

  • prompt (str 또는 list[str], 선택 사항) — 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 prompt_embeds를 대신 전달해야 합니다.
  • num_inference_steps (int, 선택 사항, 기본값 20) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다.
  • max_timesteps (float, 선택 사항, 기본값 1.57080) — SCM 스케줄러에서 사용되는 최대 timestep 값입니다.
  • intermediate_timesteps (float, 선택 사항, 기본값 1.3) — SCM 스케줄러에서 사용되는 중간 타임스텝 값입니다(단, num_inference_steps=2일 때만 사용).
  • timesteps (list[int], 선택 사항) — timesteps 인수를 지원하는 스케줄러의 set_timesteps 메서드에서 디노이징 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.
  • guidance_scale (float, 선택 사항, 기본값 4.5) — 임베디드 가이던스 스케일은 guidance_scale > 1. 을 더 높이면 guidance_scale 모델이 prompt 에 더 부합하는 이미지를 생성하도록 장려하지만, 이미지 품질이 낮아지는 대가를 치릅니다.

    Guidance-distilled 모델은 guidance_scale > 1인 경우 true classifer-free guidance를 근사합니다. 자세한 내용은 논문을 참고하세요.

  • num_images_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다.
  • height (int, 선택 사항, 기본값 self.unet.config.sample_size) — 생성된 이미지의 픽셀 단위 높이입니다.
  • width (int, 선택 사항, 기본값 self.unet.config.sample_size) — 생성된 이미지의 픽셀 단위 너비입니다.
  • eta (float, 선택 사항, 기본값 0.0) — DDIM 논문에서 파라미터 eta (η)에 해당합니다: https://huggingface.co/papers/2010.02502. schedulers.DDIMScheduler에만 적용되며, 다른 경우 무시됩니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록
  • latents (torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • prompt_attention_mask (torch.Tensor, 선택 사항) — 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 이미지 생성의 출력 형식입니다. PIL: PIL.Image.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — ~pipelines.stable_diffusion.IFPipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다.
  • attention_kwargs — 지정된 경우 diffusers.models.attention_processor의 self.processor에서 정의된 AttentionProcessor로 전달되는 kwargs 사전입니다.
  • clean_caption (bool, 선택 사항, 기본값 True) — 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다. beautifulsoup4와 ftfy가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.
  • use_resolution_binning (bool, 기본값 True) — True로 설정하면, 요청된 높이와 너비가 먼저 ASPECT_RATIO_1024_BIN을 사용하여 가장 가까운 해상도로 매핑됩니다. 생성된 latents가 이미지로 디코딩된 후, 요청된 해상도로 다시 리사이즈됩니다. 정사각형이 아닌 이미지를 생성하는 데 유용합니다.
  • callback_on_step_end (Callable, 선택 사항) — 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs에는 callback_on_step_end_tensor_inputs로 지정된 모든 텐서 목록이 포함됩니다.
  • callback_on_step_end_tensor_inputs (list, 선택 사항) — callback_on_step_end 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 callback_kwargs 인수로 전달됩니다. 파이프라인 클래스의 ._callback_tensor_inputs 속성에 나열된 변수만 포함할 수 있습니다.
  • max_sequence_length (int, 기본값 300) — prompt에 사용할 최대 시퀀스 길이입니다.
  • complex_human_instruction (list[str], 선택 사항) — 복잡한 인간 주의(attention)를 위한 지침: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.

반환값

SanaPipelineOutput 또는 tuple

return_dict가 True인 경우 SanaPipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록인 tuple이 반환됩니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:

>>> import torch
>>> from diffusers import SanaSprintPipeline

>>> pipe = SanaSprintPipeline.from_pretrained(
...     "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")

>>> image = pipe(prompt="a tiny astronaut hatching from an egg on the moon")[0]
>>> image[0].save("output.png")

encode_prompt

< >

( prompt: str | list[str]num_images_per_prompt: int = 1device: typing.Optional[torch.device] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Noneclean_caption: bool = Falsemax_sequence_length: int = 300complex_human_instruction: list[str] | None = Nonelora_scale: float | None = None )

매개변수

  • prompt (str 또는 list[str], 선택 사항) — 인코딩할 프롬프트
  • num_images_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수
  • device — (torch.device, 선택 사항): 결과 임베딩을 배치할 torch device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • clean_caption (bool, 기본값 False) — True인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.
  • max_sequence_length (int, 기본값 300) — 프롬프트에 사용할 최대 시퀀스 길이입니다.
  • complex_human_instruction (list[str], 기본값 complex_human_instruction) — complex_human_instruction이 비어 있지 않으면, 이 함수는 프롬프트에 복잡한 Human 지시를 사용합니다.

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

SanaSprintImg2ImgPipeline

클래스 diffusers.SanaSprintImg2ImgPipeline

< >

( tokenizer: GemmaTokenizertext_encoder: Gemma2PreTrainedModelvae: AutoencoderDCtransformer: SanaTransformer2DModelscheduler: DPMSolverMultistepScheduler )

SANA-Sprint를 사용한 텍스트-이미지 생성 파이프라인.

__call__

< >

( prompt: str | list[str] = Nonenum_inference_steps: int = 2timesteps: list = Nonemax_timesteps: float = 1.5708intermediate_timesteps: float = 1.3guidance_scale: float = 4.5image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonestrength: float = 0.6num_images_per_prompt: int | None = 1height: int = 1024width: int = 1024eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueclean_caption: bool = Falseuse_resolution_binning: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 300complex_human_instruction: list = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '] ) → SanaPipelineOutput or tuple

매개변수

  • prompt (str 또는 list[str], 선택 사항) — 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 prompt_embeds를 대신 전달해야 합니다.
  • num_inference_steps (int, 선택 사항, 기본값 20) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다.
  • max_timesteps (float, 선택 사항, 기본값 1.57080) — SCM 스케줄러에서 사용되는 최대 timestep 값입니다.
  • intermediate_timesteps (float, 선택 사항, 기본값 1.3) — SCM 스케줄러에서 사용되는 중간 타임스텝 값입니다(단, num_inference_steps=2일 때만 사용).
  • timesteps (list[int], 선택 사항) — timesteps 인수를 지원하는 스케줄러의 set_timesteps 메서드에서 디노이징 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.
  • guidance_scale (float, 선택 사항, 기본값 4.5) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다. guidance_scale은 Imagen Paper의 2번 식의 w로 정의됩니다. guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록 prompt 텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, list[torch.Tensor], list[PIL.Image.Image] 또는 list[np.ndarray]) — 시작점으로 사용할 이미지 배치의 Image, numpy 배열 또는 텐서를 나타냅니다. image로 이미지 latents를 직접 전달할 수도 있으며, 이 경우 다시 인코딩되지 않습니다.
  • strength (float, 선택 사항, 기본값 0.6) — 참조 image를 변환하는 정도를 나타냅니다. 0과 1 사이여야 합니다. image는 시작점으로 사용되며, strength 값이 높을수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. strength가 1이면 추가되는 노이즈가 최대가 되며, num_inference_steps에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 1이라는 값은 사실상 image를 무시하는 것과 같습니다.
  • num_images_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다.
  • height (int, 선택 사항, 기본값 self.unet.config.sample_size) — 생성된 이미지의 픽셀 단위 높이입니다.
  • width (int, 선택 사항, 기본값 self.unet.config.sample_size) — 생성된 이미지의 픽셀 단위 너비입니다.
  • eta (float, 선택 사항, 기본값 0.0) — DDIM 논문에서 파라미터 eta (η)에 해당합니다: https://arxiv.org/abs/2010.02502. schedulers.DDIMScheduler에만 적용되며, 다른 스케줄러에서는 무시됩니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록
  • latents (torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • prompt_attention_mask (torch.Tensor, 선택 사항) — 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 이미지 생성의 출력 형식입니다. PIL: PIL.Image.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — ~pipelines.stable_diffusion.IFPipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다.
  • attention_kwargs — 지정된 경우 diffusers.models.attention_processor의 self.processor에서 정의된 AttentionProcessor로 전달되는 kwargs 사전입니다.
  • clean_caption (bool, 선택 사항, 기본값 True) — 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다. beautifulsoup4와 ftfy가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.
  • use_resolution_binning (bool, 기본값 True) — True로 설정하면, 요청된 높이와 너비가 먼저 ASPECT_RATIO_1024_BIN을 사용하여 가장 가까운 해상도로 매핑됩니다. 생성된 latents가 이미지로 디코딩된 후, 요청된 해상도로 다시 리사이즈됩니다. 정사각형이 아닌 이미지를 생성하는 데 유용합니다.
  • callback_on_step_end (Callable, 선택 사항) — 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs에는 callback_on_step_end_tensor_inputs로 지정된 모든 텐서 목록이 포함됩니다.
  • callback_on_step_end_tensor_inputs (list, 선택 사항) — callback_on_step_end 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 callback_kwargs 인수로 전달됩니다. 파이프라인 클래스의 ._callback_tensor_inputs 속성에 나열된 변수만 포함할 수 있습니다.
  • max_sequence_length (int, 기본값 300) — prompt에 사용할 최대 시퀀스 길이입니다.
  • complex_human_instruction (list[str], 선택 사항) — 복잡한 인간 주의(attention)를 위한 지침: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.

반환값

SanaPipelineOutput 또는 tuple

return_dict가 True인 경우 SanaPipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록인 tuple이 반환됩니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:

>>> import torch
>>> from diffusers import SanaSprintImg2ImgPipeline
>>> from diffusers.utils.loading_utils import load_image

>>> pipe = SanaSprintImg2ImgPipeline.from_pretrained(
...     "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")

>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
... )


>>> image = pipe(prompt="a cute pink bear", image=image, strength=0.5, height=832, width=480).images[0]
>>> image[0].save("output.png")

encode_prompt

< >

( prompt: str | list[str]num_images_per_prompt: int = 1device: typing.Optional[torch.device] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Noneclean_caption: bool = Falsemax_sequence_length: int = 300complex_human_instruction: list[str] | None = Nonelora_scale: float | None = None )

매개변수

  • prompt (str 또는 list[str], 선택 사항) — 인코딩할 프롬프트
  • num_images_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수
  • device — (torch.device, 선택 사항): 결과 임베딩을 배치할 torch device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • clean_caption (bool, 기본값 False) — True인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.
  • max_sequence_length (int, 기본값 300) — 프롬프트에 사용할 최대 시퀀스 길이입니다.
  • complex_human_instruction (list[str], 기본값 complex_human_instruction) — complex_human_instruction이 비어 있지 않으면, 이 함수는 프롬프트에 복잡한 Human 지시를 사용합니다.

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

SanaPipelineOutput

클래스 diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarray )

매개변수

  • images (list[PIL.Image.Image] 또는 np.ndarray) — batch_size 길이의 denoised PIL 이미지 목록 또는 (batch_size, height, width, num_channels) 형태의 numpy 배열. PIL 이미지 또는 numpy 배열은 diffusion 파이프라인의 denoised 이미지를 나타냅니다.

Sana 파이프라인의 출력 클래스입니다.

Update on GitHub