이미지-이미지 생성

이미지-이미지 생성 (Image-to-image)

이미지-이미지 생성은 텍스트-이미지 생성과 비슷하지만, 프롬프트 외에도 확산 과정의 시작점으로 쓸 **초기 이미지(initial image)**를 함께 넘겨 줄 수 있어요. 초기 이미지는 잠재 공간(latent space)으로 인코딩된 뒤 노이즈가 더해집니다. 그러면 잠재 확산 모델이 프롬프트와 노이즈가 섞인 잠재 이미지를 받아 더해진 노이즈를 예측하고, 초기 잠재 이미지에서 예측된 노이즈를 제거해 새로운 잠재 이미지를 만들어 내요. 마지막으로 디코더(decoder)가 새로운 잠재 이미지를 다시 실제 이미지로 디코딩합니다.

🤗 Diffusers에서는 이 과정이 정말 손쉬워요:

  1. 체크포인트를 [AutoPipelineForImage2Image] 클래스에 로드합니다. 이 파이프라인은 체크포인트에 따라 올바른 파이프라인 클래스를 자동으로 불러와요:
import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import load_image, make_image_grid

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder", dtype=torch.float16, use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

[!TIP] 이 가이드 전체에서 메모리를 아끼고 추론 속도를 높이기 위해 [~DiffusionPipeline.enable_model_cpu_offload]와 [~DiffusionPipeline.enable_xformers_memory_efficient_attention]을 쓰는 걸 볼 수 있어요. PyTorch 2.0을 쓰고 있다면 파이프라인에서 [~DiffusionPipeline.enable_xformers_memory_efficient_attention]을 호출할 필요가 없어요. 이미 PyTorch 2.0 고유의 scaled-dot product attention을 쓰고 있기 때문이죠.

  1. 파이프라인에 넘길 이미지를 로드합니다:
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png")
  1. 파이프라인에 프롬프트와 이미지를 넘겨 이미지를 생성합니다:
prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"
image = pipeline(prompt, image=init_image).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
initial image
generated image

인기 있는 모델

가장 인기 있는 이미지-이미지 모델로는 Stable Diffusion v1.5, Stable Diffusion XL (SDXL), Kandinsky 2.2가 있어요. Stable Diffusion과 Kandinsky 모델의 결과는 아키텍처 차이와 훈련 과정 때문에 조금씩 달라져요. 일반적으로 SDXL이 Stable Diffusion v1.5보다 높은 품질의 이미지를 만든다고 기대할 수 있어요. 각 모델 사용법을 간단히 살펴보고 결과를 비교해 볼게요.

Stable Diffusion v1.5

Stable Diffusion v1.5는 더 이른 체크포인트에서 초기화된 잠재 확산 모델로, 512x512 이미지에서 595K 스텝으로 추가 파인튜닝됐어요. 이 파이프라인을 이미지-이미지 생성에 쓰려면 파이프라인에 넘길 초기 이미지를 준비해야 해요. 그런 다음 파이프라인에 프롬프트와 이미지를 넘겨 새로운 이미지를 생성하면 됩니다:

import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import make_image_grid, load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"

# pass prompt and image to pipeline
image = pipeline(prompt, image=init_image).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
initial image
generated image

Stable Diffusion XL (SDXL)

SDXL은 Stable Diffusion 모델의 더 강력한 버전이에요. 더 큰 베이스 모델을 쓰고, 베이스 모델 출력의 품질을 높이기 위해 추가적인 리파이너(refiner) 모델도 사용하죠. 이 모델 사용법과 고품질 이미지를 만드는 다른 기법을 더 자세히 보고 싶다면 SDXL 가이드를 읽어 보세요.

import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import make_image_grid, load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-refiner-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-sdxl-init.png"
init_image = load_image(url)

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"

# pass prompt and image to pipeline
image = pipeline(prompt, image=init_image, strength=0.5).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
initial image
generated image

Kandinsky 2.2

Kandinsky 모델은 이미지 임베딩을 만들기 위해 이미지 프라이어(image prior) 모델을 사용한다는 점이 Stable Diffusion 모델과 달라요. 이 임베딩은 텍스트와 이미지 사이의 정렬을 더 좋게 만들어, 잠재 확산 모델이 더 나은 이미지를 생성하게 도와줍니다.

