Diffusers documentation

Pipeline 콜백

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

and get access to the augmented documentation experience

to get started

Pipeline 콜백

Callback은 denoising 단계의 끝에서 실행되며, 이후 단계를 위해 pipeline 상태나 텐서를 변경할 수 있습니다. pipeline을 다시 작성하지 않고 새로운 동작을 위해 속성이나 텐서 변수를 조정하는 데 사용하세요.

이 콜백은 기본적으로 클래식 DiffusionPipeline 루프와 함께 작동합니다. 디노이징 루프에 이를 실행하는 블록이 삽입되면 Modular Diffusers 파이프라인에서도 작동하며, Modular pipelines를 참고하세요.

Diffusers는 파이프라인 개요에서 여러 콜백을 제공합니다.

콜백을 활성화하려면, … 중 하나의 인수를 사용하여 특정 수의 디노이징 단계 이후에 콜백이 실행되는 시점을 구성합니다.

  • cutoff_step_ratio는 전체 디노이징 스텝의 백분율로 콜백이 활성화되는 시점을 지정합니다. 컷오프가 num_inference_steps에 따라 비례적으로 조정되어야 하는 경우(예: 실행의 40% 이후에 CFG 제거)에 사용합니다.
  • cutoff_step_index는 콜백이 활성화되는 정확한 스텝 번호를 지정합니다. 절대 스텝(예: 고정된 25스텝 스케줄의 10번째 스텝)에 관심이 있을 때 사용합니다.

아래 예시는 cutoff_step_ratio=0.4를 사용하여, 디노이징이 전체 추론 단계의 40%에 도달하면 콜백이 활성화됩니다. SDXLCFGCutoffCallback은 특정 단계 이후에 classifier-free guidance(CFG)를 비활성화하여, 성능에 큰 영향을 주지 않으면서도 계산 비용을 절감하는 데 도움이 될 수 있습니다.

cutoff 인자 중 하나를 사용하여 콜백을 정의하고, 파이프라인의 callback_on_step_end 매개변수에 전달합니다.

import torch
from diffusers import DPMSolverMultistepScheduler, StableDiffusionXLPipeline
from diffusers.callbacks import SDXLCFGCutoffCallback

callback = SDXLCFGCutoffCallback(cutoff_step_ratio=0.4)
# if using cutoff_step_index
# callback = SDXLCFGCutoffCallback(cutoff_step_ratio=None, cutoff_step_index=10)

pipeline = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    dtype=torch.float16,
    device_map="cuda"  # or "mps", "xpu", "cpu"
)
pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config, use_karras_sigmas=True)

prompt = "a sports car on the road, best quality, high quality, high detail, 8k resolution"
output = pipeline(
    prompt=prompt,
    negative_prompt="",
    guidance_scale=6.5,
    num_inference_steps=25,
    callback_on_step_end=callback,
)

공식 콜백은 자체적으로 텐서 입력을 설정합니다. 사용자 정의 함수의 경우, 중간 이미지 표시에서와 같이 callback_on_step_end_tensor_inputs를 전달합니다.

새로운 공식 callback을 추가하려면 기능 요청을 열거나 PR을 제출할 수 있습니다. 그렇지 않으면 아래에 나와 있는 대로 직접 callback을 만들 수도 있습니다.

조기 종료

Early stopping은 생성 과정 중 중간 결과에 만족하지 못할 때 유용합니다. 이 콜백은 _interrupt 속성을 True로 설정하여 하드코딩된 중단 지점을 설정하며, 이를 통해 denoising 루프가 나머지 스텝을 건너뛰게 됩니다.

import torch
from diffusers import DiffusionPipeline

def interrupt_callback(pipeline, i, t, callback_kwargs):
    stop_idx = 10
    if i == stop_idx:
        pipeline._interrupt = True
    return callback_kwargs

pipeline = DiffusionPipeline.from_pretrained(
    "Qwen/Qwen-Image",
    dtype=torch.bfloat16,
    device_map="cuda",  # or "mps", "xpu", "cpu"
)
pipeline(
    prompt="A photo of a cat",
    num_inference_steps=50,
    callback_on_step_end=interrupt_callback,
)

중간 이미지 표시

중간 이미지를 시각화하는 것은 진행 상황 모니터링에 유용합니다. 아래 미리보기는 SDXL 전용입니다. 디노이징(denoising) 중에 빠르게 확인하기 위해 SDXL의 latents를 선형 변환(linear transform)으로 RGB로 매핑합니다. 해당 가중치는 다른 모델에 적용되지 않습니다. Qwen-Image 및 유사한 체크포인트의 경우, 이 헬퍼 대신 모델의 VAE로 디코딩하세요.

변환 Stable Diffusion XL latents(4채널)를 RGB 텐서(3채널)로 변환합니다.

import torch
from PIL import Image
from diffusers import AutoPipelineForText2Image

