Diffusers documentation
ControlNet
ControlNet
ControlNet은 Lvmin Zhang, Anyi Rao, Maneesh Agrawala가 Adding Conditional Control to Text-to-Image Diffusion Models에서 소개했습니다.
ControlNet 모델을 사용하면 추가적인 제어 이미지를 제공하여 Stable Diffusion 생성을 조건화하고 제어할 수 있습니다. 예를 들어, 깊이 맵을 제공하면 ControlNet 모델은 해당 깊이 맵의 공간 정보를 보존하는 이미지를 생성합니다. 이는 이미지 생성 과정을 제어하는 더 유연하고 정확한 방법입니다.
해당 논문의 초록은 다음과 같습니다:
저희는 대규모 사전 학습된 텍스트-이미지 확산 모델에 공간 조건 제어를 추가하는 신경망 아키텍처인 ControlNet을 소개합니다. ControlNet은 프로덕션에 바로 적용 가능한 대규모 확산 모델을 고정(lock)하고, 수십억 장의 이미지로 사전 학습된 깊고 견고한 인코딩 레이어를 강력한 백본으로 재사용하여 다양한 조건 제어 세트를 학습합니다. 이 신경 아키텍처는 “zero convolutions”(제로 초기화 컨볼루션 레이어)로 연결되어, 매개변수를 0에서 점진적으로 증가시키고 유해한 노이즈가 파인튜닝에 영향을 미치지 않도록 보장합니다. Stable Diffusion을 사용하여 엣지, 깊이, 분할, 인간 자세 등 다양한 조건 제어를 단일 또는 복수의 조건, 프롬프트 유무와 함께 테스트했습니다. ControlNet의 학습이 소규모(<50k) 및 대규모(>1m) 데이터셋 모두에서 견고함을 보임을 확인했습니다. 광범위한 결과에 따르면, ControlNet은 이미지 확산 모델에 대한 제어를 가능하게 하여 더 넓은 응용 분야로의 확장을 촉진할 수 있습니다.
이 파이프라인은 ishan24님이 기여했습니다. ❤️ 원본 코드베이스는 NVlabs/Sana에서 찾을 수 있으며, 공식 ControlNet 체크포인트는 Efficient-Large-Model의 Hub 프로필에서 확인할 수 있습니다.
SanaControlNetPipeline
클래스 diffusers.SanaControlNetPipeline
< source >( tokenizer: GemmaTokenizertext_encoder: Gemma2PreTrainedModelvae: AutoencoderDCtransformer: SanaTransformer2DModelcontrolnet: SanaControlNetModelscheduler: DPMSolverMultistepScheduler )
Sana를 사용한 텍스트-이미지 생성 파이프라인.
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str = ''num_inference_steps: int = 20timesteps: list = Nonesigmas: list = Noneguidance_scale: float = 4.5control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0num_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_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를 대신 전달해야 합니다. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우negative_prompt_embeds를 대신 전달해야 합니다. 가이던스를 사용하지 않을 때 무시됩니다(즉,guidance_scale이1보다 작으면 무시됩니다). - num_inference_steps (
int, 선택 사항, 기본값 20) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다. - timesteps (
list[int], 선택 사항) —timesteps인수를 지원하는 스케줄러의set_timesteps메서드에서 디노이징 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우,num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - sigmas (
list[float], 선택 사항) —set_timesteps메서드에sigmas인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우,num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. - guidance_scale (
float, 선택 사항, 기본값 4.5) — Classifier-Free Diffusion Guidance에서 정의한 가이던스 스케일입니다.guidance_scale은 Imagen Paper의 방정식 2의w로 정의됩니다.guidance_scale > 1로 설정하면 가이던스 스케일이 활성화됩니다. 가이던스 스케일이 높을수록prompt텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. - control_image (
torch.Tensor,PIL.Image.Image,np.ndarray,list[torch.Tensor],list[PIL.Image.Image],list[np.ndarray], —list[list[torch.Tensor]],list[list[np.ndarray]]또는list[list[PIL.Image.Image]]): 생성을 위해unet에 가이드를 제공하기 위한 ControlNet 입력 조건입니다. 타입이torch.Tensor으로 지정된 경우, ControlNet에 그대로 전달됩니다.PIL.Image.Image도 이미지로 수용할 수 있습니다. 출력 이미지의 차원은 기본적으로image의 차원을 따릅니다. height와/또는 width가 전달되면,image는 그에 맞게 리사이즈됩니다.init에서 여러 ControlNet이 지정된 경우, 각 리스트 요소가 단일 ControlNet의 입력으로 올바르게 배치될 수 있도록 리스트로 이미지를 전달해야 합니다. - controlnet_conditioning_scale (
float또는list[float], 선택 사항, 기본값 1.0) — ControlNet의 출력은 원래unet의 잔차(residual)에 더해지기 전에controlnet_conditioning_scale로 곱해집니다.init에서 여러 ControlNet을 지정했다면, 해당 스케일을 리스트로 설정할 수 있습니다. - 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, 선택 사항) — 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다. - negative_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면negative_prompt입력 인수에서 negative_prompt_embeds가 생성됩니다. - negative_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 SanaControlNetPipeline
>>> from diffusers.utils import load_image
>>> pipe = SanaControlNetPipeline.from_pretrained(
... "ishan24/Sana_600M_1024px_ControlNetPlus_diffusers",
... variant="fp16",
... torch_dtype={"default": torch.bfloat16, "controlnet": torch.float16, "transformer": torch.float16},
... device_map="balanced",
... )
>>> cond_image = load_image(
... "https://huggingface.co/ishan24/Sana_600M_1024px_ControlNet_diffusers/resolve/main/hed_example.png"
... )
>>> prompt = 'a cat with a neon sign that says "Sana"'
>>> image = pipe(
... prompt,
... control_image=cond_image,
... ).images[0]
>>> image.save("output.png")encode_prompt
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenegative_prompt: str = ''num_images_per_prompt: int = 1device: typing.Optional[torch.device] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_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], 선택 사항) — 인코딩할 프롬프트 - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 유도하지 않을 프롬프트입니다. 정의되지 않은 경우 대신negative_prompt_embeds를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉,guidance_scale이1보다 작은 경우 무시됨). PixArt-Alpha의 경우 ""여야 합니다. - do_classifier_free_guidance (
bool, 선택 사항, 기본값True) — classifier free guidance를 사용할지 여부 - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수 - device — (
torch.device, 선택 사항): 결과 임베딩을 배치할 torch device - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 부정 텍스트 임베딩입니다. Sana의 경우, "" 문자열의 임베딩이어야 합니다. - 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
< source >( images: list[PIL.Image.Image] | numpy.ndarray )
Sana 파이프라인의 출력 클래스입니다.