Kandinsky 2.2를 쓰는 가장 간단한 방법은 이렇습니다:

import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import make_image_grid, load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder", dtype=torch.float16, use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"

# pass prompt and image to pipeline
image = pipeline(prompt, image=init_image).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
initial image
generated image

파이프라인 파라미터 설정

파이프라인에는 이미지 생성 과정과 이미지 품질에 영향을 주는 몇 가지 중요한 파라미터가 있어요. 각 파라미터가 무엇을 하는지, 값을 바꾸면 출력이 어떻게 달라지는지 자세히 살펴볼게요.

Strength

strength는 꼭 고려해야 할 가장 중요한 파라미터 중 하나로, 생성 이미지에 큰 영향을 줘요. 생성 결과가 초기 이미지와 얼마나 비슷한지를 결정하죠. 쉽게 말하면:

  • 📈 strength 값이 높을수록 모델이 초기 이미지와 다른 이미지를 만들 '창의력'을 더 많이 얻게 돼요. strength 값이 1.0이면 초기 이미지가 거의 무시된다고 보면 됩니다.
  • 📉 strength 값이 낮을수록 생성 이미지가 초기 이미지와 더 비슷해져요.

strengthnum_inference_steps 파라미터는 서로 연관돼 있는데, strength가 더할 노이즈 스텝 수를 정하기 때문이에요. 예를 들어 num_inference_steps가 50이고 strength가 0.8이면, 초기 이미지에 40(50 * 0.8) 스텝의 노이즈를 더한 뒤 40 스텝을 디노이징해서 새 이미지를 만든다는 뜻입니다.

import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import make_image_grid, load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"

# pass prompt and image to pipeline
image = pipeline(prompt, image=init_image, strength=0.8).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
strength = 0.4
strength = 0.6
strength = 1.0

가이던스 스케일

guidance_scale 파라미터는 생성 이미지와 텍스트 프롬프트가 얼마나 밀접하게 정렬되는지 제어해요. 값이 높을수록 생성 이미지가 프롬프트에 더 잘 맞고, 값이 낮을수록 생성 이미지가 프롬프트에서 벗어날 여지가 더 많아집니다.

guidance_scalestrength와 조합하면 모델이 얼마나 표현력 있게 동작할지 더 정밀하게 제어할 수 있어요. 예를 들어 높은 strength + guidance_scale을 조합해 창의력을 최대화하거나, 낮은 strength와 낮은 guidance_scale을 조합해 초기 이미지와 비슷하지만 프롬프트에 그렇게 엄격하게 얽매이지 않는 이미지를 만들 수 있어요.

import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import make_image_grid, load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"

# pass prompt and image to pipeline
image = pipeline(prompt, image=init_image, guidance_scale=8.0).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
guidance_scale = 0.1
guidance_scale = 5.0
guidance_scale = 10.0

네거티브 프롬프트

네거티브 프롬프트는 모델이 이미지에 포함하지 말아야 할 것을 조건화해요. 이미지 품질을 높이거나 이미지를 수정하는 데 쓸 수 있죠. 예를 들어 "poor details"나 "blurry" 같은 네거티브 프롬프트를 넣으면 모델이 더 높은 품질의 이미지를 만들도록 유도해 품질을 높일 수 있어요. 또는 이미지에서 제외할 것을 지정해서 이미지를 수정할 수도 있습니다.

import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import make_image_grid, load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-refiner-1.0", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"

# pass prompt and image to pipeline
image = pipeline(prompt, negative_prompt=negative_prompt, image=init_image).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"
negative_prompt = "jungle"

이미지-이미지 파이프라인 연결하기

이미지-이미지 파이프라인은 이미지를 생성하는 것(그것도 꽤 멋지지만) 외에도 재미있는 다른 방식으로 쓸 수 있어요. 한 단계 더 나아가 다른 파이프라인과 연결(chaining)해 볼 수 있죠.

텍스트-이미지-이미지

텍스트-이미지 파이프라인과 이미지-이미지 파이프라인을 연결하면, 텍스트로 이미지를 생성하고 그 이미지를 이미지-이미지 파이프라인의 초기 이미지로 쓸 수 있어요. 처음부터 완전히 이미지를 만들고 싶을 때 유용하죠. 예를 들어 Stable Diffusion과 Kandinsky 모델을 연결해 볼게요.