def latents_to_rgb(latents):
    weights = (
        (60, -60, 25, -70),
        (60,  -5, 15, -50),
        (60,  10, -5, -35),
    )

    weights_tensor = torch.t(torch.tensor(weights, dtype=latents.dtype).to(latents.device))
    biases_tensor = torch.tensor((150, 140, 130), dtype=latents.dtype).to(latents.device)
    rgb_tensor = torch.einsum("...lxy,lr -> ...rxy", latents, weights_tensor) + biases_tensor.unsqueeze(-1).unsqueeze(-1)
    image_array = rgb_tensor.clamp(0, 255).byte().cpu().numpy().transpose(1, 2, 0)

    return Image.fromarray(image_array)

latents를 추출하고 배치의 첫 번째 이미지를 RGB로 변환합니다. 이미지를 단계 번호를 포함하여 PNG 파일로 저장합니다.

def decode_tensors(pipe, step, timestep, callback_kwargs):
    latents = callback_kwargs["latents"]

    image = latents_to_rgb(latents[0])
    image.save(f"{step}.png")

    return callback_kwargs

callback_on_step_end_tensor_inputs를 사용하여 콜백이 수신할 텐서를 선택합니다. 이 경우 해당 텐서는 latents입니다.

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    dtype=torch.float16,
    device_map="cuda"  # or "mps", "xpu", "cpu"
)

image = pipeline(
    prompt="A croissant shaped like a cute bear.",
    negative_prompt="Deformed, ugly, bad anatomy",
    callback_on_step_end=decode_tensors,
    callback_on_step_end_tensor_inputs=["latents"],
).images[0]

모듈형 파이프라인

모듈형 파이프라인은 callback_on_step_end 및 interrupt 메커니즘을 지원하지 않습니다. 대신 1급(streaming) 스트리밍 지원이 제공됩니다. 아직 병합되지 않은 huggingface/diffusers#14159 PR은 pipe.stream()을 추가하며, 이는 각 디노이징 단계마다 파이프라인 상태를 반환하고 반복을 중단하면 실행을 종료합니다. 현재는 기존 콜백 함수를 재사용하려면 파이프라인에서 insert_step_callback()을 호출하세요. 이 메서드는 모든 디노이징 루프의 끝에 사용자 함수를 호출하는 블록을 추가합니다.

import torch
from diffusers import ModularPipeline
from diffusers.modular_pipelines import insert_step_callback

pipe = ModularPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
insert_step_callback(pipe)
pipe.load_components(dtype=torch.float16)
pipe.to("cuda")

callback_on_step_end는 이제 파이프라인의 입력이며, DiffusionPipeline용으로 작성된 decode_tensors와 같은 콜백은 그대로 작동합니다:

image = pipe(prompt="A croissant shaped like a cute bear.", callback_on_step_end=decode_tensors, output="images")[0]

콜백은 위와 동일한 시그니처로 호출됩니다: 파이프라인, 스텝 인덱스, 타임스텝, callback_kwargs. DiffusionPipeline와 두 가지 차이점이 있습니다:

  • callback_on_step_end_tensor_inputs은 존재하지 않습니다. callback_kwargs에는 latents와 같은 디노이징 루프의 모든 값이 포함되며, 콜백이 반환하는 값은 다시 기록됩니다.
  • 모듈러 파이프라인에는 num_timesteps 속성이 없으므로, 단계 수는 callback_kwargs["num_timesteps"]에 있습니다.

Early stopping은 동작 방식이 다릅니다. 블록은 실행 중인 루프를 건너뛸 수 없으므로 _interrupt를 설정해도 효과가 없습니다. 대신 콜백에서 예외를 발생시키세요. 예외는 pipe(...)에서 전파되어 나옵니다(이미지가 디코딩되지 않음) 그리고 파이프라인은 이후에도 계속 사용할 수 있습니다.

중지된 실행은 아무것도 반환하지 않으므로, 예외를 발생시키기 전에 콜백에서 유지하려는 중간 값을 저장하세요.

class StopGeneration(BaseException):
    pass


partial = {}


def interrupt_callback(pipeline, i, t, callback_kwargs):
    stop_idx = 10
    if i == stop_idx:
        partial["latents"] = callback_kwargs["latents"]
        raise StopGeneration
    return callback_kwargs


try:
    image = pipe(prompt="A photo of a cat", callback_on_step_end=interrupt_callback, output="images")[0]
except StopGeneration:
    print("stopped early")

StopGeneration은 블록이 종료 시 에러로 기록하지 않도록 BaseException의 하위 클래스입니다. Exception의 하위 클래스도 실행을 중단하지만, 통과하는 각 블록에서 traceback이 기록됩니다.

저장된 latents는 denoising 루프가 사용하는 형태이며, 많은 모델의 경우 packed 상태입니다. 이미지를 얻으려면 decode 단계를 실행하기 전에 unpacking이 필요할 수 있습니다.

denoising 루프의 각 단계를 블록으로 실행하는 모든 modular pipeline에 대해 이 방식이 작동합니다. Helios와 Wan-Animate-2와 같은 자기회귀 모델은 외부 루프의 하나의 블록 내에서 각 청크를 denoise하므로, 콜백을 삽입할 위치가 없으며 insert_step_callback()은 ValueError를 발생시킵니다.

Update on GitHub