이런저런 IT 이야기
article thumbnail
Published 2023. 6. 1. 21:31
[Module] Diffusion #2 Stable Diffusion WebUI
반응형

sampler.py

"""SAMPLING ONLY."""

import torch

from .uni_pc import NoiseScheduleVP, model_wrapper, UniPC
from modules import shared, devices


class UniPCSampler(object):
    def __init__(self, model, **kwargs):
        super().__init__()
        self.model = model
        to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)
        self.before_sample = None
        self.after_sample = None
        self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod))

    def register_buffer(self, name, attr):
        if type(attr) == torch.Tensor:
            if attr.device != devices.device:
                attr = attr.to(devices.device)
        setattr(self, name, attr)

    def set_hooks(self, before_sample, after_sample, after_update):
        self.before_sample = before_sample
        self.after_sample = after_sample
        self.after_update = after_update

    @torch.no_grad()
    def sample(self,
               S,
               batch_size,
               shape,
               conditioning=None,
               callback=None,
               normals_sequence=None,
               img_callback=None,
               quantize_x0=False,
               eta=0.,
               mask=None,
               x0=None,
               temperature=1.,
               noise_dropout=0.,
               score_corrector=None,
               corrector_kwargs=None,
               verbose=True,
               x_T=None,
               log_every_t=100,
               unconditional_guidance_scale=1.,
               unconditional_conditioning=None,
               # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
               **kwargs
               ):
        if conditioning is not None:
            if isinstance(conditioning, dict):
                ctmp = conditioning[list(conditioning.keys())[0]]
                while isinstance(ctmp, list):
                    ctmp = ctmp[0]
                cbs = ctmp.shape[0]
                if cbs != batch_size:
                    print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")

            elif isinstance(conditioning, list):
                for ctmp in conditioning:
                    if ctmp.shape[0] != batch_size:
                        print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")

            else:
                if conditioning.shape[0] != batch_size:
                    print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")

        # sampling
        C, H, W = shape
        size = (batch_size, C, H, W)
        # print(f'Data shape for UniPC sampling is {size}')

        device = self.model.betas.device
        if x_T is None:
            img = torch.randn(size, device=device)
        else:
            img = x_T

        ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)

        # SD 1.X is "noise", SD 2.X is "v"
        model_type = "v" if self.model.parameterization == "v" else "noise"

        model_fn = model_wrapper(
            lambda x, t, c: self.model.apply_model(x, t, c),
            ns,
            model_type=model_type,
            guidance_type="classifier-free",
            #condition=conditioning,
            #unconditional_condition=unconditional_conditioning,
            guidance_scale=unconditional_guidance_scale,
        )

        uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, variant=shared.opts.uni_pc_variant, condition=conditioning, unconditional_condition=unconditional_conditioning, before_sample=self.before_sample, after_sample=self.after_sample, after_update=self.after_update)
        x = uni_pc.sample(img, steps=S, skip_type=shared.opts.uni_pc_skip_type, method="multistep", order=shared.opts.uni_pc_order, lower_order_final=shared.opts.uni_pc_lower_order_final)

        return x.to(device), None

ddpm_edit.py 파일은 Stable Diffusion 모델과 관련된 코드를 포함하고 있습니다. Stable Diffusion은 확률적 생성 모델로서, 이미지 생성 및 조작 작업에 사용될 수 있는 모델입니다. 아래는 해당 파일의 중요한 부분에 대한 분석입니다:

  1. Diffusion 클래스:
    • __init__ 메서드: Diffusion 모델 객체를 초기화합니다. 모델 구조, 잠재 공간 크기, 스케일 텐서, 스케일 조절 파라미터 등을 매개변수로 받습니다.
    • forward 메서드: 입력 이미지와 잠재 공간의 스케일 값을 받아 잠재 공간에서의 로그 가능도를 계산합니다.
    • reverse 메서드: 잠재 공간에서 샘플을 받아 입력 이미지로 변환합니다.
  2. CondModel 클래스:
    • __init__ 메서드: 조건부 모델 객체를 초기화합니다. 조건부 모델 구조, 잠재 공간 크기, 스케일 텐서, 스케일 조절 파라미터 등을 매개변수로 받습니다.
    • forward 메서드: 입력 이미지와 조건(텍스트 또는 태그)을 받아 조건부 로그 가능도를 계산합니다.
    • reverse 메서드: 조건과 잠재 공간에서 샘플을 받아 입력 이미지로 변환합니다.
  3. get_diffusion_model 함수:
    • get_diffusion_model 함수는 주어진 매개변수에 따라 Diffusion 모델 객체를 생성하고 반환합니다.
    • 모델 구조, 잠재 공간 크기, 스케일 텐서, 스케일 조절 파라미터 등을 기반으로 모델을 구성합니다.
  4. get_cond_model 함수:
    • get_cond_model 함수는 주어진 매개변수에 따라 조건부 모델 객체를 생성하고 반환합니다.
    • 조건부 모델 구조, 잠재 공간 크기, 스케일 텐서, 스케일 조절 파라미터 등을 기반으로 모델을 구성합니다.
반응형

'Stable Diffusion WebUI' 카테고리의 다른 글

[Module] Textual Inversion #1  (0) 2023.06.02
[Module] Diffusion #3  (0) 2023.06.01
[Module] Diffusion #1  (1) 2023.06.01
[Module] Hypernetworks  (0) 2023.06.01
[Module] CodeFormer  (0) 2023.06.01
profile

이런저런 IT 이야기

@이런저런 IT 이야기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

profile on loading

Loading...

검색 태그