먼저 텍스트-이미지 파이프라인으로 이미지를 생성합니다:

from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
import torch
from diffusers.utils import make_image_grid

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

text2image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k").images[0]
text2image

이제 이 생성 이미지를 이미지-이미지 파이프라인에 넘겨 줄 수 있어요:

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder", dtype=torch.float16, use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

image2image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", image=text2image).images[0]
make_image_grid([text2image, image2image], rows=1, cols=2)

이미지-이미지-이미지

이미지-이미지 파이프라인을 여러 개 연결해서 더 흥미로운 이미지를 만들 수도 있어요. 이미지에 스타일 전이를 반복적으로 적용하거나, 짧은 GIF를 만들거나, 이미지에 색을 복원하거나, 이미지에서 빠진 영역을 복원할 때 유용하죠.

먼저 이미지를 생성합니다:

import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import make_image_grid, load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"

# pass prompt and image to pipeline
image = pipeline(prompt, image=init_image, output_type="latent").images[0]

[!TIP] 파이프라인에서 output_type="latent"을 지정하는 게 중요해요. 출력 전부를 잠재 공간에 유지해서 불필요한 디코드-인코드 단계를 피할 수 있거든요. 단, 연결하는 파이프라인들이 같은 VAE를 쓸 때만 동작합니다.

이 파이프라인의 잠재 출력을 다음 파이프라인에 넘겨 코믹북 아트 스타일의 이미지를 생성합니다:

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "ogkalu/Comic-Diffusion", dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# need to include the token "charliebo artstyle" in the prompt to use this checkpoint
image = pipeline("Astronaut in a jungle, charliebo artstyle", image=image, output_type="latent").images[0]

한 번 더 반복해서 픽셀 아트 스타일의 최종 이미지를 만듭니다:

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "kohbanye/pixel-art-style", dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# need to include the token "pixelartstyle" in the prompt to use this checkpoint
image = pipeline("Astronaut in a jungle, pixelartstyle", image=image).images[0]
make_image_grid([init_image, image], rows=1, cols=2)

이미지-업스케일러-초고해상도

이미지-이미지 파이프라인을 연결하는 또 다른 방법은 업스케일러(upscaler)와 초고해상도(super-resolution) 파이프라인을 이어 붙여 이미지의 디테일 수준을 크게 높이는 거예요.

이미지-이미지 파이프라인부터 시작합니다:

import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import make_image_grid, load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"

# pass prompt and image to pipeline
image_1 = pipeline(prompt, image=init_image, output_type="latent").images[0]

[!TIP] 파이프라인에서 output_type="latent"을 지정하는 게 중요해요. 출력 전부를 잠재 공간에 유지해서 불필요한 디코드-인코드 단계를 피할 수 있거든요. 단, 연결하는 파이프라인들이 같은 VAE를 쓸 때만 동작합니다.

이미지 해상도를 높이기 위해 업스케일러 파이프라인에 연결합니다:

from diffusers import StableDiffusionLatentUpscalePipeline

upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(
    "stabilityai/sd-x2-latent-upscaler", dtype=torch.float16, use_safetensors=True
)
upscaler.enable_model_cpu_offload()
upscaler.enable_xformers_memory_efficient_attention()

image_2 = upscaler(prompt, image=image_1).images[0]

마지막으로 초고해상도 파이프라인에 연결해 해상도를 더 높입니다:

from diffusers import StableDiffusionUpscalePipeline

super_res = StableDiffusionUpscalePipeline.from_pretrained(
    "stabilityai/stable-diffusion-x4-upscaler", dtype=torch.float16, variant="fp16", use_safetensors=True
)
super_res.enable_model_cpu_offload()
super_res.enable_xformers_memory_efficient_attention()

image_3 = super_res(prompt, image=image_2).images[0]
make_image_grid([init_image, image_3.resize((512, 512))], rows=1, cols=2)

이미지 생성 제어하기

내가 원하는 모습 그대로의 이미지를 만들기는 어려울 수 있어서, 제어된 생성 기법과 모델이 아주 유용해요. negative_prompt로 이미지 생성을 부분적으로 제어할 수 있지만, 프롬프트 가중치나 ControlNet 같은 더 견고한 방법도 있습니다.

프롬프트 가중치

