safetensor는 저장된 모델의 텐서를 저장하고 로드하기 위한 새롭고 안전한 파일 형식입니다. 이 새로운 형식은 저장된 모델에 악성 코드를 저장하기 어렵게 만들며, 이는 생성형 AI의 발전과 함께 그 중요성이 점점 더 커지고 있습니다. 표시된 코드 블록에서 use_safetensors=Tru를 전달하여 safetensor를 로드합니다.
# Prompting to generate image.
prompt = "A photo of a large airplane in the middle of a storm and lightning, highly detailed, unreal engine effect"
image = pipe(
prompt,
num_inference_steps=150,
generator=torch.manual_seed(seed)
).images[0]
image
0%| | 0/150 [00:00<?, ?it/s]
Negative Prompt
이미지를 생성할 때 왜곡되고 흐릿하며 매력적이지 않은 이미지를 가능한 한 최소화하고 싶을 것입니다. 이를 위해 디퓨저의 파이프라인은 이미지에서 원하지 않는 부분을 나타내는 프롬프트 문자열을 허용하는 negative_promp 인수를 제공합니다.
prompt = "A photo of a large airplane in the middle of a storm and lightning, highly detailed, unreal engine effect"
image = pipe(
prompt,
num_inference_steps=150,
generator=torch.manual_seed(seed),
negative_prompt='low resolution, distorted, ugly, deformed, disfigured, poor details'
).images[0]
image
0%| | 0/150 [00:00<?, ?it/s]
Swapping Schedulers
Stable Diffusion 모델은 각 시간 단계에서 스케줄링 기법을 사용하여 이미지를 생성합니다. 스케줄러에 대한 자세한 내용은 노이즈 제거 확산 확률론적 모델 문서에서 확인할 수 있습니다. 또한 이러한 스케줄러를 교체하여 동일한 프롬프트를 사용하여 다른 이미지를 생성할 수도 있습니다. 일반적으로 일부 스케줄러는 다른 스케줄러보다 더 잘 작동합니다. 하지만 대부분의 경우 기본 설정인 DDIMSchedulr를 그대로 두는 것이 안전합니다.
EulerAncestralDiscreteSchedule는 매우 높은 품질의 이미지를 생성합니다
from diffusers import EulerAncestralDiscreteScheduler
prompt = "A real landscape, with starry sky, moonlit river, trending on artstation"
image = pipe(
prompt=prompt,
image=init_image,
num_inference_steps=150,
strength=1,
generator=torch.manual_seed(seed)
).images[0]
image
0%| | 0/150 [00:00<?, ?it/s]
Diffusers AutoPipeline
diffuser는 제공된 모델과 인수를 기반으로 작업을 감지하는 자동 파이프라인을 제공합니다.
어떤 모델이 기여했는지 또는 안정적인 확산 변형인지 여부에 관계없이 작업에 따라 Hugging Face Hub의 모든 모델 경로를 전달할 수 있습니다.
Text-to-Image
from diffusers import AutoPipelineForText2Image
pipe = AutoPipelineForText2Image.from_pretrained(
'stabilityai/stable-diffusion-2-1',
torch_dtype=torch.float16,
use_safetensors=True
).to(device)
prompt = "A white dog, anime style, realism, detailed line art, fine details, solid lines"
image = pipe(
prompt,
num_inference_steps=150,
generator=torch.manual_seed(seed)
).images[0]
image
prompt = "a painting of sand dunes in a desert, with sun rising on the horizon, sand particle style, pastel drawing, on canvas"
image = pipe(
prompt,
init_image,
num_inference_steps=150,
strength=1.0,
generator=torch.manual_seed(seed)
).images[0]
image
0%| | 0/150 [00:00<?, ?it/s]
Image Inpainting
인페인팅은 이미지에 마스크를 생성하고 프롬프트를 제공한 다음 생성 AI 모델이 프롬프트에 따라 마스크 대신 객체를 생성하기를 기대하는 작업입니다. 간단해 보이지만 바닐라 이미지 생성 모델을 훈련하는 것과는 훈련 전략이 다릅니다. 추가적인 미세 조정과 데이터가 필요합니다.
from diffusers import AutoPipelineForInpainting
from diffusers.utils import load_image
prompt = "A glass house in the middle of a ground"
image = pipeline(
prompt,
image=init_image,
mask_image=mask_image,
num_inference_steps=150,
generator=torch.manual_seed(seed)
).images[0]
image
0%| | 0/150 [00:00<?, ?it/s]
SXDL Inpainting
from diffusers import AutoPipelineForInpainting
from diffusers.utils import load_image, make_image_grid
import torch
prompt = "a cute baby lion sitting on a park bench"
negative_prompt = "bad anatomy, deformed, ugly, disfigured"
generator = torch.Generator(device="cuda").manual_seed(0)
NUM_INFERENCE_STES:
이미지 생성 중 노이즈 제거 단계 수를 제어합니다.
단계가 높을수록 더 많은 반복을 통해 출력을 세분화하여 이미지 품질을 향상시키지만 응답 시간이 길어집니다.
strength:
기본 이미지에 추가되는 노이즈 레벨을 결정하여 칠해진 영역이 원본과 얼마나 유사한지에 영향을 줍니다.
값이 1이면 원본의 흔적이 남지 않고, 0이면 원본 영역을 재구성합니다.
강도가 높을수록 노이즈와 베이스와의 편차가 커져 창의성이 향상되지만 처리 시간이 더 많이 소요됩니다.
guidance_scale:
텍스트 프롬프트와 생성된 이미지 사이의 정렬을 나타냅니다.
값이 클수록 프롬프트를 더 엄격하게 준수하므로 창의성이 떨어집니다.
값이 낮을수록 더 다양하고 창의적인 출력이 가능합니다.
negative_prompt:
이미지 생성 시 피해야 할 사항을 모델에 안내하는 역할을 합니다.
원치 않는 시각적 요소를 제거하여 최소한의 노력으로 이미지 품질을 향상시키는 데 도움이 됩니다.
padding_mask_crop:
이미지와 마스크 모두에서 지정된 패딩을 사용하여 마스크 영역을 자릅니다.
자른 영역이 업스케일링되어 원본 이미지에 오버레이되므로 복잡한 과정 없이 품질을 향상시킬 수 있습니다.
image = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
image=input_image,
mask_image=mask_image,
guidance_scale=8.0, # 텍스트 프롬프트와 생성된 이미지 사이의 Alignment에 영향을 줍니다.
num_inference_steps=20, # steps 15~30
strength=0.99, # `strength` below 1.0
generator=generator,
padding_mask_crop=32 #Crops masked area + padding from image and mask.
).images[0]