"comfy/ldm/modules/vscode:/vscode.git/clone" did not exist on "89507f8adff4aff4507b6f35a67717badaecd4ac"
sample.py 5.38 KB
Newer Older
1
2
import torch
import comfy.model_management
3
import comfy.samplers
4
import comfy.conds
5
import comfy.utils
6
import math
7
import numpy as np
8

9
def prepare_noise(latent_image, seed, noise_inds=None):
10
11
12
13
    """
    creates random noise given a latent image and a seed.
    optional arg skip can be used to skip and discard x number of noise generations for a given seed
    """
BlenderNeko's avatar
BlenderNeko committed
14
    generator = torch.manual_seed(seed)
15
16
17
18
19
20
    if noise_inds is None:
        return torch.randn(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu")
    
    unique_inds, inverse = np.unique(noise_inds, return_inverse=True)
    noises = []
    for i in range(unique_inds[-1]+1):
BlenderNeko's avatar
BlenderNeko committed
21
        noise = torch.randn([1] + list(latent_image.size())[1:], dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu")
22
23
24
25
26
        if i in unique_inds:
            noises.append(noise)
    noises = [noises[i] for i in inverse]
    noises = torch.cat(noises, axis=0)
    return noises
27

28
def prepare_mask(noise_mask, shape, device):
29
    """ensures noise mask is of proper dimensions"""
30
    noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bilinear")
31
    noise_mask = noise_mask.round()
32
    noise_mask = torch.cat([noise_mask] * shape[1], dim=1)
33
    noise_mask = comfy.utils.repeat_to_batch_size(noise_mask, shape[0])
34
    noise_mask = noise_mask.to(device)
35
36
    return noise_mask

37
38
39
def get_models_from_cond(cond, model_type):
    models = []
    for c in cond:
40
41
        if model_type in c:
            models += [c[model_type]]
42
    return models
43

44
45
46
47
48
49
50
51
52
53
54
def convert_cond(cond):
    out = []
    for c in cond:
        temp = c[1].copy()
        model_conds = temp.get("model_conds", {})
        if c[0] is not None:
            model_conds["c_crossattn"] = comfy.conds.CONDCrossAttn(c[0])
        temp["model_conds"] = model_conds
        out.append(temp)
    return out

55
def get_additional_models(positive, negative, dtype):
BlenderNeko's avatar
BlenderNeko committed
56
    """loads additional models in positive and negative conditioning"""
57
    control_nets = set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control"))
comfyanonymous's avatar
comfyanonymous committed
58

59
    inference_memory = 0
comfyanonymous's avatar
comfyanonymous committed
60
61
62
    control_models = []
    for m in control_nets:
        control_models += m.get_models()
63
        inference_memory += m.inference_memory_requirements(dtype)
comfyanonymous's avatar
comfyanonymous committed
64

BlenderNeko's avatar
BlenderNeko committed
65
    gligen = get_models_from_cond(positive, "gligen") + get_models_from_cond(negative, "gligen")
comfyanonymous's avatar
comfyanonymous committed
66
67
    gligen = [x[1] for x in gligen]
    models = control_models + gligen
68
    return models, inference_memory
69
70

def cleanup_additional_models(models):
BlenderNeko's avatar
BlenderNeko committed
71
    """cleanup additional models that were loaded"""
72
    for m in models:
comfyanonymous's avatar
comfyanonymous committed
73
74
        if hasattr(m, 'cleanup'):
            m.cleanup()
75

76
77
def prepare_sampling(model, noise_shape, positive, negative, noise_mask):
    device = model.load_device
78
79
    positive = convert_cond(positive)
    negative = convert_cond(negative)
80
81

    if noise_mask is not None:
82
        noise_mask = prepare_mask(noise_mask, noise_shape, device)
83
84

    real_model = None
85
    models, inference_memory = get_additional_models(positive, negative, model.model_dtype())
86
    comfy.model_management.load_models_gpu([model] + models, model.memory_required([noise_shape[0] * 2] + list(noise_shape[1:])) + inference_memory)
87
88
    real_model = model.model

89
    return real_model, positive, negative, noise_mask, models
90

91

92
93
def sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False, noise_mask=None, sigmas=None, callback=None, disable_pbar=False, seed=None):
    real_model, positive_copy, negative_copy, noise_mask, models = prepare_sampling(model, noise.shape, positive, negative, noise_mask)
94

95
96
    noise = noise.to(model.load_device)
    latent_image = latent_image.to(model.load_device)
97

98
    sampler = comfy.samplers.KSampler(real_model, steps=steps, device=model.load_device, sampler=sampler_name, scheduler=scheduler, denoise=denoise, model_options=model.model_options)
99

100
    samples = sampler.sample(noise, positive_copy, negative_copy, cfg=cfg, latent_image=latent_image, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise, denoise_mask=noise_mask, sigmas=sigmas, callback=callback, disable_pbar=disable_pbar, seed=seed)
101
102
103
    samples = samples.cpu()

    cleanup_additional_models(models)
104
    cleanup_additional_models(set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control")))
105
    return samples
comfyanonymous's avatar
comfyanonymous committed
106
107
108
109
110
111
112
113
114
115

def sample_custom(model, noise, cfg, sampler, sigmas, positive, negative, latent_image, noise_mask=None, callback=None, disable_pbar=False, seed=None):
    real_model, positive_copy, negative_copy, noise_mask, models = prepare_sampling(model, noise.shape, positive, negative, noise_mask)
    noise = noise.to(model.load_device)
    latent_image = latent_image.to(model.load_device)
    sigmas = sigmas.to(model.load_device)

    samples = comfy.samplers.sample(real_model, noise, positive_copy, negative_copy, cfg, model.load_device, sampler, sigmas, model_options=model.model_options, latent_image=latent_image, denoise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed)
    samples = samples.cpu()
    cleanup_additional_models(models)
116
    cleanup_additional_models(set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control")))
comfyanonymous's avatar
comfyanonymous committed
117
118
    return samples