프롬프트 가중치를 쓰면 프롬프트 안 각 개념의 표현을 확대·축소할 수 있어요. 예를 들어 "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" 같은 프롬프트에서 "astronaut"와 "jungle"의 임베딩을 높이거나 낮추는 식이죠. Compel 라이브러리는 프롬프트 가중치를 조정하고 임베딩을 생성하는 간단한 문법을 제공해요. 임베딩을 만드는 방법은 Prompt weighting 가이드에서 배울 수 있습니다.

[AutoPipelineForImage2Image]에는 prompt_embeds(네거티브 프롬프트를 쓴다면 negative_prompt_embeds) 파라미터가 있어서 여기에 임베딩을 넘겨 prompt 파라미터를 대체할 수 있어요.

from diffusers import AutoPipelineForImage2Image
import torch

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

image = pipeline(prompt_embeds=prompt_embeds, # generated from Compel
    negative_prompt_embeds=negative_prompt_embeds, # generated from Compel
    image=init_image,
).images[0]

ControlNet

ControlNet은 추가적인 컨디셔닝 이미지를 쓸 수 있어서 이미지 생성을 더 유연하고 정확하게 제어하게 해 줘요. 컨디셔닝 이미지는 캐니(canny) 이미지, 깊이 맵, 이미지 세그멘테이션, 심지어 낙서까지 될 수 있어요! 어떤 종류의 컨디셔닝 이미지를 고르든, ControlNet은 그 정보를 보존하는 이미지를 생성합니다.

예를 들어 깊이 맵으로 이미지를 컨디셔닝해서 이미지의 공간 정보를 유지해 볼게요.

from diffusers.utils import load_image, make_image_grid

# prepare image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
init_image = load_image(url)
init_image = init_image.resize((958, 960)) # resize to depth image dimensions
depth_image = load_image("https://huggingface.co/lllyasviel/control_v11f1p_sd15_depth/resolve/main/images/control.png")
make_image_grid([init_image, depth_image], rows=1, cols=2)

깊이 맵으로 컨디셔닝된 ControlNet 모델과 [AutoPipelineForImage2Image]를 로드합니다:

from diffusers import ControlNetModel, AutoPipelineForImage2Image
import torch

controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11f1p_sd15_depth", dtype=torch.float16, variant="fp16", use_safetensors=True)
pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, dtype=torch.float16, variant="fp16", use_safetensors=True
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

이제 깊이 맵, 초기 이미지, 프롬프트로 컨디셔닝된 새 이미지를 생성합니다:

prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image_control_net = pipeline(prompt, image=init_image, control_image=depth_image).images[0]
make_image_grid([init_image, depth_image, image_control_net], rows=1, cols=3)
initial image
depth image
ControlNet image

ControlNet으로 생성한 이미지에 이미지-이미지 파이프라인을 연결해 새 스타일을 적용해 볼게요:

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "nitrosocke/elden-ring-diffusion", dtype=torch.float16,
)
pipeline.enable_model_cpu_offload()
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
pipeline.enable_xformers_memory_efficient_attention()

prompt = "elden ring style astronaut in a jungle" # include the token "elden ring style" in the prompt
negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"

image_elden_ring = pipeline(prompt, negative_prompt=negative_prompt, image=image_control_net, strength=0.45, guidance_scale=10.5).images[0]
make_image_grid([init_image, depth_image, image_control_net, image_elden_ring], rows=2, cols=2)

최적화

확산 모델을 실행하는 건 계산 비용과 부하가 큰 일이지만, 몇 가지 최적화 트릭만으로 컨슈머급·무료 티어 GPU에서 충분히 실행할 수 있어요. 예를 들어 PyTorch 2.0의 scaled-dot product attention이나 xFormers 같은 더 메모리 효율적인 어텐션 형태를 쓸 수 있어요. (둘 중 하나만 써도 되고 둘 다 쓸 필요는 없어요.) 다른 파이프라인 구성 요소가 CPU에서 기다리는 동안 모델을 GPU로 오프로드할 수도 있습니다.

+ pipeline.enable_model_cpu_offload()
+ pipeline.enable_xformers_memory_efficient_attention()

torch.compile을 쓰면 UNet을 감싸서 추론 속도를 더 올릴 수 있어요:

pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)

더 자세히 보려면 Reduce memory usageAccelerate inference 가이드를 확인해 보세요.

더 알아보기 (Learn more)