mirror of
https://git.datalinker.icu/comfyanonymous/ComfyUI
synced 2026-11-23 16:27:00 +08:00
Merge remote-tracking branch 'upstream/master' into connect-primitives-to-reroutes
This commit is contained in:
commit
3d2ae0e85a
@ -2,6 +2,13 @@ name: "Windows Release cu118 dependencies 2"
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
xformers:
|
||||||
|
description: 'xformers version'
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
default: "xformers"
|
||||||
|
|
||||||
# push:
|
# push:
|
||||||
# branches:
|
# branches:
|
||||||
# - master
|
# - master
|
||||||
@ -17,7 +24,7 @@ jobs:
|
|||||||
|
|
||||||
- shell: bash
|
- shell: bash
|
||||||
run: |
|
run: |
|
||||||
python -m pip wheel --no-cache-dir torch torchvision torchaudio xformers --extra-index-url https://download.pytorch.org/whl/cu118 -r requirements.txt pygit2 -w ./temp_wheel_dir
|
python -m pip wheel --no-cache-dir torch torchvision torchaudio ${{ inputs.xformers }} --extra-index-url https://download.pytorch.org/whl/cu118 -r requirements.txt pygit2 -w ./temp_wheel_dir
|
||||||
python -m pip install --no-cache-dir ./temp_wheel_dir/*
|
python -m pip install --no-cache-dir ./temp_wheel_dir/*
|
||||||
echo installed basic
|
echo installed basic
|
||||||
ls -lah temp_wheel_dir
|
ls -lah temp_wheel_dir
|
||||||
|
|||||||
@ -45,6 +45,8 @@ jobs:
|
|||||||
sed -i '1i../ComfyUI' ./python310._pth
|
sed -i '1i../ComfyUI' ./python310._pth
|
||||||
cd ..
|
cd ..
|
||||||
|
|
||||||
|
git clone https://github.com/comfyanonymous/taesd
|
||||||
|
cp taesd/*.pth ./ComfyUI_copy/models/vae_approx/
|
||||||
|
|
||||||
mkdir ComfyUI_windows_portable
|
mkdir ComfyUI_windows_portable
|
||||||
mv python_embeded ComfyUI_windows_portable
|
mv python_embeded ComfyUI_windows_portable
|
||||||
@ -59,7 +61,7 @@ jobs:
|
|||||||
|
|
||||||
cd ..
|
cd ..
|
||||||
|
|
||||||
"C:\Program Files\7-Zip\7z.exe" a -t7z -m0=lzma -mx=8 -mfb=64 -md=32m -ms=on ComfyUI_windows_portable.7z ComfyUI_windows_portable
|
"C:\Program Files\7-Zip\7z.exe" a -t7z -m0=lzma -mx=8 -mfb=64 -md=32m -ms=on -mf=BCJ2 ComfyUI_windows_portable.7z ComfyUI_windows_portable
|
||||||
mv ComfyUI_windows_portable.7z ComfyUI/new_ComfyUI_windows_portable_nvidia_cu118_or_cpu.7z
|
mv ComfyUI_windows_portable.7z ComfyUI/new_ComfyUI_windows_portable_nvidia_cu118_or_cpu.7z
|
||||||
|
|
||||||
cd ComfyUI_windows_portable
|
cd ComfyUI_windows_portable
|
||||||
|
|||||||
@ -31,12 +31,14 @@ jobs:
|
|||||||
echo 'import site' >> ./python311._pth
|
echo 'import site' >> ./python311._pth
|
||||||
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
|
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
|
||||||
./python.exe get-pip.py
|
./python.exe get-pip.py
|
||||||
python -m pip wheel torch torchvision torchaudio --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu121 -r ../ComfyUI/requirements.txt pygit2 -w ../temp_wheel_dir
|
python -m pip wheel torch torchvision torchaudio aiohttp==3.8.5 --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu121 -r ../ComfyUI/requirements.txt pygit2 -w ../temp_wheel_dir
|
||||||
ls ../temp_wheel_dir
|
ls ../temp_wheel_dir
|
||||||
./python.exe -s -m pip install --pre ../temp_wheel_dir/*
|
./python.exe -s -m pip install --pre ../temp_wheel_dir/*
|
||||||
sed -i '1i../ComfyUI' ./python311._pth
|
sed -i '1i../ComfyUI' ./python311._pth
|
||||||
cd ..
|
cd ..
|
||||||
|
|
||||||
|
git clone https://github.com/comfyanonymous/taesd
|
||||||
|
cp taesd/*.pth ./ComfyUI_copy/models/vae_approx/
|
||||||
|
|
||||||
mkdir ComfyUI_windows_portable_nightly_pytorch
|
mkdir ComfyUI_windows_portable_nightly_pytorch
|
||||||
mv python_embeded ComfyUI_windows_portable_nightly_pytorch
|
mv python_embeded ComfyUI_windows_portable_nightly_pytorch
|
||||||
@ -52,7 +54,7 @@ jobs:
|
|||||||
|
|
||||||
cd ..
|
cd ..
|
||||||
|
|
||||||
"C:\Program Files\7-Zip\7z.exe" a -t7z -m0=lzma -mx=8 -mfb=64 -md=32m -ms=on ComfyUI_windows_portable_nightly_pytorch.7z ComfyUI_windows_portable_nightly_pytorch
|
"C:\Program Files\7-Zip\7z.exe" a -t7z -m0=lzma -mx=8 -mfb=64 -md=32m -ms=on -mf=BCJ2 ComfyUI_windows_portable_nightly_pytorch.7z ComfyUI_windows_portable_nightly_pytorch
|
||||||
mv ComfyUI_windows_portable_nightly_pytorch.7z ComfyUI/ComfyUI_windows_portable_nvidia_or_cpu_nightly_pytorch.7z
|
mv ComfyUI_windows_portable_nightly_pytorch.7z ComfyUI/ComfyUI_windows_portable_nvidia_or_cpu_nightly_pytorch.7z
|
||||||
|
|
||||||
cd ComfyUI_windows_portable_nightly_pytorch
|
cd ComfyUI_windows_portable_nightly_pytorch
|
||||||
|
|||||||
1
CODEOWNERS
Normal file
1
CODEOWNERS
Normal file
@ -0,0 +1 @@
|
|||||||
|
* @comfyanonymous
|
||||||
18
README.md
18
README.md
@ -29,7 +29,8 @@ This ui will let you design and execute advanced stable diffusion pipelines usin
|
|||||||
- [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/)
|
- [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/)
|
||||||
- [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/)
|
- [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/)
|
||||||
- [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/)
|
- [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/)
|
||||||
- Latent previews with [TAESD](https://github.com/madebyollin/taesd)
|
- [Model Merging](https://comfyanonymous.github.io/ComfyUI_examples/model_merging/)
|
||||||
|
- Latent previews with [TAESD](#how-to-show-high-quality-previews)
|
||||||
- Starts up very fast.
|
- Starts up very fast.
|
||||||
- Works fully offline: will never download anything.
|
- Works fully offline: will never download anything.
|
||||||
- [Config file](extra_model_paths.yaml.example) to set the search paths for models.
|
- [Config file](extra_model_paths.yaml.example) to set the search paths for models.
|
||||||
@ -46,6 +47,7 @@ Workflow examples can be found on the [Examples page](https://comfyanonymous.git
|
|||||||
| Ctrl + O | Load workflow |
|
| Ctrl + O | Load workflow |
|
||||||
| Ctrl + A | Select all nodes |
|
| Ctrl + A | Select all nodes |
|
||||||
| Ctrl + M | Mute/unmute selected nodes |
|
| Ctrl + M | Mute/unmute selected nodes |
|
||||||
|
| Ctrl + B | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) |
|
||||||
| Delete/Backspace | Delete selected nodes |
|
| Delete/Backspace | Delete selected nodes |
|
||||||
| Ctrl + Delete/Backspace | Delete the current graph |
|
| Ctrl + Delete/Backspace | Delete the current graph |
|
||||||
| Space | Move the canvas around when held and moving the cursor |
|
| Space | Move the canvas around when held and moving the cursor |
|
||||||
@ -69,15 +71,15 @@ There is a portable standalone build for Windows that should work for running on
|
|||||||
|
|
||||||
### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/download/latest/ComfyUI_windows_portable_nvidia_cu118_or_cpu.7z)
|
### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/download/latest/ComfyUI_windows_portable_nvidia_cu118_or_cpu.7z)
|
||||||
|
|
||||||
Just download, extract and run. Make sure you put your Stable Diffusion checkpoints/models (the huge ckpt/safetensors files) in: ComfyUI\models\checkpoints
|
Simply download, extract with [7-Zip](https://7-zip.org) and run. Make sure you put your Stable Diffusion checkpoints/models (the huge ckpt/safetensors files) in: ComfyUI\models\checkpoints
|
||||||
|
|
||||||
#### How do I share models between another UI and ComfyUI?
|
#### How do I share models between another UI and ComfyUI?
|
||||||
|
|
||||||
See the [Config file](extra_model_paths.yaml.example) to set the search paths for models. In the standalone windows build you can find this file in the ComfyUI directory. Rename this file to extra_model_paths.yaml and edit it with your favorite text editor.
|
See the [Config file](extra_model_paths.yaml.example) to set the search paths for models. In the standalone windows build you can find this file in the ComfyUI directory. Rename this file to extra_model_paths.yaml and edit it with your favorite text editor.
|
||||||
|
|
||||||
## Colab Notebook
|
## Jupyter Notebook
|
||||||
|
|
||||||
To run it on colab or paperspace you can use my [Colab Notebook](notebooks/comfyui_colab.ipynb) here: [Link to open with google colab](https://colab.research.google.com/github/comfyanonymous/ComfyUI/blob/master/notebooks/comfyui_colab.ipynb)
|
To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb)
|
||||||
|
|
||||||
## Manual Install (Windows, Linux)
|
## Manual Install (Windows, Linux)
|
||||||
|
|
||||||
@ -92,8 +94,8 @@ AMD users can install rocm and pytorch with pip if you don't have it already ins
|
|||||||
|
|
||||||
```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/rocm5.4.2```
|
```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/rocm5.4.2```
|
||||||
|
|
||||||
This is the command to install the nightly with ROCm 5.5 that supports the 7000 series and might have some performance improvements:
|
This is the command to install the nightly with ROCm 5.6 that supports the 7000 series and might have some performance improvements:
|
||||||
```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm5.5 -r requirements.txt```
|
```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm5.6```
|
||||||
|
|
||||||
### NVIDIA
|
### NVIDIA
|
||||||
|
|
||||||
@ -125,10 +127,10 @@ After this you should have everything installed and can proceed to running Comfy
|
|||||||
|
|
||||||
You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
|
You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
|
||||||
|
|
||||||
1. Install pytorch. For instructions, read the [Accelerated PyTorch training on Mac](https://developer.apple.com/metal/pytorch/) Apple Developer guide.
|
1. Install pytorch nightly. For instructions, read the [Accelerated PyTorch training on Mac](https://developer.apple.com/metal/pytorch/) Apple Developer guide (make sure to install the latest pytorch nightly).
|
||||||
1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
|
1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
|
||||||
1. Install the ComfyUI [dependencies](#dependencies). If you have another Stable Diffusion UI [you might be able to reuse the dependencies](#i-already-have-another-ui-for-stable-diffusion-installed-do-i-really-have-to-install-all-of-these-dependencies).
|
1. Install the ComfyUI [dependencies](#dependencies). If you have another Stable Diffusion UI [you might be able to reuse the dependencies](#i-already-have-another-ui-for-stable-diffusion-installed-do-i-really-have-to-install-all-of-these-dependencies).
|
||||||
1. Launch ComfyUI by running `python main.py`.
|
1. Launch ComfyUI by running `python main.py --force-fp16`. Note that --force-fp16 will only work if you installed the latest pytorch nightly.
|
||||||
|
|
||||||
> **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
|
> **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
|
||||||
|
|
||||||
|
|||||||
@ -6,16 +6,14 @@ import torch as th
|
|||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
|
|
||||||
from ..ldm.modules.diffusionmodules.util import (
|
from ..ldm.modules.diffusionmodules.util import (
|
||||||
conv_nd,
|
|
||||||
linear,
|
|
||||||
zero_module,
|
zero_module,
|
||||||
timestep_embedding,
|
timestep_embedding,
|
||||||
)
|
)
|
||||||
|
|
||||||
from ..ldm.modules.attention import SpatialTransformer
|
from ..ldm.modules.attention import SpatialTransformer
|
||||||
from ..ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock
|
from ..ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample
|
||||||
from ..ldm.util import exists
|
from ..ldm.util import exists
|
||||||
|
import comfy.ops
|
||||||
|
|
||||||
class ControlledUnetModel(UNetModel):
|
class ControlledUnetModel(UNetModel):
|
||||||
#implemented in the ldm unet
|
#implemented in the ldm unet
|
||||||
@ -55,8 +53,11 @@ class ControlNet(nn.Module):
|
|||||||
use_linear_in_transformer=False,
|
use_linear_in_transformer=False,
|
||||||
adm_in_channels=None,
|
adm_in_channels=None,
|
||||||
transformer_depth_middle=None,
|
transformer_depth_middle=None,
|
||||||
|
device=None,
|
||||||
|
operations=comfy.ops,
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
|
||||||
if use_spatial_transformer:
|
if use_spatial_transformer:
|
||||||
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
||||||
|
|
||||||
@ -116,9 +117,9 @@ class ControlNet(nn.Module):
|
|||||||
|
|
||||||
time_embed_dim = model_channels * 4
|
time_embed_dim = model_channels * 4
|
||||||
self.time_embed = nn.Sequential(
|
self.time_embed = nn.Sequential(
|
||||||
linear(model_channels, time_embed_dim),
|
operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
linear(time_embed_dim, time_embed_dim),
|
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.num_classes is not None:
|
if self.num_classes is not None:
|
||||||
@ -131,9 +132,9 @@ class ControlNet(nn.Module):
|
|||||||
assert adm_in_channels is not None
|
assert adm_in_channels is not None
|
||||||
self.label_emb = nn.Sequential(
|
self.label_emb = nn.Sequential(
|
||||||
nn.Sequential(
|
nn.Sequential(
|
||||||
linear(adm_in_channels, time_embed_dim),
|
operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
linear(time_embed_dim, time_embed_dim),
|
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@ -142,28 +143,28 @@ class ControlNet(nn.Module):
|
|||||||
self.input_blocks = nn.ModuleList(
|
self.input_blocks = nn.ModuleList(
|
||||||
[
|
[
|
||||||
TimestepEmbedSequential(
|
TimestepEmbedSequential(
|
||||||
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)])
|
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations)])
|
||||||
|
|
||||||
self.input_hint_block = TimestepEmbedSequential(
|
self.input_hint_block = TimestepEmbedSequential(
|
||||||
conv_nd(dims, hint_channels, 16, 3, padding=1),
|
operations.conv_nd(dims, hint_channels, 16, 3, padding=1),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
conv_nd(dims, 16, 16, 3, padding=1),
|
operations.conv_nd(dims, 16, 16, 3, padding=1),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
conv_nd(dims, 16, 32, 3, padding=1, stride=2),
|
operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
conv_nd(dims, 32, 32, 3, padding=1),
|
operations.conv_nd(dims, 32, 32, 3, padding=1),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
conv_nd(dims, 32, 96, 3, padding=1, stride=2),
|
operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
conv_nd(dims, 96, 96, 3, padding=1),
|
operations.conv_nd(dims, 96, 96, 3, padding=1),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
conv_nd(dims, 96, 256, 3, padding=1, stride=2),
|
operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
zero_module(conv_nd(dims, 256, model_channels, 3, padding=1))
|
zero_module(operations.conv_nd(dims, 256, model_channels, 3, padding=1))
|
||||||
)
|
)
|
||||||
|
|
||||||
self._feature_size = model_channels
|
self._feature_size = model_channels
|
||||||
@ -181,6 +182,7 @@ class ControlNet(nn.Module):
|
|||||||
dims=dims,
|
dims=dims,
|
||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
|
operations=operations
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
ch = mult * model_channels
|
ch = mult * model_channels
|
||||||
@ -200,20 +202,14 @@ class ControlNet(nn.Module):
|
|||||||
|
|
||||||
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
||||||
layers.append(
|
layers.append(
|
||||||
AttentionBlock(
|
SpatialTransformer(
|
||||||
ch,
|
|
||||||
use_checkpoint=use_checkpoint,
|
|
||||||
num_heads=num_heads,
|
|
||||||
num_head_channels=dim_head,
|
|
||||||
use_new_attention_order=use_new_attention_order,
|
|
||||||
) if not use_spatial_transformer else SpatialTransformer(
|
|
||||||
ch, num_heads, dim_head, depth=transformer_depth[level], context_dim=context_dim,
|
ch, num_heads, dim_head, depth=transformer_depth[level], context_dim=context_dim,
|
||||||
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
||||||
use_checkpoint=use_checkpoint
|
use_checkpoint=use_checkpoint, operations=operations
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
||||||
self.zero_convs.append(self.make_zero_conv(ch))
|
self.zero_convs.append(self.make_zero_conv(ch, operations=operations))
|
||||||
self._feature_size += ch
|
self._feature_size += ch
|
||||||
input_block_chans.append(ch)
|
input_block_chans.append(ch)
|
||||||
if level != len(channel_mult) - 1:
|
if level != len(channel_mult) - 1:
|
||||||
@ -229,16 +225,17 @@ class ControlNet(nn.Module):
|
|||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
down=True,
|
down=True,
|
||||||
|
operations=operations
|
||||||
)
|
)
|
||||||
if resblock_updown
|
if resblock_updown
|
||||||
else Downsample(
|
else Downsample(
|
||||||
ch, conv_resample, dims=dims, out_channels=out_ch
|
ch, conv_resample, dims=dims, out_channels=out_ch, operations=operations
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
ch = out_ch
|
ch = out_ch
|
||||||
input_block_chans.append(ch)
|
input_block_chans.append(ch)
|
||||||
self.zero_convs.append(self.make_zero_conv(ch))
|
self.zero_convs.append(self.make_zero_conv(ch, operations=operations))
|
||||||
ds *= 2
|
ds *= 2
|
||||||
self._feature_size += ch
|
self._feature_size += ch
|
||||||
|
|
||||||
@ -258,17 +255,12 @@ class ControlNet(nn.Module):
|
|||||||
dims=dims,
|
dims=dims,
|
||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
|
operations=operations
|
||||||
),
|
),
|
||||||
AttentionBlock(
|
SpatialTransformer( # always uses a self-attn
|
||||||
ch,
|
|
||||||
use_checkpoint=use_checkpoint,
|
|
||||||
num_heads=num_heads,
|
|
||||||
num_head_channels=dim_head,
|
|
||||||
use_new_attention_order=use_new_attention_order,
|
|
||||||
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
|
|
||||||
ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
|
ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
|
||||||
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
||||||
use_checkpoint=use_checkpoint
|
use_checkpoint=use_checkpoint, operations=operations
|
||||||
),
|
),
|
||||||
ResBlock(
|
ResBlock(
|
||||||
ch,
|
ch,
|
||||||
@ -277,16 +269,17 @@ class ControlNet(nn.Module):
|
|||||||
dims=dims,
|
dims=dims,
|
||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
|
operations=operations
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
self.middle_block_out = self.make_zero_conv(ch)
|
self.middle_block_out = self.make_zero_conv(ch, operations=operations)
|
||||||
self._feature_size += ch
|
self._feature_size += ch
|
||||||
|
|
||||||
def make_zero_conv(self, channels):
|
def make_zero_conv(self, channels, operations=None):
|
||||||
return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0)))
|
return TimestepEmbedSequential(zero_module(operations.conv_nd(self.dims, channels, channels, 1, padding=0)))
|
||||||
|
|
||||||
def forward(self, x, hint, timesteps, context, y=None, **kwargs):
|
def forward(self, x, hint, timesteps, context, y=None, **kwargs):
|
||||||
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(self.dtype)
|
||||||
emb = self.time_embed(t_emb)
|
emb = self.time_embed(t_emb)
|
||||||
|
|
||||||
guided_hint = self.input_hint_block(hint, emb, context)
|
guided_hint = self.input_hint_block(hint, emb, context)
|
||||||
@ -294,9 +287,6 @@ class ControlNet(nn.Module):
|
|||||||
outs = []
|
outs = []
|
||||||
|
|
||||||
hs = []
|
hs = []
|
||||||
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
|
||||||
emb = self.time_embed(t_emb)
|
|
||||||
|
|
||||||
if self.num_classes is not None:
|
if self.num_classes is not None:
|
||||||
assert y.shape[0] == x.shape[0]
|
assert y.shape[0] == x.shape[0]
|
||||||
emb = emb + self.label_emb(y)
|
emb = emb + self.label_emb(y)
|
||||||
|
|||||||
@ -38,12 +38,29 @@ parser.add_argument("--port", type=int, default=8188, help="Set the listen port.
|
|||||||
parser.add_argument("--enable-cors-header", type=str, default=None, metavar="ORIGIN", nargs="?", const="*", help="Enable CORS (Cross-Origin Resource Sharing) with optional origin or allow all with default '*'.")
|
parser.add_argument("--enable-cors-header", type=str, default=None, metavar="ORIGIN", nargs="?", const="*", help="Enable CORS (Cross-Origin Resource Sharing) with optional origin or allow all with default '*'.")
|
||||||
parser.add_argument("--extra-model-paths-config", type=str, default=None, metavar="PATH", nargs='+', action='append', help="Load one or more extra_model_paths.yaml files.")
|
parser.add_argument("--extra-model-paths-config", type=str, default=None, metavar="PATH", nargs='+', action='append', help="Load one or more extra_model_paths.yaml files.")
|
||||||
parser.add_argument("--output-directory", type=str, default=None, help="Set the ComfyUI output directory.")
|
parser.add_argument("--output-directory", type=str, default=None, help="Set the ComfyUI output directory.")
|
||||||
|
parser.add_argument("--temp-directory", type=str, default=None, help="Set the ComfyUI temp directory (default is in the ComfyUI directory).")
|
||||||
parser.add_argument("--auto-launch", action="store_true", help="Automatically launch ComfyUI in the default browser.")
|
parser.add_argument("--auto-launch", action="store_true", help="Automatically launch ComfyUI in the default browser.")
|
||||||
|
parser.add_argument("--disable-auto-launch", action="store_true", help="Disable auto launching the browser.")
|
||||||
parser.add_argument("--cuda-device", type=int, default=None, metavar="DEVICE_ID", help="Set the id of the cuda device this instance will use.")
|
parser.add_argument("--cuda-device", type=int, default=None, metavar="DEVICE_ID", help="Set the id of the cuda device this instance will use.")
|
||||||
|
cm_group = parser.add_mutually_exclusive_group()
|
||||||
|
cm_group.add_argument("--cuda-malloc", action="store_true", help="Enable cudaMallocAsync (enabled by default for torch 2.0 and up).")
|
||||||
|
cm_group.add_argument("--disable-cuda-malloc", action="store_true", help="Disable cudaMallocAsync.")
|
||||||
|
|
||||||
parser.add_argument("--dont-upcast-attention", action="store_true", help="Disable upcasting of attention. Can boost speed but increase the chances of black images.")
|
parser.add_argument("--dont-upcast-attention", action="store_true", help="Disable upcasting of attention. Can boost speed but increase the chances of black images.")
|
||||||
parser.add_argument("--force-fp32", action="store_true", help="Force fp32 (If this makes your GPU work better please report it).")
|
|
||||||
|
fp_group = parser.add_mutually_exclusive_group()
|
||||||
|
fp_group.add_argument("--force-fp32", action="store_true", help="Force fp32 (If this makes your GPU work better please report it).")
|
||||||
|
fp_group.add_argument("--force-fp16", action="store_true", help="Force fp16.")
|
||||||
|
|
||||||
|
fpvae_group = parser.add_mutually_exclusive_group()
|
||||||
|
fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")
|
||||||
|
fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")
|
||||||
|
fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")
|
||||||
|
|
||||||
parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
|
parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")
|
||||||
|
|
||||||
|
parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize when loading models with Intel GPUs.")
|
||||||
|
|
||||||
class LatentPreviewMethod(enum.Enum):
|
class LatentPreviewMethod(enum.Enum):
|
||||||
NoPreviews = "none"
|
NoPreviews = "none"
|
||||||
Auto = "auto"
|
Auto = "auto"
|
||||||
@ -68,11 +85,19 @@ vram_group.add_argument("--novram", action="store_true", help="When lowvram isn'
|
|||||||
vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
|
vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
|
||||||
|
|
||||||
|
|
||||||
|
parser.add_argument("--disable-smart-memory", action="store_true", help="Force ComfyUI to agressively offload to regular ram instead of keeping models in vram when it can.")
|
||||||
|
|
||||||
|
|
||||||
parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
|
parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
|
||||||
parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
|
parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
|
||||||
parser.add_argument("--windows-standalone-build", action="store_true", help="Windows standalone build: Enable convenient things that most people using the standalone windows build will probably enjoy (like auto opening the page on startup).")
|
parser.add_argument("--windows-standalone-build", action="store_true", help="Windows standalone build: Enable convenient things that most people using the standalone windows build will probably enjoy (like auto opening the page on startup).")
|
||||||
|
|
||||||
|
parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
if args.windows_standalone_build:
|
if args.windows_standalone_build:
|
||||||
args.auto_launch = True
|
args.auto_launch = True
|
||||||
|
|
||||||
|
if args.disable_auto_launch:
|
||||||
|
args.auto_launch = False
|
||||||
|
|||||||
@ -17,7 +17,7 @@
|
|||||||
"num_attention_heads": 20,
|
"num_attention_heads": 20,
|
||||||
"num_hidden_layers": 32,
|
"num_hidden_layers": 32,
|
||||||
"pad_token_id": 1,
|
"pad_token_id": 1,
|
||||||
"projection_dim": 512,
|
"projection_dim": 1280,
|
||||||
"torch_dtype": "float32",
|
"torch_dtype": "float32",
|
||||||
"vocab_size": 49408
|
"vocab_size": 49408
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,14 +2,27 @@ from transformers import CLIPVisionModelWithProjection, CLIPVisionConfig, CLIPIm
|
|||||||
from .utils import load_torch_file, transformers_convert
|
from .utils import load_torch_file, transformers_convert
|
||||||
import os
|
import os
|
||||||
import torch
|
import torch
|
||||||
|
import contextlib
|
||||||
|
|
||||||
import comfy.ops
|
import comfy.ops
|
||||||
|
import comfy.model_patcher
|
||||||
|
import comfy.model_management
|
||||||
|
|
||||||
class ClipVisionModel():
|
class ClipVisionModel():
|
||||||
def __init__(self, json_config):
|
def __init__(self, json_config):
|
||||||
config = CLIPVisionConfig.from_json_file(json_config)
|
config = CLIPVisionConfig.from_json_file(json_config)
|
||||||
with comfy.ops.use_comfy_ops():
|
self.load_device = comfy.model_management.text_encoder_device()
|
||||||
|
offload_device = comfy.model_management.text_encoder_offload_device()
|
||||||
|
self.dtype = torch.float32
|
||||||
|
if comfy.model_management.should_use_fp16(self.load_device, prioritize_performance=False):
|
||||||
|
self.dtype = torch.float16
|
||||||
|
|
||||||
|
with comfy.ops.use_comfy_ops(offload_device, self.dtype):
|
||||||
with modeling_utils.no_init_weights():
|
with modeling_utils.no_init_weights():
|
||||||
self.model = CLIPVisionModelWithProjection(config)
|
self.model = CLIPVisionModelWithProjection(config)
|
||||||
|
self.model.to(self.dtype)
|
||||||
|
|
||||||
|
self.patcher = comfy.model_patcher.ModelPatcher(self.model, load_device=self.load_device, offload_device=offload_device)
|
||||||
self.processor = CLIPImageProcessor(crop_size=224,
|
self.processor = CLIPImageProcessor(crop_size=224,
|
||||||
do_center_crop=True,
|
do_center_crop=True,
|
||||||
do_convert_rgb=True,
|
do_convert_rgb=True,
|
||||||
@ -24,9 +37,28 @@ class ClipVisionModel():
|
|||||||
return self.model.load_state_dict(sd, strict=False)
|
return self.model.load_state_dict(sd, strict=False)
|
||||||
|
|
||||||
def encode_image(self, image):
|
def encode_image(self, image):
|
||||||
img = torch.clip((255. * image[0]), 0, 255).round().int()
|
img = torch.clip((255. * image), 0, 255).round().int()
|
||||||
inputs = self.processor(images=[img], return_tensors="pt")
|
img = list(map(lambda a: a, img))
|
||||||
outputs = self.model(**inputs)
|
inputs = self.processor(images=img, return_tensors="pt")
|
||||||
|
comfy.model_management.load_model_gpu(self.patcher)
|
||||||
|
pixel_values = inputs['pixel_values'].to(self.load_device)
|
||||||
|
|
||||||
|
if self.dtype != torch.float32:
|
||||||
|
precision_scope = torch.autocast
|
||||||
|
else:
|
||||||
|
precision_scope = lambda a, b: contextlib.nullcontext(a)
|
||||||
|
|
||||||
|
with precision_scope(comfy.model_management.get_autocast_device(self.load_device), torch.float32):
|
||||||
|
outputs = self.model(pixel_values=pixel_values, output_hidden_states=True)
|
||||||
|
|
||||||
|
for k in outputs:
|
||||||
|
t = outputs[k]
|
||||||
|
if t is not None:
|
||||||
|
if k == 'hidden_states':
|
||||||
|
outputs["penultimate_hidden_states"] = t[-2].cpu()
|
||||||
|
else:
|
||||||
|
outputs[k] = t.cpu()
|
||||||
|
|
||||||
return outputs
|
return outputs
|
||||||
|
|
||||||
def convert_to_transformers(sd, prefix):
|
def convert_to_transformers(sd, prefix):
|
||||||
@ -49,18 +81,22 @@ def convert_to_transformers(sd, prefix):
|
|||||||
if "{}proj".format(prefix) in sd_k:
|
if "{}proj".format(prefix) in sd_k:
|
||||||
sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
|
sd['visual_projection.weight'] = sd.pop("{}proj".format(prefix)).transpose(0, 1)
|
||||||
|
|
||||||
sd = transformers_convert(sd, prefix, "vision_model.", 32)
|
sd = transformers_convert(sd, prefix, "vision_model.", 48)
|
||||||
return sd
|
return sd
|
||||||
|
|
||||||
def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
|
def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
|
||||||
if convert_keys:
|
if convert_keys:
|
||||||
sd = convert_to_transformers(sd, prefix)
|
sd = convert_to_transformers(sd, prefix)
|
||||||
if "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
|
if "vision_model.encoder.layers.47.layer_norm1.weight" in sd:
|
||||||
|
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_g.json")
|
||||||
|
elif "vision_model.encoder.layers.30.layer_norm1.weight" in sd:
|
||||||
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
|
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_h.json")
|
||||||
else:
|
else:
|
||||||
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
|
json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_vision_config_vitl.json")
|
||||||
clip = ClipVisionModel(json_config)
|
clip = ClipVisionModel(json_config)
|
||||||
m, u = clip.load_sd(sd)
|
m, u = clip.load_sd(sd)
|
||||||
|
if len(m) > 0:
|
||||||
|
print("missing clip vision:", m)
|
||||||
u = set(u)
|
u = set(u)
|
||||||
keys = list(sd.keys())
|
keys = list(sd.keys())
|
||||||
for k in keys:
|
for k in keys:
|
||||||
@ -71,4 +107,7 @@ def load_clipvision_from_sd(sd, prefix="", convert_keys=False):
|
|||||||
|
|
||||||
def load(ckpt_path):
|
def load(ckpt_path):
|
||||||
sd = load_torch_file(ckpt_path)
|
sd = load_torch_file(ckpt_path)
|
||||||
return load_clipvision_from_sd(sd)
|
if "visual.transformer.resblocks.0.attn.in_proj_weight" in sd:
|
||||||
|
return load_clipvision_from_sd(sd, prefix="visual.", convert_keys=True)
|
||||||
|
else:
|
||||||
|
return load_clipvision_from_sd(sd)
|
||||||
|
|||||||
18
comfy/clip_vision_config_g.json
Normal file
18
comfy/clip_vision_config_g.json
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"attention_dropout": 0.0,
|
||||||
|
"dropout": 0.0,
|
||||||
|
"hidden_act": "gelu",
|
||||||
|
"hidden_size": 1664,
|
||||||
|
"image_size": 224,
|
||||||
|
"initializer_factor": 1.0,
|
||||||
|
"initializer_range": 0.02,
|
||||||
|
"intermediate_size": 8192,
|
||||||
|
"layer_norm_eps": 1e-05,
|
||||||
|
"model_type": "clip_vision_model",
|
||||||
|
"num_attention_heads": 16,
|
||||||
|
"num_channels": 3,
|
||||||
|
"num_hidden_layers": 48,
|
||||||
|
"patch_size": 14,
|
||||||
|
"projection_dim": 1280,
|
||||||
|
"torch_dtype": "float32"
|
||||||
|
}
|
||||||
488
comfy/controlnet.py
Normal file
488
comfy/controlnet.py
Normal file
@ -0,0 +1,488 @@
|
|||||||
|
import torch
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import comfy.utils
|
||||||
|
import comfy.model_management
|
||||||
|
import comfy.model_detection
|
||||||
|
import comfy.model_patcher
|
||||||
|
|
||||||
|
import comfy.cldm.cldm
|
||||||
|
import comfy.t2i_adapter.adapter
|
||||||
|
|
||||||
|
|
||||||
|
def broadcast_image_to(tensor, target_batch_size, batched_number):
|
||||||
|
current_batch_size = tensor.shape[0]
|
||||||
|
#print(current_batch_size, target_batch_size)
|
||||||
|
if current_batch_size == 1:
|
||||||
|
return tensor
|
||||||
|
|
||||||
|
per_batch = target_batch_size // batched_number
|
||||||
|
tensor = tensor[:per_batch]
|
||||||
|
|
||||||
|
if per_batch > tensor.shape[0]:
|
||||||
|
tensor = torch.cat([tensor] * (per_batch // tensor.shape[0]) + [tensor[:(per_batch % tensor.shape[0])]], dim=0)
|
||||||
|
|
||||||
|
current_batch_size = tensor.shape[0]
|
||||||
|
if current_batch_size == target_batch_size:
|
||||||
|
return tensor
|
||||||
|
else:
|
||||||
|
return torch.cat([tensor] * batched_number, dim=0)
|
||||||
|
|
||||||
|
class ControlBase:
|
||||||
|
def __init__(self, device=None):
|
||||||
|
self.cond_hint_original = None
|
||||||
|
self.cond_hint = None
|
||||||
|
self.strength = 1.0
|
||||||
|
self.timestep_percent_range = (1.0, 0.0)
|
||||||
|
self.timestep_range = None
|
||||||
|
|
||||||
|
if device is None:
|
||||||
|
device = comfy.model_management.get_torch_device()
|
||||||
|
self.device = device
|
||||||
|
self.previous_controlnet = None
|
||||||
|
self.global_average_pooling = False
|
||||||
|
|
||||||
|
def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(1.0, 0.0)):
|
||||||
|
self.cond_hint_original = cond_hint
|
||||||
|
self.strength = strength
|
||||||
|
self.timestep_percent_range = timestep_percent_range
|
||||||
|
return self
|
||||||
|
|
||||||
|
def pre_run(self, model, percent_to_timestep_function):
|
||||||
|
self.timestep_range = (percent_to_timestep_function(self.timestep_percent_range[0]), percent_to_timestep_function(self.timestep_percent_range[1]))
|
||||||
|
if self.previous_controlnet is not None:
|
||||||
|
self.previous_controlnet.pre_run(model, percent_to_timestep_function)
|
||||||
|
|
||||||
|
def set_previous_controlnet(self, controlnet):
|
||||||
|
self.previous_controlnet = controlnet
|
||||||
|
return self
|
||||||
|
|
||||||
|
def cleanup(self):
|
||||||
|
if self.previous_controlnet is not None:
|
||||||
|
self.previous_controlnet.cleanup()
|
||||||
|
if self.cond_hint is not None:
|
||||||
|
del self.cond_hint
|
||||||
|
self.cond_hint = None
|
||||||
|
self.timestep_range = None
|
||||||
|
|
||||||
|
def get_models(self):
|
||||||
|
out = []
|
||||||
|
if self.previous_controlnet is not None:
|
||||||
|
out += self.previous_controlnet.get_models()
|
||||||
|
return out
|
||||||
|
|
||||||
|
def copy_to(self, c):
|
||||||
|
c.cond_hint_original = self.cond_hint_original
|
||||||
|
c.strength = self.strength
|
||||||
|
c.timestep_percent_range = self.timestep_percent_range
|
||||||
|
|
||||||
|
def inference_memory_requirements(self, dtype):
|
||||||
|
if self.previous_controlnet is not None:
|
||||||
|
return self.previous_controlnet.inference_memory_requirements(dtype)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def control_merge(self, control_input, control_output, control_prev, output_dtype):
|
||||||
|
out = {'input':[], 'middle':[], 'output': []}
|
||||||
|
|
||||||
|
if control_input is not None:
|
||||||
|
for i in range(len(control_input)):
|
||||||
|
key = 'input'
|
||||||
|
x = control_input[i]
|
||||||
|
if x is not None:
|
||||||
|
x *= self.strength
|
||||||
|
if x.dtype != output_dtype:
|
||||||
|
x = x.to(output_dtype)
|
||||||
|
out[key].insert(0, x)
|
||||||
|
|
||||||
|
if control_output is not None:
|
||||||
|
for i in range(len(control_output)):
|
||||||
|
if i == (len(control_output) - 1):
|
||||||
|
key = 'middle'
|
||||||
|
index = 0
|
||||||
|
else:
|
||||||
|
key = 'output'
|
||||||
|
index = i
|
||||||
|
x = control_output[i]
|
||||||
|
if x is not None:
|
||||||
|
if self.global_average_pooling:
|
||||||
|
x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
|
||||||
|
|
||||||
|
x *= self.strength
|
||||||
|
if x.dtype != output_dtype:
|
||||||
|
x = x.to(output_dtype)
|
||||||
|
|
||||||
|
out[key].append(x)
|
||||||
|
if control_prev is not None:
|
||||||
|
for x in ['input', 'middle', 'output']:
|
||||||
|
o = out[x]
|
||||||
|
for i in range(len(control_prev[x])):
|
||||||
|
prev_val = control_prev[x][i]
|
||||||
|
if i >= len(o):
|
||||||
|
o.append(prev_val)
|
||||||
|
elif prev_val is not None:
|
||||||
|
if o[i] is None:
|
||||||
|
o[i] = prev_val
|
||||||
|
else:
|
||||||
|
o[i] += prev_val
|
||||||
|
return out
|
||||||
|
|
||||||
|
class ControlNet(ControlBase):
|
||||||
|
def __init__(self, control_model, global_average_pooling=False, device=None):
|
||||||
|
super().__init__(device)
|
||||||
|
self.control_model = control_model
|
||||||
|
self.control_model_wrapped = comfy.model_patcher.ModelPatcher(self.control_model, load_device=comfy.model_management.get_torch_device(), offload_device=comfy.model_management.unet_offload_device())
|
||||||
|
self.global_average_pooling = global_average_pooling
|
||||||
|
|
||||||
|
def get_control(self, x_noisy, t, cond, batched_number):
|
||||||
|
control_prev = None
|
||||||
|
if self.previous_controlnet is not None:
|
||||||
|
control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
|
||||||
|
|
||||||
|
if self.timestep_range is not None:
|
||||||
|
if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
|
||||||
|
if control_prev is not None:
|
||||||
|
return control_prev
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
output_dtype = x_noisy.dtype
|
||||||
|
if self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
|
||||||
|
if self.cond_hint is not None:
|
||||||
|
del self.cond_hint
|
||||||
|
self.cond_hint = None
|
||||||
|
self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(self.control_model.dtype).to(self.device)
|
||||||
|
if x_noisy.shape[0] != self.cond_hint.shape[0]:
|
||||||
|
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
|
||||||
|
|
||||||
|
|
||||||
|
context = cond['c_crossattn']
|
||||||
|
y = cond.get('c_adm', None)
|
||||||
|
if y is not None:
|
||||||
|
y = y.to(self.control_model.dtype)
|
||||||
|
control = self.control_model(x=x_noisy.to(self.control_model.dtype), hint=self.cond_hint, timesteps=t, context=context.to(self.control_model.dtype), y=y)
|
||||||
|
return self.control_merge(None, control, control_prev, output_dtype)
|
||||||
|
|
||||||
|
def copy(self):
|
||||||
|
c = ControlNet(self.control_model, global_average_pooling=self.global_average_pooling)
|
||||||
|
self.copy_to(c)
|
||||||
|
return c
|
||||||
|
|
||||||
|
def get_models(self):
|
||||||
|
out = super().get_models()
|
||||||
|
out.append(self.control_model_wrapped)
|
||||||
|
return out
|
||||||
|
|
||||||
|
class ControlLoraOps:
|
||||||
|
class Linear(torch.nn.Module):
|
||||||
|
def __init__(self, in_features: int, out_features: int, bias: bool = True,
|
||||||
|
device=None, dtype=None) -> None:
|
||||||
|
factory_kwargs = {'device': device, 'dtype': dtype}
|
||||||
|
super().__init__()
|
||||||
|
self.in_features = in_features
|
||||||
|
self.out_features = out_features
|
||||||
|
self.weight = None
|
||||||
|
self.up = None
|
||||||
|
self.down = None
|
||||||
|
self.bias = None
|
||||||
|
|
||||||
|
def forward(self, input):
|
||||||
|
if self.up is not None:
|
||||||
|
return torch.nn.functional.linear(input, self.weight.to(input.device) + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), self.bias)
|
||||||
|
else:
|
||||||
|
return torch.nn.functional.linear(input, self.weight.to(input.device), self.bias)
|
||||||
|
|
||||||
|
class Conv2d(torch.nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
in_channels,
|
||||||
|
out_channels,
|
||||||
|
kernel_size,
|
||||||
|
stride=1,
|
||||||
|
padding=0,
|
||||||
|
dilation=1,
|
||||||
|
groups=1,
|
||||||
|
bias=True,
|
||||||
|
padding_mode='zeros',
|
||||||
|
device=None,
|
||||||
|
dtype=None
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.in_channels = in_channels
|
||||||
|
self.out_channels = out_channels
|
||||||
|
self.kernel_size = kernel_size
|
||||||
|
self.stride = stride
|
||||||
|
self.padding = padding
|
||||||
|
self.dilation = dilation
|
||||||
|
self.transposed = False
|
||||||
|
self.output_padding = 0
|
||||||
|
self.groups = groups
|
||||||
|
self.padding_mode = padding_mode
|
||||||
|
|
||||||
|
self.weight = None
|
||||||
|
self.bias = None
|
||||||
|
self.up = None
|
||||||
|
self.down = None
|
||||||
|
|
||||||
|
|
||||||
|
def forward(self, input):
|
||||||
|
if self.up is not None:
|
||||||
|
return torch.nn.functional.conv2d(input, self.weight.to(input.device) + (torch.mm(self.up.flatten(start_dim=1), self.down.flatten(start_dim=1))).reshape(self.weight.shape).type(input.dtype), self.bias, self.stride, self.padding, self.dilation, self.groups)
|
||||||
|
else:
|
||||||
|
return torch.nn.functional.conv2d(input, self.weight.to(input.device), self.bias, self.stride, self.padding, self.dilation, self.groups)
|
||||||
|
|
||||||
|
def conv_nd(self, dims, *args, **kwargs):
|
||||||
|
if dims == 2:
|
||||||
|
return self.Conv2d(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"unsupported dimensions: {dims}")
|
||||||
|
|
||||||
|
|
||||||
|
class ControlLora(ControlNet):
|
||||||
|
def __init__(self, control_weights, global_average_pooling=False, device=None):
|
||||||
|
ControlBase.__init__(self, device)
|
||||||
|
self.control_weights = control_weights
|
||||||
|
self.global_average_pooling = global_average_pooling
|
||||||
|
|
||||||
|
def pre_run(self, model, percent_to_timestep_function):
|
||||||
|
super().pre_run(model, percent_to_timestep_function)
|
||||||
|
controlnet_config = model.model_config.unet_config.copy()
|
||||||
|
controlnet_config.pop("out_channels")
|
||||||
|
controlnet_config["hint_channels"] = self.control_weights["input_hint_block.0.weight"].shape[1]
|
||||||
|
controlnet_config["operations"] = ControlLoraOps()
|
||||||
|
self.control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
|
||||||
|
dtype = model.get_dtype()
|
||||||
|
self.control_model.to(dtype)
|
||||||
|
self.control_model.to(comfy.model_management.get_torch_device())
|
||||||
|
diffusion_model = model.diffusion_model
|
||||||
|
sd = diffusion_model.state_dict()
|
||||||
|
cm = self.control_model.state_dict()
|
||||||
|
|
||||||
|
for k in sd:
|
||||||
|
weight = comfy.model_management.resolve_lowvram_weight(sd[k], diffusion_model, k)
|
||||||
|
try:
|
||||||
|
comfy.utils.set_attr(self.control_model, k, weight)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
for k in self.control_weights:
|
||||||
|
if k not in {"lora_controlnet"}:
|
||||||
|
comfy.utils.set_attr(self.control_model, k, self.control_weights[k].to(dtype).to(comfy.model_management.get_torch_device()))
|
||||||
|
|
||||||
|
def copy(self):
|
||||||
|
c = ControlLora(self.control_weights, global_average_pooling=self.global_average_pooling)
|
||||||
|
self.copy_to(c)
|
||||||
|
return c
|
||||||
|
|
||||||
|
def cleanup(self):
|
||||||
|
del self.control_model
|
||||||
|
self.control_model = None
|
||||||
|
super().cleanup()
|
||||||
|
|
||||||
|
def get_models(self):
|
||||||
|
out = ControlBase.get_models(self)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def inference_memory_requirements(self, dtype):
|
||||||
|
return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
|
||||||
|
|
||||||
|
def load_controlnet(ckpt_path, model=None):
|
||||||
|
controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
|
||||||
|
if "lora_controlnet" in controlnet_data:
|
||||||
|
return ControlLora(controlnet_data)
|
||||||
|
|
||||||
|
controlnet_config = None
|
||||||
|
if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
|
||||||
|
use_fp16 = comfy.model_management.should_use_fp16()
|
||||||
|
controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data, use_fp16)
|
||||||
|
diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
|
||||||
|
diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
|
||||||
|
diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
|
||||||
|
|
||||||
|
count = 0
|
||||||
|
loop = True
|
||||||
|
while loop:
|
||||||
|
suffix = [".weight", ".bias"]
|
||||||
|
for s in suffix:
|
||||||
|
k_in = "controlnet_down_blocks.{}{}".format(count, s)
|
||||||
|
k_out = "zero_convs.{}.0{}".format(count, s)
|
||||||
|
if k_in not in controlnet_data:
|
||||||
|
loop = False
|
||||||
|
break
|
||||||
|
diffusers_keys[k_in] = k_out
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
count = 0
|
||||||
|
loop = True
|
||||||
|
while loop:
|
||||||
|
suffix = [".weight", ".bias"]
|
||||||
|
for s in suffix:
|
||||||
|
if count == 0:
|
||||||
|
k_in = "controlnet_cond_embedding.conv_in{}".format(s)
|
||||||
|
else:
|
||||||
|
k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
|
||||||
|
k_out = "input_hint_block.{}{}".format(count * 2, s)
|
||||||
|
if k_in not in controlnet_data:
|
||||||
|
k_in = "controlnet_cond_embedding.conv_out{}".format(s)
|
||||||
|
loop = False
|
||||||
|
diffusers_keys[k_in] = k_out
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
new_sd = {}
|
||||||
|
for k in diffusers_keys:
|
||||||
|
if k in controlnet_data:
|
||||||
|
new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
|
||||||
|
|
||||||
|
leftover_keys = controlnet_data.keys()
|
||||||
|
if len(leftover_keys) > 0:
|
||||||
|
print("leftover keys:", leftover_keys)
|
||||||
|
controlnet_data = new_sd
|
||||||
|
|
||||||
|
pth_key = 'control_model.zero_convs.0.0.weight'
|
||||||
|
pth = False
|
||||||
|
key = 'zero_convs.0.0.weight'
|
||||||
|
if pth_key in controlnet_data:
|
||||||
|
pth = True
|
||||||
|
key = pth_key
|
||||||
|
prefix = "control_model."
|
||||||
|
elif key in controlnet_data:
|
||||||
|
prefix = ""
|
||||||
|
else:
|
||||||
|
net = load_t2i_adapter(controlnet_data)
|
||||||
|
if net is None:
|
||||||
|
print("error checkpoint does not contain controlnet or t2i adapter data", ckpt_path)
|
||||||
|
return net
|
||||||
|
|
||||||
|
if controlnet_config is None:
|
||||||
|
use_fp16 = comfy.model_management.should_use_fp16()
|
||||||
|
controlnet_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, use_fp16).unet_config
|
||||||
|
controlnet_config.pop("out_channels")
|
||||||
|
controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
|
||||||
|
control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
|
||||||
|
|
||||||
|
if pth:
|
||||||
|
if 'difference' in controlnet_data:
|
||||||
|
if model is not None:
|
||||||
|
comfy.model_management.load_models_gpu([model])
|
||||||
|
model_sd = model.model_state_dict()
|
||||||
|
for x in controlnet_data:
|
||||||
|
c_m = "control_model."
|
||||||
|
if x.startswith(c_m):
|
||||||
|
sd_key = "diffusion_model.{}".format(x[len(c_m):])
|
||||||
|
if sd_key in model_sd:
|
||||||
|
cd = controlnet_data[x]
|
||||||
|
cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
|
||||||
|
else:
|
||||||
|
print("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
|
||||||
|
|
||||||
|
class WeightsLoader(torch.nn.Module):
|
||||||
|
pass
|
||||||
|
w = WeightsLoader()
|
||||||
|
w.control_model = control_model
|
||||||
|
missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
|
||||||
|
else:
|
||||||
|
missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
|
||||||
|
print(missing, unexpected)
|
||||||
|
|
||||||
|
if use_fp16:
|
||||||
|
control_model = control_model.half()
|
||||||
|
|
||||||
|
global_average_pooling = False
|
||||||
|
filename = os.path.splitext(ckpt_path)[0]
|
||||||
|
if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
|
||||||
|
global_average_pooling = True
|
||||||
|
|
||||||
|
control = ControlNet(control_model, global_average_pooling=global_average_pooling)
|
||||||
|
return control
|
||||||
|
|
||||||
|
class T2IAdapter(ControlBase):
|
||||||
|
def __init__(self, t2i_model, channels_in, device=None):
|
||||||
|
super().__init__(device)
|
||||||
|
self.t2i_model = t2i_model
|
||||||
|
self.channels_in = channels_in
|
||||||
|
self.control_input = None
|
||||||
|
|
||||||
|
def scale_image_to(self, width, height):
|
||||||
|
unshuffle_amount = self.t2i_model.unshuffle_amount
|
||||||
|
width = math.ceil(width / unshuffle_amount) * unshuffle_amount
|
||||||
|
height = math.ceil(height / unshuffle_amount) * unshuffle_amount
|
||||||
|
return width, height
|
||||||
|
|
||||||
|
def get_control(self, x_noisy, t, cond, batched_number):
|
||||||
|
control_prev = None
|
||||||
|
if self.previous_controlnet is not None:
|
||||||
|
control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
|
||||||
|
|
||||||
|
if self.timestep_range is not None:
|
||||||
|
if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
|
||||||
|
if control_prev is not None:
|
||||||
|
return control_prev
|
||||||
|
else:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
if self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
|
||||||
|
if self.cond_hint is not None:
|
||||||
|
del self.cond_hint
|
||||||
|
self.control_input = None
|
||||||
|
self.cond_hint = None
|
||||||
|
width, height = self.scale_image_to(x_noisy.shape[3] * 8, x_noisy.shape[2] * 8)
|
||||||
|
self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, width, height, 'nearest-exact', "center").float().to(self.device)
|
||||||
|
if self.channels_in == 1 and self.cond_hint.shape[1] > 1:
|
||||||
|
self.cond_hint = torch.mean(self.cond_hint, 1, keepdim=True)
|
||||||
|
if x_noisy.shape[0] != self.cond_hint.shape[0]:
|
||||||
|
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
|
||||||
|
if self.control_input is None:
|
||||||
|
self.t2i_model.to(x_noisy.dtype)
|
||||||
|
self.t2i_model.to(self.device)
|
||||||
|
self.control_input = self.t2i_model(self.cond_hint.to(x_noisy.dtype))
|
||||||
|
self.t2i_model.cpu()
|
||||||
|
|
||||||
|
control_input = list(map(lambda a: None if a is None else a.clone(), self.control_input))
|
||||||
|
mid = None
|
||||||
|
if self.t2i_model.xl == True:
|
||||||
|
mid = control_input[-1:]
|
||||||
|
control_input = control_input[:-1]
|
||||||
|
return self.control_merge(control_input, mid, control_prev, x_noisy.dtype)
|
||||||
|
|
||||||
|
def copy(self):
|
||||||
|
c = T2IAdapter(self.t2i_model, self.channels_in)
|
||||||
|
self.copy_to(c)
|
||||||
|
return c
|
||||||
|
|
||||||
|
def load_t2i_adapter(t2i_data):
|
||||||
|
if 'adapter' in t2i_data:
|
||||||
|
t2i_data = t2i_data['adapter']
|
||||||
|
if 'adapter.body.0.resnets.0.block1.weight' in t2i_data: #diffusers format
|
||||||
|
prefix_replace = {}
|
||||||
|
for i in range(4):
|
||||||
|
for j in range(2):
|
||||||
|
prefix_replace["adapter.body.{}.resnets.{}.".format(i, j)] = "body.{}.".format(i * 2 + j)
|
||||||
|
prefix_replace["adapter.body.{}.".format(i, j)] = "body.{}.".format(i * 2)
|
||||||
|
prefix_replace["adapter."] = ""
|
||||||
|
t2i_data = comfy.utils.state_dict_prefix_replace(t2i_data, prefix_replace)
|
||||||
|
keys = t2i_data.keys()
|
||||||
|
|
||||||
|
if "body.0.in_conv.weight" in keys:
|
||||||
|
cin = t2i_data['body.0.in_conv.weight'].shape[1]
|
||||||
|
model_ad = comfy.t2i_adapter.adapter.Adapter_light(cin=cin, channels=[320, 640, 1280, 1280], nums_rb=4)
|
||||||
|
elif 'conv_in.weight' in keys:
|
||||||
|
cin = t2i_data['conv_in.weight'].shape[1]
|
||||||
|
channel = t2i_data['conv_in.weight'].shape[0]
|
||||||
|
ksize = t2i_data['body.0.block2.weight'].shape[2]
|
||||||
|
use_conv = False
|
||||||
|
down_opts = list(filter(lambda a: a.endswith("down_opt.op.weight"), keys))
|
||||||
|
if len(down_opts) > 0:
|
||||||
|
use_conv = True
|
||||||
|
xl = False
|
||||||
|
if cin == 256 or cin == 768:
|
||||||
|
xl = True
|
||||||
|
model_ad = comfy.t2i_adapter.adapter.Adapter(cin=cin, channels=[channel, channel*2, channel*4, channel*4][:4], nums_rb=2, ksize=ksize, sk=True, use_conv=use_conv, xl=xl)
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
missing, unexpected = model_ad.load_state_dict(t2i_data)
|
||||||
|
if len(missing) > 0:
|
||||||
|
print("t2i missing", missing)
|
||||||
|
|
||||||
|
if len(unexpected) > 0:
|
||||||
|
print("t2i unexpected", unexpected)
|
||||||
|
|
||||||
|
return T2IAdapter(model_ad, model_ad.input_channels)
|
||||||
@ -148,6 +148,10 @@ vae_conversion_map_attn = [
|
|||||||
("q.", "query."),
|
("q.", "query."),
|
||||||
("k.", "key."),
|
("k.", "key."),
|
||||||
("v.", "value."),
|
("v.", "value."),
|
||||||
|
("q.", "to_q."),
|
||||||
|
("k.", "to_k."),
|
||||||
|
("v.", "to_v."),
|
||||||
|
("proj_out.", "to_out.0."),
|
||||||
("proj_out.", "proj_attn."),
|
("proj_out.", "proj_attn."),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@ -1,86 +1,36 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import yaml
|
|
||||||
|
|
||||||
import folder_paths
|
import comfy.sd
|
||||||
from comfy.sd import ModelPatcher, load_model_weights, CLIP, VAE, load_checkpoint
|
|
||||||
import os.path as osp
|
|
||||||
import re
|
|
||||||
import torch
|
|
||||||
from safetensors.torch import load_file, save_file
|
|
||||||
import diffusers_convert
|
|
||||||
|
|
||||||
def load_diffusers(model_path, fp16=True, output_vae=True, output_clip=True, embedding_directory=None):
|
def first_file(path, filenames):
|
||||||
diffusers_unet_conf = json.load(open(osp.join(model_path, "unet/config.json")))
|
for f in filenames:
|
||||||
diffusers_scheduler_conf = json.load(open(osp.join(model_path, "scheduler/scheduler_config.json")))
|
p = os.path.join(path, f)
|
||||||
|
if os.path.exists(p):
|
||||||
|
return p
|
||||||
|
return None
|
||||||
|
|
||||||
# magic
|
def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_directory=None):
|
||||||
v2 = diffusers_unet_conf["sample_size"] == 96
|
diffusion_model_names = ["diffusion_pytorch_model.fp16.safetensors", "diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.fp16.bin", "diffusion_pytorch_model.bin"]
|
||||||
if 'prediction_type' in diffusers_scheduler_conf:
|
unet_path = first_file(os.path.join(model_path, "unet"), diffusion_model_names)
|
||||||
v_pred = diffusers_scheduler_conf['prediction_type'] == 'v_prediction'
|
vae_path = first_file(os.path.join(model_path, "vae"), diffusion_model_names)
|
||||||
|
|
||||||
if v2:
|
text_encoder_model_names = ["model.fp16.safetensors", "model.safetensors", "pytorch_model.fp16.bin", "pytorch_model.bin"]
|
||||||
if v_pred:
|
text_encoder1_path = first_file(os.path.join(model_path, "text_encoder"), text_encoder_model_names)
|
||||||
config_path = folder_paths.get_full_path("configs", 'v2-inference-v.yaml')
|
text_encoder2_path = first_file(os.path.join(model_path, "text_encoder_2"), text_encoder_model_names)
|
||||||
else:
|
|
||||||
config_path = folder_paths.get_full_path("configs", 'v2-inference.yaml')
|
|
||||||
else:
|
|
||||||
config_path = folder_paths.get_full_path("configs", 'v1-inference.yaml')
|
|
||||||
|
|
||||||
with open(config_path, 'r') as stream:
|
text_encoder_paths = [text_encoder1_path]
|
||||||
config = yaml.safe_load(stream)
|
if text_encoder2_path is not None:
|
||||||
|
text_encoder_paths.append(text_encoder2_path)
|
||||||
|
|
||||||
model_config_params = config['model']['params']
|
unet = comfy.sd.load_unet(unet_path)
|
||||||
clip_config = model_config_params['cond_stage_config']
|
|
||||||
scale_factor = model_config_params['scale_factor']
|
|
||||||
vae_config = model_config_params['first_stage_config']
|
|
||||||
vae_config['scale_factor'] = scale_factor
|
|
||||||
model_config_params["unet_config"]["params"]["use_fp16"] = fp16
|
|
||||||
|
|
||||||
unet_path = osp.join(model_path, "unet", "diffusion_pytorch_model.safetensors")
|
clip = None
|
||||||
vae_path = osp.join(model_path, "vae", "diffusion_pytorch_model.safetensors")
|
if output_clip:
|
||||||
text_enc_path = osp.join(model_path, "text_encoder", "model.safetensors")
|
clip = comfy.sd.load_clip(text_encoder_paths, embedding_directory=embedding_directory)
|
||||||
|
|
||||||
# Load models from safetensors if it exists, if it doesn't pytorch
|
vae = None
|
||||||
if osp.exists(unet_path):
|
if output_vae:
|
||||||
unet_state_dict = load_file(unet_path, device="cpu")
|
vae = comfy.sd.VAE(ckpt_path=vae_path)
|
||||||
else:
|
|
||||||
unet_path = osp.join(model_path, "unet", "diffusion_pytorch_model.bin")
|
|
||||||
unet_state_dict = torch.load(unet_path, map_location="cpu")
|
|
||||||
|
|
||||||
if osp.exists(vae_path):
|
return (unet, clip, vae)
|
||||||
vae_state_dict = load_file(vae_path, device="cpu")
|
|
||||||
else:
|
|
||||||
vae_path = osp.join(model_path, "vae", "diffusion_pytorch_model.bin")
|
|
||||||
vae_state_dict = torch.load(vae_path, map_location="cpu")
|
|
||||||
|
|
||||||
if osp.exists(text_enc_path):
|
|
||||||
text_enc_dict = load_file(text_enc_path, device="cpu")
|
|
||||||
else:
|
|
||||||
text_enc_path = osp.join(model_path, "text_encoder", "pytorch_model.bin")
|
|
||||||
text_enc_dict = torch.load(text_enc_path, map_location="cpu")
|
|
||||||
|
|
||||||
# Convert the UNet model
|
|
||||||
unet_state_dict = diffusers_convert.convert_unet_state_dict(unet_state_dict)
|
|
||||||
unet_state_dict = {"model.diffusion_model." + k: v for k, v in unet_state_dict.items()}
|
|
||||||
|
|
||||||
# Convert the VAE model
|
|
||||||
vae_state_dict = diffusers_convert.convert_vae_state_dict(vae_state_dict)
|
|
||||||
vae_state_dict = {"first_stage_model." + k: v for k, v in vae_state_dict.items()}
|
|
||||||
|
|
||||||
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
|
|
||||||
is_v20_model = "text_model.encoder.layers.22.layer_norm2.bias" in text_enc_dict
|
|
||||||
|
|
||||||
if is_v20_model:
|
|
||||||
# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
|
|
||||||
text_enc_dict = {"transformer." + k: v for k, v in text_enc_dict.items()}
|
|
||||||
text_enc_dict = diffusers_convert.convert_text_enc_state_dict_v20(text_enc_dict)
|
|
||||||
text_enc_dict = {"cond_stage_model.model." + k: v for k, v in text_enc_dict.items()}
|
|
||||||
else:
|
|
||||||
text_enc_dict = diffusers_convert.convert_text_enc_state_dict(text_enc_dict)
|
|
||||||
text_enc_dict = {"cond_stage_model.transformer." + k: v for k, v in text_enc_dict.items()}
|
|
||||||
|
|
||||||
# Put together new checkpoint
|
|
||||||
sd = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
|
|
||||||
|
|
||||||
return load_checkpoint(embedding_directory=embedding_directory, state_dict=sd, config=config)
|
|
||||||
|
|||||||
@ -180,7 +180,6 @@ class NoiseScheduleVP:
|
|||||||
|
|
||||||
def model_wrapper(
|
def model_wrapper(
|
||||||
model,
|
model,
|
||||||
sampling_function,
|
|
||||||
noise_schedule,
|
noise_schedule,
|
||||||
model_type="noise",
|
model_type="noise",
|
||||||
model_kwargs={},
|
model_kwargs={},
|
||||||
@ -295,7 +294,7 @@ def model_wrapper(
|
|||||||
if t_continuous.reshape((-1,)).shape[0] == 1:
|
if t_continuous.reshape((-1,)).shape[0] == 1:
|
||||||
t_continuous = t_continuous.expand((x.shape[0]))
|
t_continuous = t_continuous.expand((x.shape[0]))
|
||||||
t_input = get_model_input_time(t_continuous)
|
t_input = get_model_input_time(t_continuous)
|
||||||
output = sampling_function(model, x, t_input, **model_kwargs)
|
output = model(x, t_input, **model_kwargs)
|
||||||
if model_type == "noise":
|
if model_type == "noise":
|
||||||
return output
|
return output
|
||||||
elif model_type == "x_start":
|
elif model_type == "x_start":
|
||||||
@ -843,10 +842,12 @@ def sample_unipc(model, noise, image, sigmas, sampling_function, max_denoise, ex
|
|||||||
else:
|
else:
|
||||||
timesteps = sigmas.clone()
|
timesteps = sigmas.clone()
|
||||||
|
|
||||||
for s in range(timesteps.shape[0]):
|
alphas_cumprod = model.inner_model.alphas_cumprod
|
||||||
timesteps[s] = (model.sigma_to_t(timesteps[s]) / 1000) + (1 / len(model.sigmas))
|
|
||||||
|
|
||||||
ns = NoiseScheduleVP('discrete', alphas_cumprod=model.inner_model.alphas_cumprod)
|
for s in range(timesteps.shape[0]):
|
||||||
|
timesteps[s] = (model.sigma_to_discrete_timestep(timesteps[s]) / 1000) + (1 / len(alphas_cumprod))
|
||||||
|
|
||||||
|
ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod)
|
||||||
|
|
||||||
if image is not None:
|
if image is not None:
|
||||||
img = image * ns.marginal_alpha(timesteps[0])
|
img = image * ns.marginal_alpha(timesteps[0])
|
||||||
@ -859,18 +860,15 @@ def sample_unipc(model, noise, image, sigmas, sampling_function, max_denoise, ex
|
|||||||
img = noise
|
img = noise
|
||||||
|
|
||||||
if to_zero:
|
if to_zero:
|
||||||
timesteps[-1] = (1 / len(model.sigmas))
|
timesteps[-1] = (1 / len(alphas_cumprod))
|
||||||
|
|
||||||
device = noise.device
|
device = noise.device
|
||||||
|
|
||||||
if model.parameterization == "v":
|
|
||||||
model_type = "v"
|
model_type = "noise"
|
||||||
else:
|
|
||||||
model_type = "noise"
|
|
||||||
|
|
||||||
model_fn = model_wrapper(
|
model_fn = model_wrapper(
|
||||||
model.inner_model.inner_model.apply_model,
|
model.predict_eps_discrete_timestep,
|
||||||
sampling_function,
|
|
||||||
ns,
|
ns,
|
||||||
model_type=model_type,
|
model_type=model_type,
|
||||||
guidance_type="uncond",
|
guidance_type="uncond",
|
||||||
|
|||||||
@ -215,10 +215,12 @@ class PositionNet(nn.Module):
|
|||||||
|
|
||||||
def forward(self, boxes, masks, positive_embeddings):
|
def forward(self, boxes, masks, positive_embeddings):
|
||||||
B, N, _ = boxes.shape
|
B, N, _ = boxes.shape
|
||||||
masks = masks.unsqueeze(-1)
|
dtype = self.linears[0].weight.dtype
|
||||||
|
masks = masks.unsqueeze(-1).to(dtype)
|
||||||
|
positive_embeddings = positive_embeddings.to(dtype)
|
||||||
|
|
||||||
# embedding position (it may includes padding as placeholder)
|
# embedding position (it may includes padding as placeholder)
|
||||||
xyxy_embedding = self.fourier_embedder(boxes) # B*N*4 --> B*N*C
|
xyxy_embedding = self.fourier_embedder(boxes.to(dtype)) # B*N*4 --> B*N*C
|
||||||
|
|
||||||
# learnable null embedding
|
# learnable null embedding
|
||||||
positive_null = self.null_positive_feature.view(1, 1, -1)
|
positive_null = self.null_positive_feature.view(1, 1, -1)
|
||||||
@ -242,29 +244,15 @@ class Gligen(nn.Module):
|
|||||||
self.position_net = position_net
|
self.position_net = position_net
|
||||||
self.key_dim = key_dim
|
self.key_dim = key_dim
|
||||||
self.max_objs = 30
|
self.max_objs = 30
|
||||||
self.lowvram = False
|
self.current_device = torch.device("cpu")
|
||||||
|
|
||||||
def _set_position(self, boxes, masks, positive_embeddings):
|
def _set_position(self, boxes, masks, positive_embeddings):
|
||||||
if self.lowvram == True:
|
|
||||||
self.position_net.to(boxes.device)
|
|
||||||
|
|
||||||
objs = self.position_net(boxes, masks, positive_embeddings)
|
objs = self.position_net(boxes, masks, positive_embeddings)
|
||||||
|
def func(x, extra_options):
|
||||||
if self.lowvram == True:
|
key = extra_options["transformer_index"]
|
||||||
self.position_net.cpu()
|
module = self.module_list[key]
|
||||||
def func_lowvram(key, x):
|
return module(x, objs)
|
||||||
module = self.module_list[key]
|
return func
|
||||||
module.to(x.device)
|
|
||||||
r = module(x, objs)
|
|
||||||
module.cpu()
|
|
||||||
return r
|
|
||||||
return func_lowvram
|
|
||||||
else:
|
|
||||||
def func(x, extra_options):
|
|
||||||
key = extra_options["transformer_index"]
|
|
||||||
module = self.module_list[key]
|
|
||||||
return module(x, objs)
|
|
||||||
return func
|
|
||||||
|
|
||||||
def set_position(self, latent_image_shape, position_params, device):
|
def set_position(self, latent_image_shape, position_params, device):
|
||||||
batch, c, h, w = latent_image_shape
|
batch, c, h, w = latent_image_shape
|
||||||
@ -309,14 +297,6 @@ class Gligen(nn.Module):
|
|||||||
masks.to(device),
|
masks.to(device),
|
||||||
conds.to(device))
|
conds.to(device))
|
||||||
|
|
||||||
def set_lowvram(self, value=True):
|
|
||||||
self.lowvram = value
|
|
||||||
|
|
||||||
def cleanup(self):
|
|
||||||
self.lowvram = False
|
|
||||||
|
|
||||||
def get_models(self):
|
|
||||||
return [self]
|
|
||||||
|
|
||||||
def load_gligen(sd):
|
def load_gligen(sd):
|
||||||
sd_k = sd.keys()
|
sd_k = sd.keys()
|
||||||
|
|||||||
@ -63,12 +63,17 @@ class DiscreteSchedule(nn.Module):
|
|||||||
t = torch.linspace(t_max, 0, n, device=self.sigmas.device)
|
t = torch.linspace(t_max, 0, n, device=self.sigmas.device)
|
||||||
return sampling.append_zero(self.t_to_sigma(t))
|
return sampling.append_zero(self.t_to_sigma(t))
|
||||||
|
|
||||||
def sigma_to_t(self, sigma, quantize=None):
|
def sigma_to_discrete_timestep(self, sigma):
|
||||||
quantize = self.quantize if quantize is None else quantize
|
|
||||||
log_sigma = sigma.log()
|
log_sigma = sigma.log()
|
||||||
dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
|
dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
|
||||||
|
return dists.abs().argmin(dim=0).view(sigma.shape)
|
||||||
|
|
||||||
|
def sigma_to_t(self, sigma, quantize=None):
|
||||||
|
quantize = self.quantize if quantize is None else quantize
|
||||||
if quantize:
|
if quantize:
|
||||||
return dists.abs().argmin(dim=0).view(sigma.shape)
|
return self.sigma_to_discrete_timestep(sigma)
|
||||||
|
log_sigma = sigma.log()
|
||||||
|
dists = log_sigma.to(self.log_sigmas.device) - self.log_sigmas[:, None]
|
||||||
low_idx = dists.ge(0).cumsum(dim=0).argmax(dim=0).clamp(max=self.log_sigmas.shape[0] - 2)
|
low_idx = dists.ge(0).cumsum(dim=0).argmax(dim=0).clamp(max=self.log_sigmas.shape[0] - 2)
|
||||||
high_idx = low_idx + 1
|
high_idx = low_idx + 1
|
||||||
low, high = self.log_sigmas[low_idx], self.log_sigmas[high_idx]
|
low, high = self.log_sigmas[low_idx], self.log_sigmas[high_idx]
|
||||||
@ -85,6 +90,12 @@ class DiscreteSchedule(nn.Module):
|
|||||||
log_sigma = (1 - w) * self.log_sigmas[low_idx] + w * self.log_sigmas[high_idx]
|
log_sigma = (1 - w) * self.log_sigmas[low_idx] + w * self.log_sigmas[high_idx]
|
||||||
return log_sigma.exp()
|
return log_sigma.exp()
|
||||||
|
|
||||||
|
def predict_eps_discrete_timestep(self, input, t, **kwargs):
|
||||||
|
if t.dtype != torch.int64 and t.dtype != torch.int32:
|
||||||
|
t = t.round()
|
||||||
|
sigma = self.t_to_sigma(t)
|
||||||
|
input = input * ((utils.append_dims(sigma, input.ndim) ** 2 + 1.0) ** 0.5)
|
||||||
|
return (input - self(input, sigma, **kwargs)) / utils.append_dims(sigma, input.ndim)
|
||||||
|
|
||||||
class DiscreteEpsDDPMDenoiser(DiscreteSchedule):
|
class DiscreteEpsDDPMDenoiser(DiscreteSchedule):
|
||||||
"""A wrapper for discrete schedule DDPM models that output eps (the predicted
|
"""A wrapper for discrete schedule DDPM models that output eps (the predicted
|
||||||
|
|||||||
@ -3,7 +3,6 @@ import math
|
|||||||
from scipy import integrate
|
from scipy import integrate
|
||||||
import torch
|
import torch
|
||||||
from torch import nn
|
from torch import nn
|
||||||
from torchdiffeq import odeint
|
|
||||||
import torchsde
|
import torchsde
|
||||||
from tqdm.auto import trange, tqdm
|
from tqdm.auto import trange, tqdm
|
||||||
|
|
||||||
@ -66,6 +65,9 @@ class BatchedBrownianTree:
|
|||||||
"""A wrapper around torchsde.BrownianTree that enables batches of entropy."""
|
"""A wrapper around torchsde.BrownianTree that enables batches of entropy."""
|
||||||
|
|
||||||
def __init__(self, x, t0, t1, seed=None, **kwargs):
|
def __init__(self, x, t0, t1, seed=None, **kwargs):
|
||||||
|
self.cpu_tree = True
|
||||||
|
if "cpu" in kwargs:
|
||||||
|
self.cpu_tree = kwargs.pop("cpu")
|
||||||
t0, t1, self.sign = self.sort(t0, t1)
|
t0, t1, self.sign = self.sort(t0, t1)
|
||||||
w0 = kwargs.get('w0', torch.zeros_like(x))
|
w0 = kwargs.get('w0', torch.zeros_like(x))
|
||||||
if seed is None:
|
if seed is None:
|
||||||
@ -77,7 +79,10 @@ class BatchedBrownianTree:
|
|||||||
except TypeError:
|
except TypeError:
|
||||||
seed = [seed]
|
seed = [seed]
|
||||||
self.batched = False
|
self.batched = False
|
||||||
self.trees = [torchsde.BrownianTree(t0.cpu(), w0.cpu(), t1.cpu(), entropy=s, **kwargs) for s in seed]
|
if self.cpu_tree:
|
||||||
|
self.trees = [torchsde.BrownianTree(t0.cpu(), w0.cpu(), t1.cpu(), entropy=s, **kwargs) for s in seed]
|
||||||
|
else:
|
||||||
|
self.trees = [torchsde.BrownianTree(t0, w0, t1, entropy=s, **kwargs) for s in seed]
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def sort(a, b):
|
def sort(a, b):
|
||||||
@ -85,7 +90,11 @@ class BatchedBrownianTree:
|
|||||||
|
|
||||||
def __call__(self, t0, t1):
|
def __call__(self, t0, t1):
|
||||||
t0, t1, sign = self.sort(t0, t1)
|
t0, t1, sign = self.sort(t0, t1)
|
||||||
w = torch.stack([tree(t0.cpu().float(), t1.cpu().float()).to(t0.dtype).to(t0.device) for tree in self.trees]) * (self.sign * sign)
|
if self.cpu_tree:
|
||||||
|
w = torch.stack([tree(t0.cpu().float(), t1.cpu().float()).to(t0.dtype).to(t0.device) for tree in self.trees]) * (self.sign * sign)
|
||||||
|
else:
|
||||||
|
w = torch.stack([tree(t0, t1) for tree in self.trees]) * (self.sign * sign)
|
||||||
|
|
||||||
return w if self.batched else w[0]
|
return w if self.batched else w[0]
|
||||||
|
|
||||||
|
|
||||||
@ -104,10 +113,10 @@ class BrownianTreeNoiseSampler:
|
|||||||
internal timestep.
|
internal timestep.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x):
|
def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x, cpu=False):
|
||||||
self.transform = transform
|
self.transform = transform
|
||||||
t0, t1 = self.transform(torch.as_tensor(sigma_min)), self.transform(torch.as_tensor(sigma_max))
|
t0, t1 = self.transform(torch.as_tensor(sigma_min)), self.transform(torch.as_tensor(sigma_max))
|
||||||
self.tree = BatchedBrownianTree(x, t0, t1, seed)
|
self.tree = BatchedBrownianTree(x, t0, t1, seed, cpu=cpu)
|
||||||
|
|
||||||
def __call__(self, sigma, sigma_next):
|
def __call__(self, sigma, sigma_next):
|
||||||
t0, t1 = self.transform(torch.as_tensor(sigma)), self.transform(torch.as_tensor(sigma_next))
|
t0, t1 = self.transform(torch.as_tensor(sigma)), self.transform(torch.as_tensor(sigma_next))
|
||||||
@ -121,9 +130,9 @@ def sample_euler(model, x, sigmas, extra_args=None, callback=None, disable=None,
|
|||||||
s_in = x.new_ones([x.shape[0]])
|
s_in = x.new_ones([x.shape[0]])
|
||||||
for i in trange(len(sigmas) - 1, disable=disable):
|
for i in trange(len(sigmas) - 1, disable=disable):
|
||||||
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
||||||
eps = torch.randn_like(x) * s_noise
|
|
||||||
sigma_hat = sigmas[i] * (gamma + 1)
|
sigma_hat = sigmas[i] * (gamma + 1)
|
||||||
if gamma > 0:
|
if gamma > 0:
|
||||||
|
eps = torch.randn_like(x) * s_noise
|
||||||
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
||||||
denoised = model(x, sigma_hat * s_in, **extra_args)
|
denoised = model(x, sigma_hat * s_in, **extra_args)
|
||||||
d = to_d(x, sigma_hat, denoised)
|
d = to_d(x, sigma_hat, denoised)
|
||||||
@ -162,9 +171,9 @@ def sample_heun(model, x, sigmas, extra_args=None, callback=None, disable=None,
|
|||||||
s_in = x.new_ones([x.shape[0]])
|
s_in = x.new_ones([x.shape[0]])
|
||||||
for i in trange(len(sigmas) - 1, disable=disable):
|
for i in trange(len(sigmas) - 1, disable=disable):
|
||||||
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
||||||
eps = torch.randn_like(x) * s_noise
|
|
||||||
sigma_hat = sigmas[i] * (gamma + 1)
|
sigma_hat = sigmas[i] * (gamma + 1)
|
||||||
if gamma > 0:
|
if gamma > 0:
|
||||||
|
eps = torch.randn_like(x) * s_noise
|
||||||
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
||||||
denoised = model(x, sigma_hat * s_in, **extra_args)
|
denoised = model(x, sigma_hat * s_in, **extra_args)
|
||||||
d = to_d(x, sigma_hat, denoised)
|
d = to_d(x, sigma_hat, denoised)
|
||||||
@ -191,9 +200,9 @@ def sample_dpm_2(model, x, sigmas, extra_args=None, callback=None, disable=None,
|
|||||||
s_in = x.new_ones([x.shape[0]])
|
s_in = x.new_ones([x.shape[0]])
|
||||||
for i in trange(len(sigmas) - 1, disable=disable):
|
for i in trange(len(sigmas) - 1, disable=disable):
|
||||||
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.
|
||||||
eps = torch.randn_like(x) * s_noise
|
|
||||||
sigma_hat = sigmas[i] * (gamma + 1)
|
sigma_hat = sigmas[i] * (gamma + 1)
|
||||||
if gamma > 0:
|
if gamma > 0:
|
||||||
|
eps = torch.randn_like(x) * s_noise
|
||||||
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5
|
||||||
denoised = model(x, sigma_hat * s_in, **extra_args)
|
denoised = model(x, sigma_hat * s_in, **extra_args)
|
||||||
d = to_d(x, sigma_hat, denoised)
|
d = to_d(x, sigma_hat, denoised)
|
||||||
@ -277,30 +286,6 @@ def sample_lms(model, x, sigmas, extra_args=None, callback=None, disable=None, o
|
|||||||
return x
|
return x
|
||||||
|
|
||||||
|
|
||||||
@torch.no_grad()
|
|
||||||
def log_likelihood(model, x, sigma_min, sigma_max, extra_args=None, atol=1e-4, rtol=1e-4):
|
|
||||||
extra_args = {} if extra_args is None else extra_args
|
|
||||||
s_in = x.new_ones([x.shape[0]])
|
|
||||||
v = torch.randint_like(x, 2) * 2 - 1
|
|
||||||
fevals = 0
|
|
||||||
def ode_fn(sigma, x):
|
|
||||||
nonlocal fevals
|
|
||||||
with torch.enable_grad():
|
|
||||||
x = x[0].detach().requires_grad_()
|
|
||||||
denoised = model(x, sigma * s_in, **extra_args)
|
|
||||||
d = to_d(x, sigma, denoised)
|
|
||||||
fevals += 1
|
|
||||||
grad = torch.autograd.grad((d * v).sum(), x)[0]
|
|
||||||
d_ll = (v * grad).flatten(1).sum(1)
|
|
||||||
return d.detach(), d_ll
|
|
||||||
x_min = x, x.new_zeros([x.shape[0]])
|
|
||||||
t = x.new_tensor([sigma_min, sigma_max])
|
|
||||||
sol = odeint(ode_fn, x_min, t, atol=atol, rtol=rtol, method='dopri5')
|
|
||||||
latent, delta_ll = sol[0][-1], sol[1][-1]
|
|
||||||
ll_prior = torch.distributions.Normal(0, sigma_max).log_prob(latent).flatten(1).sum(1)
|
|
||||||
return ll_prior + delta_ll, {'fevals': fevals}
|
|
||||||
|
|
||||||
|
|
||||||
class PIDStepSizeController:
|
class PIDStepSizeController:
|
||||||
"""A PID controller for ODE adaptive step size control."""
|
"""A PID controller for ODE adaptive step size control."""
|
||||||
def __init__(self, h, pcoeff, icoeff, dcoeff, order=1, accept_safety=0.81, eps=1e-8):
|
def __init__(self, h, pcoeff, icoeff, dcoeff, order=1, accept_safety=0.81, eps=1e-8):
|
||||||
@ -544,7 +529,7 @@ def sample_dpmpp_sde(model, x, sigmas, extra_args=None, callback=None, disable=N
|
|||||||
"""DPM-Solver++ (stochastic)."""
|
"""DPM-Solver++ (stochastic)."""
|
||||||
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
||||||
seed = extra_args.get("seed", None)
|
seed = extra_args.get("seed", None)
|
||||||
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed) if noise_sampler is None else noise_sampler
|
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
||||||
extra_args = {} if extra_args is None else extra_args
|
extra_args = {} if extra_args is None else extra_args
|
||||||
s_in = x.new_ones([x.shape[0]])
|
s_in = x.new_ones([x.shape[0]])
|
||||||
sigma_fn = lambda t: t.neg().exp()
|
sigma_fn = lambda t: t.neg().exp()
|
||||||
@ -616,7 +601,7 @@ def sample_dpmpp_2m_sde(model, x, sigmas, extra_args=None, callback=None, disabl
|
|||||||
|
|
||||||
seed = extra_args.get("seed", None)
|
seed = extra_args.get("seed", None)
|
||||||
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
||||||
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed) if noise_sampler is None else noise_sampler
|
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
||||||
extra_args = {} if extra_args is None else extra_args
|
extra_args = {} if extra_args is None else extra_args
|
||||||
s_in = x.new_ones([x.shape[0]])
|
s_in = x.new_ones([x.shape[0]])
|
||||||
|
|
||||||
@ -646,8 +631,78 @@ def sample_dpmpp_2m_sde(model, x, sigmas, extra_args=None, callback=None, disabl
|
|||||||
elif solver_type == 'midpoint':
|
elif solver_type == 'midpoint':
|
||||||
x = x + 0.5 * (-h - eta_h).expm1().neg() * (1 / r) * (denoised - old_denoised)
|
x = x + 0.5 * (-h - eta_h).expm1().neg() * (1 / r) * (denoised - old_denoised)
|
||||||
|
|
||||||
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * eta_h).expm1().neg().sqrt() * s_noise
|
if eta:
|
||||||
|
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * eta_h).expm1().neg().sqrt() * s_noise
|
||||||
|
|
||||||
old_denoised = denoised
|
old_denoised = denoised
|
||||||
h_last = h
|
h_last = h
|
||||||
return x
|
return x
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def sample_dpmpp_3m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
||||||
|
"""DPM-Solver++(3M) SDE."""
|
||||||
|
|
||||||
|
seed = extra_args.get("seed", None)
|
||||||
|
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
||||||
|
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler
|
||||||
|
extra_args = {} if extra_args is None else extra_args
|
||||||
|
s_in = x.new_ones([x.shape[0]])
|
||||||
|
|
||||||
|
denoised_1, denoised_2 = None, None
|
||||||
|
h, h_1, h_2 = None, None, None
|
||||||
|
|
||||||
|
for i in trange(len(sigmas) - 1, disable=disable):
|
||||||
|
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
||||||
|
if callback is not None:
|
||||||
|
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
||||||
|
if sigmas[i + 1] == 0:
|
||||||
|
# Denoising step
|
||||||
|
x = denoised
|
||||||
|
else:
|
||||||
|
t, s = -sigmas[i].log(), -sigmas[i + 1].log()
|
||||||
|
h = s - t
|
||||||
|
h_eta = h * (eta + 1)
|
||||||
|
|
||||||
|
x = torch.exp(-h_eta) * x + (-h_eta).expm1().neg() * denoised
|
||||||
|
|
||||||
|
if h_2 is not None:
|
||||||
|
r0 = h_1 / h
|
||||||
|
r1 = h_2 / h
|
||||||
|
d1_0 = (denoised - denoised_1) / r0
|
||||||
|
d1_1 = (denoised_1 - denoised_2) / r1
|
||||||
|
d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)
|
||||||
|
d2 = (d1_0 - d1_1) / (r0 + r1)
|
||||||
|
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
||||||
|
phi_3 = phi_2 / h_eta - 0.5
|
||||||
|
x = x + phi_2 * d1 - phi_3 * d2
|
||||||
|
elif h_1 is not None:
|
||||||
|
r = h_1 / h
|
||||||
|
d = (denoised - denoised_1) / r
|
||||||
|
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
||||||
|
x = x + phi_2 * d
|
||||||
|
|
||||||
|
if eta:
|
||||||
|
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * h * eta).expm1().neg().sqrt() * s_noise
|
||||||
|
|
||||||
|
denoised_1, denoised_2 = denoised, denoised_1
|
||||||
|
h_1, h_2 = h, h_1
|
||||||
|
return x
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def sample_dpmpp_3m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
|
||||||
|
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
||||||
|
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
||||||
|
return sample_dpmpp_3m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler)
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def sample_dpmpp_2m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'):
|
||||||
|
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
||||||
|
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
||||||
|
return sample_dpmpp_2m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, solver_type=solver_type)
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def sample_dpmpp_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2):
|
||||||
|
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
||||||
|
noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler
|
||||||
|
return sample_dpmpp_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, r=r)
|
||||||
|
|
||||||
|
|||||||
@ -11,21 +11,21 @@ class SD15(LatentFormat):
|
|||||||
self.scale_factor = scale_factor
|
self.scale_factor = scale_factor
|
||||||
self.latent_rgb_factors = [
|
self.latent_rgb_factors = [
|
||||||
# R G B
|
# R G B
|
||||||
[0.298, 0.207, 0.208], # L1
|
[ 0.3512, 0.2297, 0.3227],
|
||||||
[0.187, 0.286, 0.173], # L2
|
[ 0.3250, 0.4974, 0.2350],
|
||||||
[-0.158, 0.189, 0.264], # L3
|
[-0.2829, 0.1762, 0.2721],
|
||||||
[-0.184, -0.271, -0.473], # L4
|
[-0.2120, -0.2616, -0.7177]
|
||||||
]
|
]
|
||||||
self.taesd_decoder_name = "taesd_decoder.pth"
|
self.taesd_decoder_name = "taesd_decoder.pth"
|
||||||
|
|
||||||
class SDXL(LatentFormat):
|
class SDXL(LatentFormat):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.scale_factor = 0.13025
|
self.scale_factor = 0.13025
|
||||||
self.latent_rgb_factors = [ #TODO: these are the factors for SD1.5, need to estimate new ones for SDXL
|
self.latent_rgb_factors = [
|
||||||
# R G B
|
# R G B
|
||||||
[0.298, 0.207, 0.208], # L1
|
[ 0.3920, 0.4054, 0.4549],
|
||||||
[0.187, 0.286, 0.173], # L2
|
[-0.2634, -0.0196, 0.0653],
|
||||||
[-0.158, 0.189, 0.264], # L3
|
[ 0.0568, 0.1687, -0.0755],
|
||||||
[-0.184, -0.271, -0.473], # L4
|
[-0.3112, -0.2359, -0.2076]
|
||||||
]
|
]
|
||||||
self.taesd_decoder_name = "taesdxl_decoder.pth"
|
self.taesd_decoder_name = "taesdxl_decoder.pth"
|
||||||
|
|||||||
@ -14,6 +14,7 @@ class DDIMSampler(object):
|
|||||||
self.ddpm_num_timesteps = model.num_timesteps
|
self.ddpm_num_timesteps = model.num_timesteps
|
||||||
self.schedule = schedule
|
self.schedule = schedule
|
||||||
self.device = device
|
self.device = device
|
||||||
|
self.parameterization = kwargs.get("parameterization", "eps")
|
||||||
|
|
||||||
def register_buffer(self, name, attr):
|
def register_buffer(self, name, attr):
|
||||||
if type(attr) == torch.Tensor:
|
if type(attr) == torch.Tensor:
|
||||||
@ -261,7 +262,7 @@ class DDIMSampler(object):
|
|||||||
b, *_, device = *x.shape, x.device
|
b, *_, device = *x.shape, x.device
|
||||||
|
|
||||||
if denoise_function is not None:
|
if denoise_function is not None:
|
||||||
model_output = denoise_function(self.model.apply_model, x, t, **extra_args)
|
model_output = denoise_function(x, t, **extra_args)
|
||||||
elif unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
elif unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
||||||
model_output = self.model.apply_model(x, t, c)
|
model_output = self.model.apply_model(x, t, c)
|
||||||
else:
|
else:
|
||||||
@ -289,13 +290,13 @@ class DDIMSampler(object):
|
|||||||
model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
|
model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
|
||||||
model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
|
model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
|
||||||
|
|
||||||
if self.model.parameterization == "v":
|
if self.parameterization == "v":
|
||||||
e_t = extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * model_output + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
|
e_t = extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * model_output + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
|
||||||
else:
|
else:
|
||||||
e_t = model_output
|
e_t = model_output
|
||||||
|
|
||||||
if score_corrector is not None:
|
if score_corrector is not None:
|
||||||
assert self.model.parameterization == "eps", 'not implemented'
|
assert self.parameterization == "eps", 'not implemented'
|
||||||
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
||||||
|
|
||||||
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
||||||
@ -309,7 +310,7 @@ class DDIMSampler(object):
|
|||||||
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
|
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
|
||||||
|
|
||||||
# current prediction for x_0
|
# current prediction for x_0
|
||||||
if self.model.parameterization != "v":
|
if self.parameterization != "v":
|
||||||
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
||||||
else:
|
else:
|
||||||
pred_x0 = extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * x - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * model_output
|
pred_x0 = extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * x - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * model_output
|
||||||
|
|||||||
@ -10,17 +10,21 @@ from .diffusionmodules.util import checkpoint
|
|||||||
from .sub_quadratic_attention import efficient_dot_product_attention
|
from .sub_quadratic_attention import efficient_dot_product_attention
|
||||||
|
|
||||||
from comfy import model_management
|
from comfy import model_management
|
||||||
import comfy.ops
|
|
||||||
|
|
||||||
if model_management.xformers_enabled():
|
if model_management.xformers_enabled():
|
||||||
import xformers
|
import xformers
|
||||||
import xformers.ops
|
import xformers.ops
|
||||||
|
|
||||||
# CrossAttn precision handling
|
|
||||||
import os
|
|
||||||
_ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32")
|
|
||||||
|
|
||||||
from comfy.cli_args import args
|
from comfy.cli_args import args
|
||||||
|
import comfy.ops
|
||||||
|
|
||||||
|
# CrossAttn precision handling
|
||||||
|
if args.dont_upcast_attention:
|
||||||
|
print("disabling upcasting of attention")
|
||||||
|
_ATTN_PRECISION = "fp16"
|
||||||
|
else:
|
||||||
|
_ATTN_PRECISION = "fp32"
|
||||||
|
|
||||||
|
|
||||||
def exists(val):
|
def exists(val):
|
||||||
return val is not None
|
return val is not None
|
||||||
@ -33,7 +37,7 @@ def uniq(arr):
|
|||||||
def default(val, d):
|
def default(val, d):
|
||||||
if exists(val):
|
if exists(val):
|
||||||
return val
|
return val
|
||||||
return d() if isfunction(d) else d
|
return d
|
||||||
|
|
||||||
|
|
||||||
def max_neg_value(t):
|
def max_neg_value(t):
|
||||||
@ -49,9 +53,9 @@ def init_(tensor):
|
|||||||
|
|
||||||
# feedforward
|
# feedforward
|
||||||
class GEGLU(nn.Module):
|
class GEGLU(nn.Module):
|
||||||
def __init__(self, dim_in, dim_out, dtype=None):
|
def __init__(self, dim_in, dim_out, dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.proj = comfy.ops.Linear(dim_in, dim_out * 2, dtype=dtype)
|
self.proj = operations.Linear(dim_in, dim_out * 2, dtype=dtype, device=device)
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
x, gate = self.proj(x).chunk(2, dim=-1)
|
x, gate = self.proj(x).chunk(2, dim=-1)
|
||||||
@ -59,19 +63,19 @@ class GEGLU(nn.Module):
|
|||||||
|
|
||||||
|
|
||||||
class FeedForward(nn.Module):
|
class FeedForward(nn.Module):
|
||||||
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0., dtype=None):
|
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0., dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
inner_dim = int(dim * mult)
|
inner_dim = int(dim * mult)
|
||||||
dim_out = default(dim_out, dim)
|
dim_out = default(dim_out, dim)
|
||||||
project_in = nn.Sequential(
|
project_in = nn.Sequential(
|
||||||
comfy.ops.Linear(dim, inner_dim, dtype=dtype),
|
operations.Linear(dim, inner_dim, dtype=dtype, device=device),
|
||||||
nn.GELU()
|
nn.GELU()
|
||||||
) if not glu else GEGLU(dim, inner_dim, dtype=dtype)
|
) if not glu else GEGLU(dim, inner_dim, dtype=dtype, device=device, operations=operations)
|
||||||
|
|
||||||
self.net = nn.Sequential(
|
self.net = nn.Sequential(
|
||||||
project_in,
|
project_in,
|
||||||
nn.Dropout(dropout),
|
nn.Dropout(dropout),
|
||||||
comfy.ops.Linear(inner_dim, dim_out, dtype=dtype)
|
operations.Linear(inner_dim, dim_out, dtype=dtype, device=device)
|
||||||
)
|
)
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
@ -87,8 +91,8 @@ def zero_module(module):
|
|||||||
return module
|
return module
|
||||||
|
|
||||||
|
|
||||||
def Normalize(in_channels, dtype=None):
|
def Normalize(in_channels, dtype=None, device=None):
|
||||||
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True, dtype=dtype)
|
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True, dtype=dtype, device=device)
|
||||||
|
|
||||||
|
|
||||||
class SpatialSelfAttention(nn.Module):
|
class SpatialSelfAttention(nn.Module):
|
||||||
@ -145,7 +149,7 @@ class SpatialSelfAttention(nn.Module):
|
|||||||
|
|
||||||
|
|
||||||
class CrossAttentionBirchSan(nn.Module):
|
class CrossAttentionBirchSan(nn.Module):
|
||||||
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None):
|
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
inner_dim = dim_head * heads
|
inner_dim = dim_head * heads
|
||||||
context_dim = default(context_dim, query_dim)
|
context_dim = default(context_dim, query_dim)
|
||||||
@ -153,12 +157,12 @@ class CrossAttentionBirchSan(nn.Module):
|
|||||||
self.scale = dim_head ** -0.5
|
self.scale = dim_head ** -0.5
|
||||||
self.heads = heads
|
self.heads = heads
|
||||||
|
|
||||||
self.to_q = comfy.ops.Linear(query_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_k = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_v = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
|
|
||||||
self.to_out = nn.Sequential(
|
self.to_out = nn.Sequential(
|
||||||
comfy.ops.Linear(inner_dim, query_dim, dtype=dtype),
|
operations.Linear(inner_dim, query_dim, dtype=dtype, device=device),
|
||||||
nn.Dropout(dropout)
|
nn.Dropout(dropout)
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -242,7 +246,7 @@ class CrossAttentionBirchSan(nn.Module):
|
|||||||
|
|
||||||
|
|
||||||
class CrossAttentionDoggettx(nn.Module):
|
class CrossAttentionDoggettx(nn.Module):
|
||||||
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None):
|
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
inner_dim = dim_head * heads
|
inner_dim = dim_head * heads
|
||||||
context_dim = default(context_dim, query_dim)
|
context_dim = default(context_dim, query_dim)
|
||||||
@ -250,12 +254,12 @@ class CrossAttentionDoggettx(nn.Module):
|
|||||||
self.scale = dim_head ** -0.5
|
self.scale = dim_head ** -0.5
|
||||||
self.heads = heads
|
self.heads = heads
|
||||||
|
|
||||||
self.to_q = comfy.ops.Linear(query_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_k = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_v = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
|
|
||||||
self.to_out = nn.Sequential(
|
self.to_out = nn.Sequential(
|
||||||
comfy.ops.Linear(inner_dim, query_dim, dtype=dtype),
|
operations.Linear(inner_dim, query_dim, dtype=dtype, device=device),
|
||||||
nn.Dropout(dropout)
|
nn.Dropout(dropout)
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -275,7 +279,7 @@ class CrossAttentionDoggettx(nn.Module):
|
|||||||
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q_in, k_in, v_in))
|
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q_in, k_in, v_in))
|
||||||
del q_in, k_in, v_in
|
del q_in, k_in, v_in
|
||||||
|
|
||||||
r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device)
|
r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype)
|
||||||
|
|
||||||
mem_free_total = model_management.get_free_memory(q.device)
|
mem_free_total = model_management.get_free_memory(q.device)
|
||||||
|
|
||||||
@ -311,7 +315,7 @@ class CrossAttentionDoggettx(nn.Module):
|
|||||||
s1 = einsum('b i d, b j d -> b i j', q[:, i:end], k) * self.scale
|
s1 = einsum('b i d, b j d -> b i j', q[:, i:end], k) * self.scale
|
||||||
first_op_done = True
|
first_op_done = True
|
||||||
|
|
||||||
s2 = s1.softmax(dim=-1)
|
s2 = s1.softmax(dim=-1).to(v.dtype)
|
||||||
del s1
|
del s1
|
||||||
|
|
||||||
r1[:, i:end] = einsum('b i j, b j d -> b i d', s2, v)
|
r1[:, i:end] = einsum('b i j, b j d -> b i d', s2, v)
|
||||||
@ -319,8 +323,7 @@ class CrossAttentionDoggettx(nn.Module):
|
|||||||
break
|
break
|
||||||
except model_management.OOM_EXCEPTION as e:
|
except model_management.OOM_EXCEPTION as e:
|
||||||
if first_op_done == False:
|
if first_op_done == False:
|
||||||
torch.cuda.empty_cache()
|
model_management.soft_empty_cache(True)
|
||||||
torch.cuda.ipc_collect()
|
|
||||||
if cleared_cache == False:
|
if cleared_cache == False:
|
||||||
cleared_cache = True
|
cleared_cache = True
|
||||||
print("out of memory error, emptying cache and trying again")
|
print("out of memory error, emptying cache and trying again")
|
||||||
@ -340,7 +343,7 @@ class CrossAttentionDoggettx(nn.Module):
|
|||||||
return self.to_out(r2)
|
return self.to_out(r2)
|
||||||
|
|
||||||
class CrossAttention(nn.Module):
|
class CrossAttention(nn.Module):
|
||||||
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None):
|
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
inner_dim = dim_head * heads
|
inner_dim = dim_head * heads
|
||||||
context_dim = default(context_dim, query_dim)
|
context_dim = default(context_dim, query_dim)
|
||||||
@ -348,12 +351,12 @@ class CrossAttention(nn.Module):
|
|||||||
self.scale = dim_head ** -0.5
|
self.scale = dim_head ** -0.5
|
||||||
self.heads = heads
|
self.heads = heads
|
||||||
|
|
||||||
self.to_q = comfy.ops.Linear(query_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_k = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_v = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
|
|
||||||
self.to_out = nn.Sequential(
|
self.to_out = nn.Sequential(
|
||||||
comfy.ops.Linear(inner_dim, query_dim, dtype=dtype),
|
operations.Linear(inner_dim, query_dim, dtype=dtype, device=device),
|
||||||
nn.Dropout(dropout)
|
nn.Dropout(dropout)
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -396,21 +399,19 @@ class CrossAttention(nn.Module):
|
|||||||
|
|
||||||
class MemoryEfficientCrossAttention(nn.Module):
|
class MemoryEfficientCrossAttention(nn.Module):
|
||||||
# https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
|
# https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
|
||||||
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0, dtype=None):
|
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0, dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
print(f"Setting up {self.__class__.__name__}. Query dim is {query_dim}, context_dim is {context_dim} and using "
|
|
||||||
f"{heads} heads.")
|
|
||||||
inner_dim = dim_head * heads
|
inner_dim = dim_head * heads
|
||||||
context_dim = default(context_dim, query_dim)
|
context_dim = default(context_dim, query_dim)
|
||||||
|
|
||||||
self.heads = heads
|
self.heads = heads
|
||||||
self.dim_head = dim_head
|
self.dim_head = dim_head
|
||||||
|
|
||||||
self.to_q = comfy.ops.Linear(query_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_k = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_v = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
|
|
||||||
self.to_out = nn.Sequential(comfy.ops.Linear(inner_dim, query_dim, dtype=dtype), nn.Dropout(dropout))
|
self.to_out = nn.Sequential(operations.Linear(inner_dim, query_dim, dtype=dtype, device=device), nn.Dropout(dropout))
|
||||||
self.attention_op: Optional[Any] = None
|
self.attention_op: Optional[Any] = None
|
||||||
|
|
||||||
def forward(self, x, context=None, value=None, mask=None):
|
def forward(self, x, context=None, value=None, mask=None):
|
||||||
@ -447,7 +448,7 @@ class MemoryEfficientCrossAttention(nn.Module):
|
|||||||
return self.to_out(out)
|
return self.to_out(out)
|
||||||
|
|
||||||
class CrossAttentionPytorch(nn.Module):
|
class CrossAttentionPytorch(nn.Module):
|
||||||
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None):
|
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
inner_dim = dim_head * heads
|
inner_dim = dim_head * heads
|
||||||
context_dim = default(context_dim, query_dim)
|
context_dim = default(context_dim, query_dim)
|
||||||
@ -455,11 +456,11 @@ class CrossAttentionPytorch(nn.Module):
|
|||||||
self.heads = heads
|
self.heads = heads
|
||||||
self.dim_head = dim_head
|
self.dim_head = dim_head
|
||||||
|
|
||||||
self.to_q = comfy.ops.Linear(query_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_k = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
self.to_v = comfy.ops.Linear(context_dim, inner_dim, bias=False, dtype=dtype)
|
self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
|
||||||
|
|
||||||
self.to_out = nn.Sequential(comfy.ops.Linear(inner_dim, query_dim, dtype=dtype), nn.Dropout(dropout))
|
self.to_out = nn.Sequential(operations.Linear(inner_dim, query_dim, dtype=dtype, device=device), nn.Dropout(dropout))
|
||||||
self.attention_op: Optional[Any] = None
|
self.attention_op: Optional[Any] = None
|
||||||
|
|
||||||
def forward(self, x, context=None, value=None, mask=None):
|
def forward(self, x, context=None, value=None, mask=None):
|
||||||
@ -505,17 +506,17 @@ else:
|
|||||||
|
|
||||||
class BasicTransformerBlock(nn.Module):
|
class BasicTransformerBlock(nn.Module):
|
||||||
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
|
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True,
|
||||||
disable_self_attn=False, dtype=None):
|
disable_self_attn=False, dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.disable_self_attn = disable_self_attn
|
self.disable_self_attn = disable_self_attn
|
||||||
self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
|
self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout,
|
||||||
context_dim=context_dim if self.disable_self_attn else None, dtype=dtype) # is a self-attention if not self.disable_self_attn
|
context_dim=context_dim if self.disable_self_attn else None, dtype=dtype, device=device, operations=operations) # is a self-attention if not self.disable_self_attn
|
||||||
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff, dtype=dtype)
|
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff, dtype=dtype, device=device, operations=operations)
|
||||||
self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
|
self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
|
||||||
heads=n_heads, dim_head=d_head, dropout=dropout, dtype=dtype) # is self-attn if context is none
|
heads=n_heads, dim_head=d_head, dropout=dropout, dtype=dtype, device=device, operations=operations) # is self-attn if context is none
|
||||||
self.norm1 = nn.LayerNorm(dim, dtype=dtype)
|
self.norm1 = nn.LayerNorm(dim, dtype=dtype, device=device)
|
||||||
self.norm2 = nn.LayerNorm(dim, dtype=dtype)
|
self.norm2 = nn.LayerNorm(dim, dtype=dtype, device=device)
|
||||||
self.norm3 = nn.LayerNorm(dim, dtype=dtype)
|
self.norm3 = nn.LayerNorm(dim, dtype=dtype, device=device)
|
||||||
self.checkpoint = checkpoint
|
self.checkpoint = checkpoint
|
||||||
self.n_heads = n_heads
|
self.n_heads = n_heads
|
||||||
self.d_head = d_head
|
self.d_head = d_head
|
||||||
@ -645,34 +646,34 @@ class SpatialTransformer(nn.Module):
|
|||||||
def __init__(self, in_channels, n_heads, d_head,
|
def __init__(self, in_channels, n_heads, d_head,
|
||||||
depth=1, dropout=0., context_dim=None,
|
depth=1, dropout=0., context_dim=None,
|
||||||
disable_self_attn=False, use_linear=False,
|
disable_self_attn=False, use_linear=False,
|
||||||
use_checkpoint=True, dtype=None):
|
use_checkpoint=True, dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
if exists(context_dim) and not isinstance(context_dim, list):
|
if exists(context_dim) and not isinstance(context_dim, list):
|
||||||
context_dim = [context_dim] * depth
|
context_dim = [context_dim] * depth
|
||||||
self.in_channels = in_channels
|
self.in_channels = in_channels
|
||||||
inner_dim = n_heads * d_head
|
inner_dim = n_heads * d_head
|
||||||
self.norm = Normalize(in_channels, dtype=dtype)
|
self.norm = Normalize(in_channels, dtype=dtype, device=device)
|
||||||
if not use_linear:
|
if not use_linear:
|
||||||
self.proj_in = nn.Conv2d(in_channels,
|
self.proj_in = operations.Conv2d(in_channels,
|
||||||
inner_dim,
|
inner_dim,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0, dtype=dtype)
|
padding=0, dtype=dtype, device=device)
|
||||||
else:
|
else:
|
||||||
self.proj_in = comfy.ops.Linear(in_channels, inner_dim, dtype=dtype)
|
self.proj_in = operations.Linear(in_channels, inner_dim, dtype=dtype, device=device)
|
||||||
|
|
||||||
self.transformer_blocks = nn.ModuleList(
|
self.transformer_blocks = nn.ModuleList(
|
||||||
[BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
|
[BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim[d],
|
||||||
disable_self_attn=disable_self_attn, checkpoint=use_checkpoint, dtype=dtype)
|
disable_self_attn=disable_self_attn, checkpoint=use_checkpoint, dtype=dtype, device=device, operations=operations)
|
||||||
for d in range(depth)]
|
for d in range(depth)]
|
||||||
)
|
)
|
||||||
if not use_linear:
|
if not use_linear:
|
||||||
self.proj_out = nn.Conv2d(inner_dim,in_channels,
|
self.proj_out = operations.Conv2d(inner_dim,in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0, dtype=dtype)
|
padding=0, dtype=dtype, device=device)
|
||||||
else:
|
else:
|
||||||
self.proj_out = comfy.ops.Linear(in_channels, inner_dim, dtype=dtype)
|
self.proj_out = operations.Linear(in_channels, inner_dim, dtype=dtype, device=device)
|
||||||
self.use_linear = use_linear
|
self.use_linear = use_linear
|
||||||
|
|
||||||
def forward(self, x, context=None, transformer_options={}):
|
def forward(self, x, context=None, transformer_options={}):
|
||||||
|
|||||||
@ -8,6 +8,7 @@ from typing import Optional, Any
|
|||||||
|
|
||||||
from ..attention import MemoryEfficientCrossAttention
|
from ..attention import MemoryEfficientCrossAttention
|
||||||
from comfy import model_management
|
from comfy import model_management
|
||||||
|
import comfy.ops
|
||||||
|
|
||||||
if model_management.xformers_enabled_vae():
|
if model_management.xformers_enabled_vae():
|
||||||
import xformers
|
import xformers
|
||||||
@ -48,14 +49,25 @@ class Upsample(nn.Module):
|
|||||||
super().__init__()
|
super().__init__()
|
||||||
self.with_conv = with_conv
|
self.with_conv = with_conv
|
||||||
if self.with_conv:
|
if self.with_conv:
|
||||||
self.conv = torch.nn.Conv2d(in_channels,
|
self.conv = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=1)
|
padding=1)
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
try:
|
||||||
|
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
||||||
|
except: #operation not implemented for bf16
|
||||||
|
b, c, h, w = x.shape
|
||||||
|
out = torch.empty((b, c, h*2, w*2), dtype=x.dtype, layout=x.layout, device=x.device)
|
||||||
|
split = 8
|
||||||
|
l = out.shape[1] // split
|
||||||
|
for i in range(0, out.shape[1], l):
|
||||||
|
out[:,i:i+l] = torch.nn.functional.interpolate(x[:,i:i+l].to(torch.float32), scale_factor=2.0, mode="nearest").to(x.dtype)
|
||||||
|
del x
|
||||||
|
x = out
|
||||||
|
|
||||||
if self.with_conv:
|
if self.with_conv:
|
||||||
x = self.conv(x)
|
x = self.conv(x)
|
||||||
return x
|
return x
|
||||||
@ -67,17 +79,16 @@ class Downsample(nn.Module):
|
|||||||
self.with_conv = with_conv
|
self.with_conv = with_conv
|
||||||
if self.with_conv:
|
if self.with_conv:
|
||||||
# no asymmetric padding in torch conv, must do it ourselves
|
# no asymmetric padding in torch conv, must do it ourselves
|
||||||
self.conv = torch.nn.Conv2d(in_channels,
|
self.conv = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=2,
|
stride=2,
|
||||||
padding=0)
|
padding=0)
|
||||||
|
|
||||||
def forward(self, x, already_padded=False):
|
def forward(self, x):
|
||||||
if self.with_conv:
|
if self.with_conv:
|
||||||
if not already_padded:
|
pad = (0,1,0,1)
|
||||||
pad = (0,1,0,1)
|
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
||||||
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
|
||||||
x = self.conv(x)
|
x = self.conv(x)
|
||||||
else:
|
else:
|
||||||
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
|
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
|
||||||
@ -95,30 +106,30 @@ class ResnetBlock(nn.Module):
|
|||||||
|
|
||||||
self.swish = torch.nn.SiLU(inplace=True)
|
self.swish = torch.nn.SiLU(inplace=True)
|
||||||
self.norm1 = Normalize(in_channels)
|
self.norm1 = Normalize(in_channels)
|
||||||
self.conv1 = torch.nn.Conv2d(in_channels,
|
self.conv1 = comfy.ops.Conv2d(in_channels,
|
||||||
out_channels,
|
out_channels,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=1)
|
padding=1)
|
||||||
if temb_channels > 0:
|
if temb_channels > 0:
|
||||||
self.temb_proj = torch.nn.Linear(temb_channels,
|
self.temb_proj = comfy.ops.Linear(temb_channels,
|
||||||
out_channels)
|
out_channels)
|
||||||
self.norm2 = Normalize(out_channels)
|
self.norm2 = Normalize(out_channels)
|
||||||
self.dropout = torch.nn.Dropout(dropout, inplace=True)
|
self.dropout = torch.nn.Dropout(dropout, inplace=True)
|
||||||
self.conv2 = torch.nn.Conv2d(out_channels,
|
self.conv2 = comfy.ops.Conv2d(out_channels,
|
||||||
out_channels,
|
out_channels,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=1)
|
padding=1)
|
||||||
if self.in_channels != self.out_channels:
|
if self.in_channels != self.out_channels:
|
||||||
if self.use_conv_shortcut:
|
if self.use_conv_shortcut:
|
||||||
self.conv_shortcut = torch.nn.Conv2d(in_channels,
|
self.conv_shortcut = comfy.ops.Conv2d(in_channels,
|
||||||
out_channels,
|
out_channels,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=1)
|
padding=1)
|
||||||
else:
|
else:
|
||||||
self.nin_shortcut = torch.nn.Conv2d(in_channels,
|
self.nin_shortcut = comfy.ops.Conv2d(in_channels,
|
||||||
out_channels,
|
out_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -175,6 +186,7 @@ def slice_attention(q, k, v):
|
|||||||
del s2
|
del s2
|
||||||
break
|
break
|
||||||
except model_management.OOM_EXCEPTION as e:
|
except model_management.OOM_EXCEPTION as e:
|
||||||
|
model_management.soft_empty_cache(True)
|
||||||
steps *= 2
|
steps *= 2
|
||||||
if steps > 128:
|
if steps > 128:
|
||||||
raise e
|
raise e
|
||||||
@ -188,22 +200,22 @@ class AttnBlock(nn.Module):
|
|||||||
self.in_channels = in_channels
|
self.in_channels = in_channels
|
||||||
|
|
||||||
self.norm = Normalize(in_channels)
|
self.norm = Normalize(in_channels)
|
||||||
self.q = torch.nn.Conv2d(in_channels,
|
self.q = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.k = torch.nn.Conv2d(in_channels,
|
self.k = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.v = torch.nn.Conv2d(in_channels,
|
self.v = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.proj_out = torch.nn.Conv2d(in_channels,
|
self.proj_out = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -243,22 +255,22 @@ class MemoryEfficientAttnBlock(nn.Module):
|
|||||||
self.in_channels = in_channels
|
self.in_channels = in_channels
|
||||||
|
|
||||||
self.norm = Normalize(in_channels)
|
self.norm = Normalize(in_channels)
|
||||||
self.q = torch.nn.Conv2d(in_channels,
|
self.q = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.k = torch.nn.Conv2d(in_channels,
|
self.k = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.v = torch.nn.Conv2d(in_channels,
|
self.v = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.proj_out = torch.nn.Conv2d(in_channels,
|
self.proj_out = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -274,25 +286,17 @@ class MemoryEfficientAttnBlock(nn.Module):
|
|||||||
|
|
||||||
# compute attention
|
# compute attention
|
||||||
B, C, H, W = q.shape
|
B, C, H, W = q.shape
|
||||||
q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
|
|
||||||
|
|
||||||
q, k, v = map(
|
q, k, v = map(
|
||||||
lambda t: t.unsqueeze(3)
|
lambda t: t.view(B, C, -1).transpose(1, 2).contiguous(),
|
||||||
.reshape(B, t.shape[1], 1, C)
|
|
||||||
.permute(0, 2, 1, 3)
|
|
||||||
.reshape(B * 1, t.shape[1], C)
|
|
||||||
.contiguous(),
|
|
||||||
(q, k, v),
|
(q, k, v),
|
||||||
)
|
)
|
||||||
out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
|
|
||||||
|
|
||||||
out = (
|
try:
|
||||||
out.unsqueeze(0)
|
out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
|
||||||
.reshape(B, 1, out.shape[1], C)
|
out = out.transpose(1, 2).reshape(B, C, H, W)
|
||||||
.permute(0, 2, 1, 3)
|
except NotImplementedError as e:
|
||||||
.reshape(B, out.shape[1], C)
|
out = slice_attention(q.view(B, -1, C), k.view(B, -1, C).transpose(1, 2), v.view(B, -1, C).transpose(1, 2)).reshape(B, C, H, W)
|
||||||
)
|
|
||||||
out = rearrange(out, 'b (h w) c -> b c h w', b=B, h=H, w=W, c=C)
|
|
||||||
out = self.proj_out(out)
|
out = self.proj_out(out)
|
||||||
return x+out
|
return x+out
|
||||||
|
|
||||||
@ -302,22 +306,22 @@ class MemoryEfficientAttnBlockPytorch(nn.Module):
|
|||||||
self.in_channels = in_channels
|
self.in_channels = in_channels
|
||||||
|
|
||||||
self.norm = Normalize(in_channels)
|
self.norm = Normalize(in_channels)
|
||||||
self.q = torch.nn.Conv2d(in_channels,
|
self.q = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.k = torch.nn.Conv2d(in_channels,
|
self.k = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.v = torch.nn.Conv2d(in_channels,
|
self.v = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
padding=0)
|
padding=0)
|
||||||
self.proj_out = torch.nn.Conv2d(in_channels,
|
self.proj_out = comfy.ops.Conv2d(in_channels,
|
||||||
in_channels,
|
in_channels,
|
||||||
kernel_size=1,
|
kernel_size=1,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -399,14 +403,14 @@ class Model(nn.Module):
|
|||||||
# timestep embedding
|
# timestep embedding
|
||||||
self.temb = nn.Module()
|
self.temb = nn.Module()
|
||||||
self.temb.dense = nn.ModuleList([
|
self.temb.dense = nn.ModuleList([
|
||||||
torch.nn.Linear(self.ch,
|
comfy.ops.Linear(self.ch,
|
||||||
self.temb_ch),
|
self.temb_ch),
|
||||||
torch.nn.Linear(self.temb_ch,
|
comfy.ops.Linear(self.temb_ch,
|
||||||
self.temb_ch),
|
self.temb_ch),
|
||||||
])
|
])
|
||||||
|
|
||||||
# downsampling
|
# downsampling
|
||||||
self.conv_in = torch.nn.Conv2d(in_channels,
|
self.conv_in = comfy.ops.Conv2d(in_channels,
|
||||||
self.ch,
|
self.ch,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -475,7 +479,7 @@ class Model(nn.Module):
|
|||||||
|
|
||||||
# end
|
# end
|
||||||
self.norm_out = Normalize(block_in)
|
self.norm_out = Normalize(block_in)
|
||||||
self.conv_out = torch.nn.Conv2d(block_in,
|
self.conv_out = comfy.ops.Conv2d(block_in,
|
||||||
out_ch,
|
out_ch,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -548,7 +552,7 @@ class Encoder(nn.Module):
|
|||||||
self.in_channels = in_channels
|
self.in_channels = in_channels
|
||||||
|
|
||||||
# downsampling
|
# downsampling
|
||||||
self.conv_in = torch.nn.Conv2d(in_channels,
|
self.conv_in = comfy.ops.Conv2d(in_channels,
|
||||||
self.ch,
|
self.ch,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -593,7 +597,7 @@ class Encoder(nn.Module):
|
|||||||
|
|
||||||
# end
|
# end
|
||||||
self.norm_out = Normalize(block_in)
|
self.norm_out = Normalize(block_in)
|
||||||
self.conv_out = torch.nn.Conv2d(block_in,
|
self.conv_out = comfy.ops.Conv2d(block_in,
|
||||||
2*z_channels if double_z else z_channels,
|
2*z_channels if double_z else z_channels,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -602,9 +606,6 @@ class Encoder(nn.Module):
|
|||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
# timestep embedding
|
# timestep embedding
|
||||||
temb = None
|
temb = None
|
||||||
pad = (0,1,0,1)
|
|
||||||
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
|
||||||
already_padded = True
|
|
||||||
# downsampling
|
# downsampling
|
||||||
h = self.conv_in(x)
|
h = self.conv_in(x)
|
||||||
for i_level in range(self.num_resolutions):
|
for i_level in range(self.num_resolutions):
|
||||||
@ -613,8 +614,7 @@ class Encoder(nn.Module):
|
|||||||
if len(self.down[i_level].attn) > 0:
|
if len(self.down[i_level].attn) > 0:
|
||||||
h = self.down[i_level].attn[i_block](h)
|
h = self.down[i_level].attn[i_block](h)
|
||||||
if i_level != self.num_resolutions-1:
|
if i_level != self.num_resolutions-1:
|
||||||
h = self.down[i_level].downsample(h, already_padded)
|
h = self.down[i_level].downsample(h)
|
||||||
already_padded = False
|
|
||||||
|
|
||||||
# middle
|
# middle
|
||||||
h = self.mid.block_1(h, temb)
|
h = self.mid.block_1(h, temb)
|
||||||
@ -653,7 +653,7 @@ class Decoder(nn.Module):
|
|||||||
self.z_shape, np.prod(self.z_shape)))
|
self.z_shape, np.prod(self.z_shape)))
|
||||||
|
|
||||||
# z to block_in
|
# z to block_in
|
||||||
self.conv_in = torch.nn.Conv2d(z_channels,
|
self.conv_in = comfy.ops.Conv2d(z_channels,
|
||||||
block_in,
|
block_in,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
@ -695,7 +695,7 @@ class Decoder(nn.Module):
|
|||||||
|
|
||||||
# end
|
# end
|
||||||
self.norm_out = Normalize(block_in)
|
self.norm_out = Normalize(block_in)
|
||||||
self.conv_out = torch.nn.Conv2d(block_in,
|
self.conv_out = comfy.ops.Conv2d(block_in,
|
||||||
out_ch,
|
out_ch,
|
||||||
kernel_size=3,
|
kernel_size=3,
|
||||||
stride=1,
|
stride=1,
|
||||||
|
|||||||
@ -8,8 +8,6 @@ import torch.nn.functional as F
|
|||||||
|
|
||||||
from .util import (
|
from .util import (
|
||||||
checkpoint,
|
checkpoint,
|
||||||
conv_nd,
|
|
||||||
linear,
|
|
||||||
avg_pool_nd,
|
avg_pool_nd,
|
||||||
zero_module,
|
zero_module,
|
||||||
normalization,
|
normalization,
|
||||||
@ -17,46 +15,7 @@ from .util import (
|
|||||||
)
|
)
|
||||||
from ..attention import SpatialTransformer
|
from ..attention import SpatialTransformer
|
||||||
from comfy.ldm.util import exists
|
from comfy.ldm.util import exists
|
||||||
|
import comfy.ops
|
||||||
|
|
||||||
# dummy replace
|
|
||||||
def convert_module_to_f16(x):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def convert_module_to_f32(x):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
## go
|
|
||||||
class AttentionPool2d(nn.Module):
|
|
||||||
"""
|
|
||||||
Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
spacial_dim: int,
|
|
||||||
embed_dim: int,
|
|
||||||
num_heads_channels: int,
|
|
||||||
output_dim: int = None,
|
|
||||||
):
|
|
||||||
super().__init__()
|
|
||||||
self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5)
|
|
||||||
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
|
|
||||||
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
|
|
||||||
self.num_heads = embed_dim // num_heads_channels
|
|
||||||
self.attention = QKVAttention(self.num_heads)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
b, c, *_spatial = x.shape
|
|
||||||
x = x.reshape(b, c, -1) # NC(HW)
|
|
||||||
x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
|
|
||||||
x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
|
|
||||||
x = self.qkv_proj(x)
|
|
||||||
x = self.attention(x)
|
|
||||||
x = self.c_proj(x)
|
|
||||||
return x[:, :, 0]
|
|
||||||
|
|
||||||
|
|
||||||
class TimestepBlock(nn.Module):
|
class TimestepBlock(nn.Module):
|
||||||
"""
|
"""
|
||||||
@ -111,14 +70,14 @@ class Upsample(nn.Module):
|
|||||||
upsampling occurs in the inner-two dimensions.
|
upsampling occurs in the inner-two dimensions.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None):
|
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.channels = channels
|
self.channels = channels
|
||||||
self.out_channels = out_channels or channels
|
self.out_channels = out_channels or channels
|
||||||
self.use_conv = use_conv
|
self.use_conv = use_conv
|
||||||
self.dims = dims
|
self.dims = dims
|
||||||
if use_conv:
|
if use_conv:
|
||||||
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding, dtype=dtype)
|
self.conv = operations.conv_nd(dims, self.channels, self.out_channels, 3, padding=padding, dtype=dtype, device=device)
|
||||||
|
|
||||||
def forward(self, x, output_shape=None):
|
def forward(self, x, output_shape=None):
|
||||||
assert x.shape[1] == self.channels
|
assert x.shape[1] == self.channels
|
||||||
@ -138,19 +97,6 @@ class Upsample(nn.Module):
|
|||||||
x = self.conv(x)
|
x = self.conv(x)
|
||||||
return x
|
return x
|
||||||
|
|
||||||
class TransposedUpsample(nn.Module):
|
|
||||||
'Learned 2x upsampling without padding'
|
|
||||||
def __init__(self, channels, out_channels=None, ks=5):
|
|
||||||
super().__init__()
|
|
||||||
self.channels = channels
|
|
||||||
self.out_channels = out_channels or channels
|
|
||||||
|
|
||||||
self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
|
|
||||||
|
|
||||||
def forward(self,x):
|
|
||||||
return self.up(x)
|
|
||||||
|
|
||||||
|
|
||||||
class Downsample(nn.Module):
|
class Downsample(nn.Module):
|
||||||
"""
|
"""
|
||||||
A downsampling layer with an optional convolution.
|
A downsampling layer with an optional convolution.
|
||||||
@ -160,7 +106,7 @@ class Downsample(nn.Module):
|
|||||||
downsampling occurs in the inner-two dimensions.
|
downsampling occurs in the inner-two dimensions.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None):
|
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=comfy.ops):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.channels = channels
|
self.channels = channels
|
||||||
self.out_channels = out_channels or channels
|
self.out_channels = out_channels or channels
|
||||||
@ -168,8 +114,8 @@ class Downsample(nn.Module):
|
|||||||
self.dims = dims
|
self.dims = dims
|
||||||
stride = 2 if dims != 3 else (1, 2, 2)
|
stride = 2 if dims != 3 else (1, 2, 2)
|
||||||
if use_conv:
|
if use_conv:
|
||||||
self.op = conv_nd(
|
self.op = operations.conv_nd(
|
||||||
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding, dtype=dtype
|
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding, dtype=dtype, device=device
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
assert self.channels == self.out_channels
|
assert self.channels == self.out_channels
|
||||||
@ -208,7 +154,9 @@ class ResBlock(TimestepBlock):
|
|||||||
use_checkpoint=False,
|
use_checkpoint=False,
|
||||||
up=False,
|
up=False,
|
||||||
down=False,
|
down=False,
|
||||||
dtype=None
|
dtype=None,
|
||||||
|
device=None,
|
||||||
|
operations=comfy.ops
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.channels = channels
|
self.channels = channels
|
||||||
@ -220,46 +168,46 @@ class ResBlock(TimestepBlock):
|
|||||||
self.use_scale_shift_norm = use_scale_shift_norm
|
self.use_scale_shift_norm = use_scale_shift_norm
|
||||||
|
|
||||||
self.in_layers = nn.Sequential(
|
self.in_layers = nn.Sequential(
|
||||||
normalization(channels, dtype=dtype),
|
nn.GroupNorm(32, channels, dtype=dtype, device=device),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
conv_nd(dims, channels, self.out_channels, 3, padding=1, dtype=dtype),
|
operations.conv_nd(dims, channels, self.out_channels, 3, padding=1, dtype=dtype, device=device),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.updown = up or down
|
self.updown = up or down
|
||||||
|
|
||||||
if up:
|
if up:
|
||||||
self.h_upd = Upsample(channels, False, dims, dtype=dtype)
|
self.h_upd = Upsample(channels, False, dims, dtype=dtype, device=device)
|
||||||
self.x_upd = Upsample(channels, False, dims, dtype=dtype)
|
self.x_upd = Upsample(channels, False, dims, dtype=dtype, device=device)
|
||||||
elif down:
|
elif down:
|
||||||
self.h_upd = Downsample(channels, False, dims, dtype=dtype)
|
self.h_upd = Downsample(channels, False, dims, dtype=dtype, device=device)
|
||||||
self.x_upd = Downsample(channels, False, dims, dtype=dtype)
|
self.x_upd = Downsample(channels, False, dims, dtype=dtype, device=device)
|
||||||
else:
|
else:
|
||||||
self.h_upd = self.x_upd = nn.Identity()
|
self.h_upd = self.x_upd = nn.Identity()
|
||||||
|
|
||||||
self.emb_layers = nn.Sequential(
|
self.emb_layers = nn.Sequential(
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
linear(
|
operations.Linear(
|
||||||
emb_channels,
|
emb_channels,
|
||||||
2 * self.out_channels if use_scale_shift_norm else self.out_channels, dtype=dtype
|
2 * self.out_channels if use_scale_shift_norm else self.out_channels, dtype=dtype, device=device
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
self.out_layers = nn.Sequential(
|
self.out_layers = nn.Sequential(
|
||||||
normalization(self.out_channels, dtype=dtype),
|
nn.GroupNorm(32, self.out_channels, dtype=dtype, device=device),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
nn.Dropout(p=dropout),
|
nn.Dropout(p=dropout),
|
||||||
zero_module(
|
zero_module(
|
||||||
conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1, dtype=dtype)
|
operations.conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1, dtype=dtype, device=device)
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.out_channels == channels:
|
if self.out_channels == channels:
|
||||||
self.skip_connection = nn.Identity()
|
self.skip_connection = nn.Identity()
|
||||||
elif use_conv:
|
elif use_conv:
|
||||||
self.skip_connection = conv_nd(
|
self.skip_connection = operations.conv_nd(
|
||||||
dims, channels, self.out_channels, 3, padding=1, dtype=dtype
|
dims, channels, self.out_channels, 3, padding=1, dtype=dtype, device=device
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1, dtype=dtype)
|
self.skip_connection = operations.conv_nd(dims, channels, self.out_channels, 1, dtype=dtype, device=device)
|
||||||
|
|
||||||
def forward(self, x, emb):
|
def forward(self, x, emb):
|
||||||
"""
|
"""
|
||||||
@ -295,142 +243,6 @@ class ResBlock(TimestepBlock):
|
|||||||
h = self.out_layers(h)
|
h = self.out_layers(h)
|
||||||
return self.skip_connection(x) + h
|
return self.skip_connection(x) + h
|
||||||
|
|
||||||
|
|
||||||
class AttentionBlock(nn.Module):
|
|
||||||
"""
|
|
||||||
An attention block that allows spatial positions to attend to each other.
|
|
||||||
Originally ported from here, but adapted to the N-d case.
|
|
||||||
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
channels,
|
|
||||||
num_heads=1,
|
|
||||||
num_head_channels=-1,
|
|
||||||
use_checkpoint=False,
|
|
||||||
use_new_attention_order=False,
|
|
||||||
):
|
|
||||||
super().__init__()
|
|
||||||
self.channels = channels
|
|
||||||
if num_head_channels == -1:
|
|
||||||
self.num_heads = num_heads
|
|
||||||
else:
|
|
||||||
assert (
|
|
||||||
channels % num_head_channels == 0
|
|
||||||
), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
|
|
||||||
self.num_heads = channels // num_head_channels
|
|
||||||
self.use_checkpoint = use_checkpoint
|
|
||||||
self.norm = normalization(channels)
|
|
||||||
self.qkv = conv_nd(1, channels, channels * 3, 1)
|
|
||||||
if use_new_attention_order:
|
|
||||||
# split qkv before split heads
|
|
||||||
self.attention = QKVAttention(self.num_heads)
|
|
||||||
else:
|
|
||||||
# split heads before split qkv
|
|
||||||
self.attention = QKVAttentionLegacy(self.num_heads)
|
|
||||||
|
|
||||||
self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
|
|
||||||
#return pt_checkpoint(self._forward, x) # pytorch
|
|
||||||
|
|
||||||
def _forward(self, x):
|
|
||||||
b, c, *spatial = x.shape
|
|
||||||
x = x.reshape(b, c, -1)
|
|
||||||
qkv = self.qkv(self.norm(x))
|
|
||||||
h = self.attention(qkv)
|
|
||||||
h = self.proj_out(h)
|
|
||||||
return (x + h).reshape(b, c, *spatial)
|
|
||||||
|
|
||||||
|
|
||||||
def count_flops_attn(model, _x, y):
|
|
||||||
"""
|
|
||||||
A counter for the `thop` package to count the operations in an
|
|
||||||
attention operation.
|
|
||||||
Meant to be used like:
|
|
||||||
macs, params = thop.profile(
|
|
||||||
model,
|
|
||||||
inputs=(inputs, timestamps),
|
|
||||||
custom_ops={QKVAttention: QKVAttention.count_flops},
|
|
||||||
)
|
|
||||||
"""
|
|
||||||
b, c, *spatial = y[0].shape
|
|
||||||
num_spatial = int(np.prod(spatial))
|
|
||||||
# We perform two matmuls with the same number of ops.
|
|
||||||
# The first computes the weight matrix, the second computes
|
|
||||||
# the combination of the value vectors.
|
|
||||||
matmul_ops = 2 * b * (num_spatial ** 2) * c
|
|
||||||
model.total_ops += th.DoubleTensor([matmul_ops])
|
|
||||||
|
|
||||||
|
|
||||||
class QKVAttentionLegacy(nn.Module):
|
|
||||||
"""
|
|
||||||
A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, n_heads):
|
|
||||||
super().__init__()
|
|
||||||
self.n_heads = n_heads
|
|
||||||
|
|
||||||
def forward(self, qkv):
|
|
||||||
"""
|
|
||||||
Apply QKV attention.
|
|
||||||
:param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
|
|
||||||
:return: an [N x (H * C) x T] tensor after attention.
|
|
||||||
"""
|
|
||||||
bs, width, length = qkv.shape
|
|
||||||
assert width % (3 * self.n_heads) == 0
|
|
||||||
ch = width // (3 * self.n_heads)
|
|
||||||
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
|
|
||||||
scale = 1 / math.sqrt(math.sqrt(ch))
|
|
||||||
weight = th.einsum(
|
|
||||||
"bct,bcs->bts", q * scale, k * scale
|
|
||||||
) # More stable with f16 than dividing afterwards
|
|
||||||
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
|
|
||||||
a = th.einsum("bts,bcs->bct", weight, v)
|
|
||||||
return a.reshape(bs, -1, length)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def count_flops(model, _x, y):
|
|
||||||
return count_flops_attn(model, _x, y)
|
|
||||||
|
|
||||||
|
|
||||||
class QKVAttention(nn.Module):
|
|
||||||
"""
|
|
||||||
A module which performs QKV attention and splits in a different order.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, n_heads):
|
|
||||||
super().__init__()
|
|
||||||
self.n_heads = n_heads
|
|
||||||
|
|
||||||
def forward(self, qkv):
|
|
||||||
"""
|
|
||||||
Apply QKV attention.
|
|
||||||
:param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
|
|
||||||
:return: an [N x (H * C) x T] tensor after attention.
|
|
||||||
"""
|
|
||||||
bs, width, length = qkv.shape
|
|
||||||
assert width % (3 * self.n_heads) == 0
|
|
||||||
ch = width // (3 * self.n_heads)
|
|
||||||
q, k, v = qkv.chunk(3, dim=1)
|
|
||||||
scale = 1 / math.sqrt(math.sqrt(ch))
|
|
||||||
weight = th.einsum(
|
|
||||||
"bct,bcs->bts",
|
|
||||||
(q * scale).view(bs * self.n_heads, ch, length),
|
|
||||||
(k * scale).view(bs * self.n_heads, ch, length),
|
|
||||||
) # More stable with f16 than dividing afterwards
|
|
||||||
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
|
|
||||||
a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
|
|
||||||
return a.reshape(bs, -1, length)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def count_flops(model, _x, y):
|
|
||||||
return count_flops_attn(model, _x, y)
|
|
||||||
|
|
||||||
|
|
||||||
class Timestep(nn.Module):
|
class Timestep(nn.Module):
|
||||||
def __init__(self, dim):
|
def __init__(self, dim):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
@ -503,8 +315,11 @@ class UNetModel(nn.Module):
|
|||||||
use_linear_in_transformer=False,
|
use_linear_in_transformer=False,
|
||||||
adm_in_channels=None,
|
adm_in_channels=None,
|
||||||
transformer_depth_middle=None,
|
transformer_depth_middle=None,
|
||||||
|
device=None,
|
||||||
|
operations=comfy.ops,
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
|
||||||
if use_spatial_transformer:
|
if use_spatial_transformer:
|
||||||
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
||||||
|
|
||||||
@ -564,9 +379,9 @@ class UNetModel(nn.Module):
|
|||||||
|
|
||||||
time_embed_dim = model_channels * 4
|
time_embed_dim = model_channels * 4
|
||||||
self.time_embed = nn.Sequential(
|
self.time_embed = nn.Sequential(
|
||||||
linear(model_channels, time_embed_dim, dtype=self.dtype),
|
operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
linear(time_embed_dim, time_embed_dim, dtype=self.dtype),
|
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.num_classes is not None:
|
if self.num_classes is not None:
|
||||||
@ -579,9 +394,9 @@ class UNetModel(nn.Module):
|
|||||||
assert adm_in_channels is not None
|
assert adm_in_channels is not None
|
||||||
self.label_emb = nn.Sequential(
|
self.label_emb = nn.Sequential(
|
||||||
nn.Sequential(
|
nn.Sequential(
|
||||||
linear(adm_in_channels, time_embed_dim, dtype=self.dtype),
|
operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
linear(time_embed_dim, time_embed_dim, dtype=self.dtype),
|
operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@ -590,7 +405,7 @@ class UNetModel(nn.Module):
|
|||||||
self.input_blocks = nn.ModuleList(
|
self.input_blocks = nn.ModuleList(
|
||||||
[
|
[
|
||||||
TimestepEmbedSequential(
|
TimestepEmbedSequential(
|
||||||
conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype)
|
operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@ -609,7 +424,9 @@ class UNetModel(nn.Module):
|
|||||||
dims=dims,
|
dims=dims,
|
||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
dtype=self.dtype
|
dtype=self.dtype,
|
||||||
|
device=device,
|
||||||
|
operations=operations,
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
ch = mult * model_channels
|
ch = mult * model_channels
|
||||||
@ -628,17 +445,10 @@ class UNetModel(nn.Module):
|
|||||||
disabled_sa = False
|
disabled_sa = False
|
||||||
|
|
||||||
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
||||||
layers.append(
|
layers.append(SpatialTransformer(
|
||||||
AttentionBlock(
|
|
||||||
ch,
|
|
||||||
use_checkpoint=use_checkpoint,
|
|
||||||
num_heads=num_heads,
|
|
||||||
num_head_channels=dim_head,
|
|
||||||
use_new_attention_order=use_new_attention_order,
|
|
||||||
) if not use_spatial_transformer else SpatialTransformer(
|
|
||||||
ch, num_heads, dim_head, depth=transformer_depth[level], context_dim=context_dim,
|
ch, num_heads, dim_head, depth=transformer_depth[level], context_dim=context_dim,
|
||||||
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
||||||
use_checkpoint=use_checkpoint, dtype=self.dtype
|
use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
||||||
@ -657,11 +467,13 @@ class UNetModel(nn.Module):
|
|||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
down=True,
|
down=True,
|
||||||
dtype=self.dtype
|
dtype=self.dtype,
|
||||||
|
device=device,
|
||||||
|
operations=operations
|
||||||
)
|
)
|
||||||
if resblock_updown
|
if resblock_updown
|
||||||
else Downsample(
|
else Downsample(
|
||||||
ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype
|
ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@ -686,18 +498,14 @@ class UNetModel(nn.Module):
|
|||||||
dims=dims,
|
dims=dims,
|
||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
dtype=self.dtype
|
dtype=self.dtype,
|
||||||
|
device=device,
|
||||||
|
operations=operations
|
||||||
),
|
),
|
||||||
AttentionBlock(
|
SpatialTransformer( # always uses a self-attn
|
||||||
ch,
|
|
||||||
use_checkpoint=use_checkpoint,
|
|
||||||
num_heads=num_heads,
|
|
||||||
num_head_channels=dim_head,
|
|
||||||
use_new_attention_order=use_new_attention_order,
|
|
||||||
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
|
|
||||||
ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
|
ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
|
||||||
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
||||||
use_checkpoint=use_checkpoint, dtype=self.dtype
|
use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
|
||||||
),
|
),
|
||||||
ResBlock(
|
ResBlock(
|
||||||
ch,
|
ch,
|
||||||
@ -706,7 +514,9 @@ class UNetModel(nn.Module):
|
|||||||
dims=dims,
|
dims=dims,
|
||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
dtype=self.dtype
|
dtype=self.dtype,
|
||||||
|
device=device,
|
||||||
|
operations=operations
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
self._feature_size += ch
|
self._feature_size += ch
|
||||||
@ -724,7 +534,9 @@ class UNetModel(nn.Module):
|
|||||||
dims=dims,
|
dims=dims,
|
||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
dtype=self.dtype
|
dtype=self.dtype,
|
||||||
|
device=device,
|
||||||
|
operations=operations
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
ch = model_channels * mult
|
ch = model_channels * mult
|
||||||
@ -744,16 +556,10 @@ class UNetModel(nn.Module):
|
|||||||
|
|
||||||
if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
|
if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
|
||||||
layers.append(
|
layers.append(
|
||||||
AttentionBlock(
|
SpatialTransformer(
|
||||||
ch,
|
|
||||||
use_checkpoint=use_checkpoint,
|
|
||||||
num_heads=num_heads_upsample,
|
|
||||||
num_head_channels=dim_head,
|
|
||||||
use_new_attention_order=use_new_attention_order,
|
|
||||||
) if not use_spatial_transformer else SpatialTransformer(
|
|
||||||
ch, num_heads, dim_head, depth=transformer_depth[level], context_dim=context_dim,
|
ch, num_heads, dim_head, depth=transformer_depth[level], context_dim=context_dim,
|
||||||
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
||||||
use_checkpoint=use_checkpoint, dtype=self.dtype
|
use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if level and i == self.num_res_blocks[level]:
|
if level and i == self.num_res_blocks[level]:
|
||||||
@ -768,43 +574,29 @@ class UNetModel(nn.Module):
|
|||||||
use_checkpoint=use_checkpoint,
|
use_checkpoint=use_checkpoint,
|
||||||
use_scale_shift_norm=use_scale_shift_norm,
|
use_scale_shift_norm=use_scale_shift_norm,
|
||||||
up=True,
|
up=True,
|
||||||
dtype=self.dtype
|
dtype=self.dtype,
|
||||||
|
device=device,
|
||||||
|
operations=operations
|
||||||
)
|
)
|
||||||
if resblock_updown
|
if resblock_updown
|
||||||
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype)
|
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations)
|
||||||
)
|
)
|
||||||
ds //= 2
|
ds //= 2
|
||||||
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
self.output_blocks.append(TimestepEmbedSequential(*layers))
|
||||||
self._feature_size += ch
|
self._feature_size += ch
|
||||||
|
|
||||||
self.out = nn.Sequential(
|
self.out = nn.Sequential(
|
||||||
normalization(ch, dtype=self.dtype),
|
nn.GroupNorm(32, ch, dtype=self.dtype, device=device),
|
||||||
nn.SiLU(),
|
nn.SiLU(),
|
||||||
zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1, dtype=self.dtype)),
|
zero_module(operations.conv_nd(dims, model_channels, out_channels, 3, padding=1, dtype=self.dtype, device=device)),
|
||||||
)
|
)
|
||||||
if self.predict_codebook_ids:
|
if self.predict_codebook_ids:
|
||||||
self.id_predictor = nn.Sequential(
|
self.id_predictor = nn.Sequential(
|
||||||
normalization(ch),
|
nn.GroupNorm(32, ch, dtype=self.dtype, device=device),
|
||||||
conv_nd(dims, model_channels, n_embed, 1),
|
operations.conv_nd(dims, model_channels, n_embed, 1, dtype=self.dtype, device=device),
|
||||||
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
|
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
|
||||||
)
|
)
|
||||||
|
|
||||||
def convert_to_fp16(self):
|
|
||||||
"""
|
|
||||||
Convert the torso of the model to float16.
|
|
||||||
"""
|
|
||||||
self.input_blocks.apply(convert_module_to_f16)
|
|
||||||
self.middle_block.apply(convert_module_to_f16)
|
|
||||||
self.output_blocks.apply(convert_module_to_f16)
|
|
||||||
|
|
||||||
def convert_to_fp32(self):
|
|
||||||
"""
|
|
||||||
Convert the torso of the model to float32.
|
|
||||||
"""
|
|
||||||
self.input_blocks.apply(convert_module_to_f32)
|
|
||||||
self.middle_block.apply(convert_module_to_f32)
|
|
||||||
self.output_blocks.apply(convert_module_to_f32)
|
|
||||||
|
|
||||||
def forward(self, x, timesteps=None, context=None, y=None, control=None, transformer_options={}, **kwargs):
|
def forward(self, x, timesteps=None, context=None, y=None, control=None, transformer_options={}, **kwargs):
|
||||||
"""
|
"""
|
||||||
Apply the model to an input batch.
|
Apply the model to an input batch.
|
||||||
@ -821,7 +613,7 @@ class UNetModel(nn.Module):
|
|||||||
self.num_classes is not None
|
self.num_classes is not None
|
||||||
), "must specify y if and only if the model is class-conditional"
|
), "must specify y if and only if the model is class-conditional"
|
||||||
hs = []
|
hs = []
|
||||||
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(self.dtype)
|
||||||
emb = self.time_embed(t_emb)
|
emb = self.time_embed(t_emb)
|
||||||
|
|
||||||
if self.num_classes is not None:
|
if self.num_classes is not None:
|
||||||
@ -840,7 +632,9 @@ class UNetModel(nn.Module):
|
|||||||
transformer_options["block"] = ("middle", 0)
|
transformer_options["block"] = ("middle", 0)
|
||||||
h = forward_timestep_embed(self.middle_block, h, emb, context, transformer_options)
|
h = forward_timestep_embed(self.middle_block, h, emb, context, transformer_options)
|
||||||
if control is not None and 'middle' in control and len(control['middle']) > 0:
|
if control is not None and 'middle' in control and len(control['middle']) > 0:
|
||||||
h += control['middle'].pop()
|
ctrl = control['middle'].pop()
|
||||||
|
if ctrl is not None:
|
||||||
|
h += ctrl
|
||||||
|
|
||||||
for id, module in enumerate(self.output_blocks):
|
for id, module in enumerate(self.output_blocks):
|
||||||
transformer_options["block"] = ("output", id)
|
transformer_options["block"] = ("output", id)
|
||||||
|
|||||||
@ -84,7 +84,7 @@ def _summarize_chunk(
|
|||||||
max_score, _ = torch.max(attn_weights, -1, keepdim=True)
|
max_score, _ = torch.max(attn_weights, -1, keepdim=True)
|
||||||
max_score = max_score.detach()
|
max_score = max_score.detach()
|
||||||
torch.exp(attn_weights - max_score, out=attn_weights)
|
torch.exp(attn_weights - max_score, out=attn_weights)
|
||||||
exp_weights = attn_weights
|
exp_weights = attn_weights.to(value.dtype)
|
||||||
exp_values = torch.bmm(exp_weights, value)
|
exp_values = torch.bmm(exp_weights, value)
|
||||||
max_score = max_score.squeeze(-1)
|
max_score = max_score.squeeze(-1)
|
||||||
return AttnChunk(exp_values, exp_weights.sum(dim=-1), max_score)
|
return AttnChunk(exp_values, exp_weights.sum(dim=-1), max_score)
|
||||||
@ -166,7 +166,7 @@ def _get_attention_scores_no_kv_chunking(
|
|||||||
attn_scores /= summed
|
attn_scores /= summed
|
||||||
attn_probs = attn_scores
|
attn_probs = attn_scores
|
||||||
|
|
||||||
hidden_states_slice = torch.bmm(attn_probs, value)
|
hidden_states_slice = torch.bmm(attn_probs.to(value.dtype), value)
|
||||||
return hidden_states_slice
|
return hidden_states_slice
|
||||||
|
|
||||||
class ScannedChunk(NamedTuple):
|
class ScannedChunk(NamedTuple):
|
||||||
|
|||||||
199
comfy/lora.py
Normal file
199
comfy/lora.py
Normal file
@ -0,0 +1,199 @@
|
|||||||
|
import comfy.utils
|
||||||
|
|
||||||
|
LORA_CLIP_MAP = {
|
||||||
|
"mlp.fc1": "mlp_fc1",
|
||||||
|
"mlp.fc2": "mlp_fc2",
|
||||||
|
"self_attn.k_proj": "self_attn_k_proj",
|
||||||
|
"self_attn.q_proj": "self_attn_q_proj",
|
||||||
|
"self_attn.v_proj": "self_attn_v_proj",
|
||||||
|
"self_attn.out_proj": "self_attn_out_proj",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def load_lora(lora, to_load):
|
||||||
|
patch_dict = {}
|
||||||
|
loaded_keys = set()
|
||||||
|
for x in to_load:
|
||||||
|
alpha_name = "{}.alpha".format(x)
|
||||||
|
alpha = None
|
||||||
|
if alpha_name in lora.keys():
|
||||||
|
alpha = lora[alpha_name].item()
|
||||||
|
loaded_keys.add(alpha_name)
|
||||||
|
|
||||||
|
regular_lora = "{}.lora_up.weight".format(x)
|
||||||
|
diffusers_lora = "{}_lora.up.weight".format(x)
|
||||||
|
transformers_lora = "{}.lora_linear_layer.up.weight".format(x)
|
||||||
|
A_name = None
|
||||||
|
|
||||||
|
if regular_lora in lora.keys():
|
||||||
|
A_name = regular_lora
|
||||||
|
B_name = "{}.lora_down.weight".format(x)
|
||||||
|
mid_name = "{}.lora_mid.weight".format(x)
|
||||||
|
elif diffusers_lora in lora.keys():
|
||||||
|
A_name = diffusers_lora
|
||||||
|
B_name = "{}_lora.down.weight".format(x)
|
||||||
|
mid_name = None
|
||||||
|
elif transformers_lora in lora.keys():
|
||||||
|
A_name = transformers_lora
|
||||||
|
B_name ="{}.lora_linear_layer.down.weight".format(x)
|
||||||
|
mid_name = None
|
||||||
|
|
||||||
|
if A_name is not None:
|
||||||
|
mid = None
|
||||||
|
if mid_name is not None and mid_name in lora.keys():
|
||||||
|
mid = lora[mid_name]
|
||||||
|
loaded_keys.add(mid_name)
|
||||||
|
patch_dict[to_load[x]] = (lora[A_name], lora[B_name], alpha, mid)
|
||||||
|
loaded_keys.add(A_name)
|
||||||
|
loaded_keys.add(B_name)
|
||||||
|
|
||||||
|
|
||||||
|
######## loha
|
||||||
|
hada_w1_a_name = "{}.hada_w1_a".format(x)
|
||||||
|
hada_w1_b_name = "{}.hada_w1_b".format(x)
|
||||||
|
hada_w2_a_name = "{}.hada_w2_a".format(x)
|
||||||
|
hada_w2_b_name = "{}.hada_w2_b".format(x)
|
||||||
|
hada_t1_name = "{}.hada_t1".format(x)
|
||||||
|
hada_t2_name = "{}.hada_t2".format(x)
|
||||||
|
if hada_w1_a_name in lora.keys():
|
||||||
|
hada_t1 = None
|
||||||
|
hada_t2 = None
|
||||||
|
if hada_t1_name in lora.keys():
|
||||||
|
hada_t1 = lora[hada_t1_name]
|
||||||
|
hada_t2 = lora[hada_t2_name]
|
||||||
|
loaded_keys.add(hada_t1_name)
|
||||||
|
loaded_keys.add(hada_t2_name)
|
||||||
|
|
||||||
|
patch_dict[to_load[x]] = (lora[hada_w1_a_name], lora[hada_w1_b_name], alpha, lora[hada_w2_a_name], lora[hada_w2_b_name], hada_t1, hada_t2)
|
||||||
|
loaded_keys.add(hada_w1_a_name)
|
||||||
|
loaded_keys.add(hada_w1_b_name)
|
||||||
|
loaded_keys.add(hada_w2_a_name)
|
||||||
|
loaded_keys.add(hada_w2_b_name)
|
||||||
|
|
||||||
|
|
||||||
|
######## lokr
|
||||||
|
lokr_w1_name = "{}.lokr_w1".format(x)
|
||||||
|
lokr_w2_name = "{}.lokr_w2".format(x)
|
||||||
|
lokr_w1_a_name = "{}.lokr_w1_a".format(x)
|
||||||
|
lokr_w1_b_name = "{}.lokr_w1_b".format(x)
|
||||||
|
lokr_t2_name = "{}.lokr_t2".format(x)
|
||||||
|
lokr_w2_a_name = "{}.lokr_w2_a".format(x)
|
||||||
|
lokr_w2_b_name = "{}.lokr_w2_b".format(x)
|
||||||
|
|
||||||
|
lokr_w1 = None
|
||||||
|
if lokr_w1_name in lora.keys():
|
||||||
|
lokr_w1 = lora[lokr_w1_name]
|
||||||
|
loaded_keys.add(lokr_w1_name)
|
||||||
|
|
||||||
|
lokr_w2 = None
|
||||||
|
if lokr_w2_name in lora.keys():
|
||||||
|
lokr_w2 = lora[lokr_w2_name]
|
||||||
|
loaded_keys.add(lokr_w2_name)
|
||||||
|
|
||||||
|
lokr_w1_a = None
|
||||||
|
if lokr_w1_a_name in lora.keys():
|
||||||
|
lokr_w1_a = lora[lokr_w1_a_name]
|
||||||
|
loaded_keys.add(lokr_w1_a_name)
|
||||||
|
|
||||||
|
lokr_w1_b = None
|
||||||
|
if lokr_w1_b_name in lora.keys():
|
||||||
|
lokr_w1_b = lora[lokr_w1_b_name]
|
||||||
|
loaded_keys.add(lokr_w1_b_name)
|
||||||
|
|
||||||
|
lokr_w2_a = None
|
||||||
|
if lokr_w2_a_name in lora.keys():
|
||||||
|
lokr_w2_a = lora[lokr_w2_a_name]
|
||||||
|
loaded_keys.add(lokr_w2_a_name)
|
||||||
|
|
||||||
|
lokr_w2_b = None
|
||||||
|
if lokr_w2_b_name in lora.keys():
|
||||||
|
lokr_w2_b = lora[lokr_w2_b_name]
|
||||||
|
loaded_keys.add(lokr_w2_b_name)
|
||||||
|
|
||||||
|
lokr_t2 = None
|
||||||
|
if lokr_t2_name in lora.keys():
|
||||||
|
lokr_t2 = lora[lokr_t2_name]
|
||||||
|
loaded_keys.add(lokr_t2_name)
|
||||||
|
|
||||||
|
if (lokr_w1 is not None) or (lokr_w2 is not None) or (lokr_w1_a is not None) or (lokr_w2_a is not None):
|
||||||
|
patch_dict[to_load[x]] = (lokr_w1, lokr_w2, alpha, lokr_w1_a, lokr_w1_b, lokr_w2_a, lokr_w2_b, lokr_t2)
|
||||||
|
|
||||||
|
|
||||||
|
w_norm_name = "{}.w_norm".format(x)
|
||||||
|
b_norm_name = "{}.b_norm".format(x)
|
||||||
|
w_norm = lora.get(w_norm_name, None)
|
||||||
|
b_norm = lora.get(b_norm_name, None)
|
||||||
|
|
||||||
|
if w_norm is not None:
|
||||||
|
loaded_keys.add(w_norm_name)
|
||||||
|
patch_dict[to_load[x]] = (w_norm,)
|
||||||
|
if b_norm is not None:
|
||||||
|
loaded_keys.add(b_norm_name)
|
||||||
|
patch_dict["{}.bias".format(to_load[x][:-len(".weight")])] = (b_norm,)
|
||||||
|
|
||||||
|
for x in lora.keys():
|
||||||
|
if x not in loaded_keys:
|
||||||
|
print("lora key not loaded", x)
|
||||||
|
return patch_dict
|
||||||
|
|
||||||
|
def model_lora_keys_clip(model, key_map={}):
|
||||||
|
sdk = model.state_dict().keys()
|
||||||
|
|
||||||
|
text_model_lora_key = "lora_te_text_model_encoder_layers_{}_{}"
|
||||||
|
clip_l_present = False
|
||||||
|
for b in range(32):
|
||||||
|
for c in LORA_CLIP_MAP:
|
||||||
|
k = "transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
|
||||||
|
if k in sdk:
|
||||||
|
lora_key = text_model_lora_key.format(b, LORA_CLIP_MAP[c])
|
||||||
|
key_map[lora_key] = k
|
||||||
|
lora_key = "lora_te1_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c])
|
||||||
|
key_map[lora_key] = k
|
||||||
|
lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
|
||||||
|
key_map[lora_key] = k
|
||||||
|
|
||||||
|
k = "clip_l.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
|
||||||
|
if k in sdk:
|
||||||
|
lora_key = "lora_te1_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #SDXL base
|
||||||
|
key_map[lora_key] = k
|
||||||
|
clip_l_present = True
|
||||||
|
lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
|
||||||
|
key_map[lora_key] = k
|
||||||
|
|
||||||
|
k = "clip_g.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
|
||||||
|
if k in sdk:
|
||||||
|
if clip_l_present:
|
||||||
|
lora_key = "lora_te2_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #SDXL base
|
||||||
|
key_map[lora_key] = k
|
||||||
|
lora_key = "text_encoder_2.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
|
||||||
|
key_map[lora_key] = k
|
||||||
|
else:
|
||||||
|
lora_key = "lora_te_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #TODO: test if this is correct for SDXL-Refiner
|
||||||
|
key_map[lora_key] = k
|
||||||
|
lora_key = "text_encoder.text_model.encoder.layers.{}.{}".format(b, c) #diffusers lora
|
||||||
|
key_map[lora_key] = k
|
||||||
|
|
||||||
|
return key_map
|
||||||
|
|
||||||
|
def model_lora_keys_unet(model, key_map={}):
|
||||||
|
sdk = model.state_dict().keys()
|
||||||
|
|
||||||
|
for k in sdk:
|
||||||
|
if k.startswith("diffusion_model.") and k.endswith(".weight"):
|
||||||
|
key_lora = k[len("diffusion_model."):-len(".weight")].replace(".", "_")
|
||||||
|
key_map["lora_unet_{}".format(key_lora)] = k
|
||||||
|
|
||||||
|
diffusers_keys = comfy.utils.unet_to_diffusers(model.model_config.unet_config)
|
||||||
|
for k in diffusers_keys:
|
||||||
|
if k.endswith(".weight"):
|
||||||
|
unet_key = "diffusion_model.{}".format(diffusers_keys[k])
|
||||||
|
key_lora = k[:-len(".weight")].replace(".", "_")
|
||||||
|
key_map["lora_unet_{}".format(key_lora)] = unet_key
|
||||||
|
|
||||||
|
diffusers_lora_prefix = ["", "unet."]
|
||||||
|
for p in diffusers_lora_prefix:
|
||||||
|
diffusers_lora_key = "{}{}".format(p, k[:-len(".weight")].replace(".to_", ".processor.to_"))
|
||||||
|
if diffusers_lora_key.endswith(".to_out.0"):
|
||||||
|
diffusers_lora_key = diffusers_lora_key[:-2]
|
||||||
|
key_map[diffusers_lora_key] = unet_key
|
||||||
|
return key_map
|
||||||
@ -3,28 +3,30 @@ from comfy.ldm.modules.diffusionmodules.openaimodel import UNetModel
|
|||||||
from comfy.ldm.modules.encoders.noise_aug_modules import CLIPEmbeddingNoiseAugmentation
|
from comfy.ldm.modules.encoders.noise_aug_modules import CLIPEmbeddingNoiseAugmentation
|
||||||
from comfy.ldm.modules.diffusionmodules.util import make_beta_schedule
|
from comfy.ldm.modules.diffusionmodules.util import make_beta_schedule
|
||||||
from comfy.ldm.modules.diffusionmodules.openaimodel import Timestep
|
from comfy.ldm.modules.diffusionmodules.openaimodel import Timestep
|
||||||
|
import comfy.model_management
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
from enum import Enum
|
||||||
from . import utils
|
from . import utils
|
||||||
|
|
||||||
|
class ModelType(Enum):
|
||||||
|
EPS = 1
|
||||||
|
V_PREDICTION = 2
|
||||||
|
|
||||||
class BaseModel(torch.nn.Module):
|
class BaseModel(torch.nn.Module):
|
||||||
def __init__(self, model_config, v_prediction=False):
|
def __init__(self, model_config, model_type=ModelType.EPS, device=None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
unet_config = model_config.unet_config
|
unet_config = model_config.unet_config
|
||||||
self.latent_format = model_config.latent_format
|
self.latent_format = model_config.latent_format
|
||||||
self.model_config = model_config
|
self.model_config = model_config
|
||||||
self.register_schedule(given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=0.00085, linear_end=0.012, cosine_s=8e-3)
|
self.register_schedule(given_betas=None, beta_schedule=model_config.beta_schedule, timesteps=1000, linear_start=0.00085, linear_end=0.012, cosine_s=8e-3)
|
||||||
self.diffusion_model = UNetModel(**unet_config)
|
if not unet_config.get("disable_unet_model_creation", False):
|
||||||
self.v_prediction = v_prediction
|
self.diffusion_model = UNetModel(**unet_config, device=device)
|
||||||
if self.v_prediction:
|
self.model_type = model_type
|
||||||
self.parameterization = "v"
|
|
||||||
else:
|
|
||||||
self.parameterization = "eps"
|
|
||||||
|
|
||||||
self.adm_channels = unet_config.get("adm_in_channels", None)
|
self.adm_channels = unet_config.get("adm_in_channels", None)
|
||||||
if self.adm_channels is None:
|
if self.adm_channels is None:
|
||||||
self.adm_channels = 0
|
self.adm_channels = 0
|
||||||
print("v_prediction", v_prediction)
|
print("model_type", model_type.name)
|
||||||
print("adm", self.adm_channels)
|
print("adm", self.adm_channels)
|
||||||
|
|
||||||
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
||||||
@ -48,11 +50,17 @@ class BaseModel(torch.nn.Module):
|
|||||||
|
|
||||||
def apply_model(self, x, t, c_concat=None, c_crossattn=None, c_adm=None, control=None, transformer_options={}):
|
def apply_model(self, x, t, c_concat=None, c_crossattn=None, c_adm=None, control=None, transformer_options={}):
|
||||||
if c_concat is not None:
|
if c_concat is not None:
|
||||||
xc = torch.cat([x] + c_concat, dim=1)
|
xc = torch.cat([x] + [c_concat], dim=1)
|
||||||
else:
|
else:
|
||||||
xc = x
|
xc = x
|
||||||
context = torch.cat(c_crossattn, 1)
|
context = c_crossattn
|
||||||
return self.diffusion_model(xc, t, context=context, y=c_adm, control=control, transformer_options=transformer_options)
|
dtype = self.get_dtype()
|
||||||
|
xc = xc.to(dtype)
|
||||||
|
t = t.to(dtype)
|
||||||
|
context = context.to(dtype)
|
||||||
|
if c_adm is not None:
|
||||||
|
c_adm = c_adm.to(dtype)
|
||||||
|
return self.diffusion_model(xc, t, context=context, y=c_adm, control=control, transformer_options=transformer_options).float()
|
||||||
|
|
||||||
def get_dtype(self):
|
def get_dtype(self):
|
||||||
return self.diffusion_model.dtype
|
return self.diffusion_model.dtype
|
||||||
@ -87,63 +95,76 @@ class BaseModel(torch.nn.Module):
|
|||||||
|
|
||||||
def state_dict_for_saving(self, clip_state_dict, vae_state_dict):
|
def state_dict_for_saving(self, clip_state_dict, vae_state_dict):
|
||||||
clip_state_dict = self.model_config.process_clip_state_dict_for_saving(clip_state_dict)
|
clip_state_dict = self.model_config.process_clip_state_dict_for_saving(clip_state_dict)
|
||||||
unet_state_dict = self.diffusion_model.state_dict()
|
unet_sd = self.diffusion_model.state_dict()
|
||||||
|
unet_state_dict = {}
|
||||||
|
for k in unet_sd:
|
||||||
|
unet_state_dict[k] = comfy.model_management.resolve_lowvram_weight(unet_sd[k], self.diffusion_model, k)
|
||||||
|
|
||||||
unet_state_dict = self.model_config.process_unet_state_dict_for_saving(unet_state_dict)
|
unet_state_dict = self.model_config.process_unet_state_dict_for_saving(unet_state_dict)
|
||||||
vae_state_dict = self.model_config.process_vae_state_dict_for_saving(vae_state_dict)
|
vae_state_dict = self.model_config.process_vae_state_dict_for_saving(vae_state_dict)
|
||||||
if self.get_dtype() == torch.float16:
|
if self.get_dtype() == torch.float16:
|
||||||
clip_state_dict = utils.convert_sd_to(clip_state_dict, torch.float16)
|
clip_state_dict = utils.convert_sd_to(clip_state_dict, torch.float16)
|
||||||
vae_state_dict = utils.convert_sd_to(vae_state_dict, torch.float16)
|
vae_state_dict = utils.convert_sd_to(vae_state_dict, torch.float16)
|
||||||
|
|
||||||
|
if self.model_type == ModelType.V_PREDICTION:
|
||||||
|
unet_state_dict["v_pred"] = torch.tensor([])
|
||||||
|
|
||||||
return {**unet_state_dict, **vae_state_dict, **clip_state_dict}
|
return {**unet_state_dict, **vae_state_dict, **clip_state_dict}
|
||||||
|
|
||||||
|
def set_inpaint(self):
|
||||||
|
self.concat_keys = ("mask", "masked_image")
|
||||||
|
|
||||||
|
def unclip_adm(unclip_conditioning, device, noise_augmentor, noise_augment_merge=0.0):
|
||||||
|
adm_inputs = []
|
||||||
|
weights = []
|
||||||
|
noise_aug = []
|
||||||
|
for unclip_cond in unclip_conditioning:
|
||||||
|
for adm_cond in unclip_cond["clip_vision_output"].image_embeds:
|
||||||
|
weight = unclip_cond["strength"]
|
||||||
|
noise_augment = unclip_cond["noise_augmentation"]
|
||||||
|
noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment)
|
||||||
|
c_adm, noise_level_emb = noise_augmentor(adm_cond.to(device), noise_level=torch.tensor([noise_level], device=device))
|
||||||
|
adm_out = torch.cat((c_adm, noise_level_emb), 1) * weight
|
||||||
|
weights.append(weight)
|
||||||
|
noise_aug.append(noise_augment)
|
||||||
|
adm_inputs.append(adm_out)
|
||||||
|
|
||||||
|
if len(noise_aug) > 1:
|
||||||
|
adm_out = torch.stack(adm_inputs).sum(0)
|
||||||
|
noise_augment = noise_augment_merge
|
||||||
|
noise_level = round((noise_augmentor.max_noise_level - 1) * noise_augment)
|
||||||
|
c_adm, noise_level_emb = noise_augmentor(adm_out[:, :noise_augmentor.time_embed.dim], noise_level=torch.tensor([noise_level], device=device))
|
||||||
|
adm_out = torch.cat((c_adm, noise_level_emb), 1)
|
||||||
|
|
||||||
|
return adm_out
|
||||||
|
|
||||||
class SD21UNCLIP(BaseModel):
|
class SD21UNCLIP(BaseModel):
|
||||||
def __init__(self, model_config, noise_aug_config, v_prediction=True):
|
def __init__(self, model_config, noise_aug_config, model_type=ModelType.V_PREDICTION, device=None):
|
||||||
super().__init__(model_config, v_prediction)
|
super().__init__(model_config, model_type, device=device)
|
||||||
self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**noise_aug_config)
|
self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**noise_aug_config)
|
||||||
|
|
||||||
def encode_adm(self, **kwargs):
|
def encode_adm(self, **kwargs):
|
||||||
unclip_conditioning = kwargs.get("unclip_conditioning", None)
|
unclip_conditioning = kwargs.get("unclip_conditioning", None)
|
||||||
device = kwargs["device"]
|
device = kwargs["device"]
|
||||||
|
if unclip_conditioning is None:
|
||||||
if unclip_conditioning is not None:
|
return torch.zeros((1, self.adm_channels))
|
||||||
adm_inputs = []
|
|
||||||
weights = []
|
|
||||||
noise_aug = []
|
|
||||||
for unclip_cond in unclip_conditioning:
|
|
||||||
adm_cond = unclip_cond["clip_vision_output"].image_embeds
|
|
||||||
weight = unclip_cond["strength"]
|
|
||||||
noise_augment = unclip_cond["noise_augmentation"]
|
|
||||||
noise_level = round((self.noise_augmentor.max_noise_level - 1) * noise_augment)
|
|
||||||
c_adm, noise_level_emb = self.noise_augmentor(adm_cond.to(device), noise_level=torch.tensor([noise_level], device=device))
|
|
||||||
adm_out = torch.cat((c_adm, noise_level_emb), 1) * weight
|
|
||||||
weights.append(weight)
|
|
||||||
noise_aug.append(noise_augment)
|
|
||||||
adm_inputs.append(adm_out)
|
|
||||||
|
|
||||||
if len(noise_aug) > 1:
|
|
||||||
adm_out = torch.stack(adm_inputs).sum(0)
|
|
||||||
#TODO: add a way to control this
|
|
||||||
noise_augment = 0.05
|
|
||||||
noise_level = round((self.noise_augmentor.max_noise_level - 1) * noise_augment)
|
|
||||||
c_adm, noise_level_emb = self.noise_augmentor(adm_out[:, :self.noise_augmentor.time_embed.dim], noise_level=torch.tensor([noise_level], device=device))
|
|
||||||
adm_out = torch.cat((c_adm, noise_level_emb), 1)
|
|
||||||
else:
|
else:
|
||||||
adm_out = torch.zeros((1, self.adm_channels))
|
return unclip_adm(unclip_conditioning, device, self.noise_augmentor, kwargs.get("unclip_noise_augment_merge", 0.05))
|
||||||
|
|
||||||
return adm_out
|
def sdxl_pooled(args, noise_augmentor):
|
||||||
|
if "unclip_conditioning" in args:
|
||||||
class SDInpaint(BaseModel):
|
return unclip_adm(args.get("unclip_conditioning", None), args["device"], noise_augmentor)[:,:1280]
|
||||||
def __init__(self, model_config, v_prediction=False):
|
else:
|
||||||
super().__init__(model_config, v_prediction)
|
return args["pooled_output"]
|
||||||
self.concat_keys = ("mask", "masked_image")
|
|
||||||
|
|
||||||
class SDXLRefiner(BaseModel):
|
class SDXLRefiner(BaseModel):
|
||||||
def __init__(self, model_config, v_prediction=False):
|
def __init__(self, model_config, model_type=ModelType.EPS, device=None):
|
||||||
super().__init__(model_config, v_prediction)
|
super().__init__(model_config, model_type, device=device)
|
||||||
self.embedder = Timestep(256)
|
self.embedder = Timestep(256)
|
||||||
|
self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**{"noise_schedule_config": {"timesteps": 1000, "beta_schedule": "squaredcos_cap_v2"}, "timestep_dim": 1280})
|
||||||
|
|
||||||
def encode_adm(self, **kwargs):
|
def encode_adm(self, **kwargs):
|
||||||
clip_pooled = kwargs["pooled_output"]
|
clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
|
||||||
width = kwargs.get("width", 768)
|
width = kwargs.get("width", 768)
|
||||||
height = kwargs.get("height", 768)
|
height = kwargs.get("height", 768)
|
||||||
crop_w = kwargs.get("crop_w", 0)
|
crop_w = kwargs.get("crop_w", 0)
|
||||||
@ -154,23 +175,23 @@ class SDXLRefiner(BaseModel):
|
|||||||
else:
|
else:
|
||||||
aesthetic_score = kwargs.get("aesthetic_score", 6)
|
aesthetic_score = kwargs.get("aesthetic_score", 6)
|
||||||
|
|
||||||
print(clip_pooled.shape, width, height, crop_w, crop_h, aesthetic_score)
|
|
||||||
out = []
|
out = []
|
||||||
out.append(self.embedder(torch.Tensor([width])))
|
|
||||||
out.append(self.embedder(torch.Tensor([height])))
|
out.append(self.embedder(torch.Tensor([height])))
|
||||||
out.append(self.embedder(torch.Tensor([crop_w])))
|
out.append(self.embedder(torch.Tensor([width])))
|
||||||
out.append(self.embedder(torch.Tensor([crop_h])))
|
out.append(self.embedder(torch.Tensor([crop_h])))
|
||||||
|
out.append(self.embedder(torch.Tensor([crop_w])))
|
||||||
out.append(self.embedder(torch.Tensor([aesthetic_score])))
|
out.append(self.embedder(torch.Tensor([aesthetic_score])))
|
||||||
flat = torch.flatten(torch.cat(out))[None, ]
|
flat = torch.flatten(torch.cat(out))[None, ]
|
||||||
return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
|
return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
|
||||||
|
|
||||||
class SDXL(BaseModel):
|
class SDXL(BaseModel):
|
||||||
def __init__(self, model_config, v_prediction=False):
|
def __init__(self, model_config, model_type=ModelType.EPS, device=None):
|
||||||
super().__init__(model_config, v_prediction)
|
super().__init__(model_config, model_type, device=device)
|
||||||
self.embedder = Timestep(256)
|
self.embedder = Timestep(256)
|
||||||
|
self.noise_augmentor = CLIPEmbeddingNoiseAugmentation(**{"noise_schedule_config": {"timesteps": 1000, "beta_schedule": "squaredcos_cap_v2"}, "timestep_dim": 1280})
|
||||||
|
|
||||||
def encode_adm(self, **kwargs):
|
def encode_adm(self, **kwargs):
|
||||||
clip_pooled = kwargs["pooled_output"]
|
clip_pooled = sdxl_pooled(kwargs, self.noise_augmentor)
|
||||||
width = kwargs.get("width", 768)
|
width = kwargs.get("width", 768)
|
||||||
height = kwargs.get("height", 768)
|
height = kwargs.get("height", 768)
|
||||||
crop_w = kwargs.get("crop_w", 0)
|
crop_w = kwargs.get("crop_w", 0)
|
||||||
@ -178,13 +199,12 @@ class SDXL(BaseModel):
|
|||||||
target_width = kwargs.get("target_width", width)
|
target_width = kwargs.get("target_width", width)
|
||||||
target_height = kwargs.get("target_height", height)
|
target_height = kwargs.get("target_height", height)
|
||||||
|
|
||||||
print(clip_pooled.shape, width, height, crop_w, crop_h, target_width, target_height)
|
|
||||||
out = []
|
out = []
|
||||||
out.append(self.embedder(torch.Tensor([width])))
|
|
||||||
out.append(self.embedder(torch.Tensor([height])))
|
out.append(self.embedder(torch.Tensor([height])))
|
||||||
out.append(self.embedder(torch.Tensor([crop_w])))
|
out.append(self.embedder(torch.Tensor([width])))
|
||||||
out.append(self.embedder(torch.Tensor([crop_h])))
|
out.append(self.embedder(torch.Tensor([crop_h])))
|
||||||
out.append(self.embedder(torch.Tensor([target_width])))
|
out.append(self.embedder(torch.Tensor([crop_w])))
|
||||||
out.append(self.embedder(torch.Tensor([target_height])))
|
out.append(self.embedder(torch.Tensor([target_height])))
|
||||||
|
out.append(self.embedder(torch.Tensor([target_width])))
|
||||||
flat = torch.flatten(torch.cat(out))[None, ]
|
flat = torch.flatten(torch.cat(out))[None, ]
|
||||||
return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
|
return torch.cat((clip_pooled.to(flat.device), flat), dim=1)
|
||||||
|
|||||||
@ -16,13 +16,11 @@ def count_blocks(state_dict_keys, prefix_string):
|
|||||||
|
|
||||||
def detect_unet_config(state_dict, key_prefix, use_fp16):
|
def detect_unet_config(state_dict, key_prefix, use_fp16):
|
||||||
state_dict_keys = list(state_dict.keys())
|
state_dict_keys = list(state_dict.keys())
|
||||||
num_res_blocks = 2
|
|
||||||
|
|
||||||
unet_config = {
|
unet_config = {
|
||||||
"use_checkpoint": False,
|
"use_checkpoint": False,
|
||||||
"image_size": 32,
|
"image_size": 32,
|
||||||
"out_channels": 4,
|
"out_channels": 4,
|
||||||
"num_res_blocks": num_res_blocks,
|
|
||||||
"use_spatial_transformer": True,
|
"use_spatial_transformer": True,
|
||||||
"legacy": False
|
"legacy": False
|
||||||
}
|
}
|
||||||
@ -110,11 +108,100 @@ def detect_unet_config(state_dict, key_prefix, use_fp16):
|
|||||||
unet_config["context_dim"] = context_dim
|
unet_config["context_dim"] = context_dim
|
||||||
return unet_config
|
return unet_config
|
||||||
|
|
||||||
|
def model_config_from_unet_config(unet_config):
|
||||||
def model_config_from_unet(state_dict, unet_key_prefix, use_fp16):
|
|
||||||
unet_config = detect_unet_config(state_dict, unet_key_prefix, use_fp16)
|
|
||||||
for model_config in supported_models.models:
|
for model_config in supported_models.models:
|
||||||
if model_config.matches(unet_config):
|
if model_config.matches(unet_config):
|
||||||
return model_config(unet_config)
|
return model_config(unet_config)
|
||||||
|
|
||||||
|
print("no match", unet_config)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def model_config_from_unet(state_dict, unet_key_prefix, use_fp16):
|
||||||
|
unet_config = detect_unet_config(state_dict, unet_key_prefix, use_fp16)
|
||||||
|
return model_config_from_unet_config(unet_config)
|
||||||
|
|
||||||
|
|
||||||
|
def unet_config_from_diffusers_unet(state_dict, use_fp16):
|
||||||
|
match = {}
|
||||||
|
attention_resolutions = []
|
||||||
|
|
||||||
|
attn_res = 1
|
||||||
|
for i in range(5):
|
||||||
|
k = "down_blocks.{}.attentions.1.transformer_blocks.0.attn2.to_k.weight".format(i)
|
||||||
|
if k in state_dict:
|
||||||
|
match["context_dim"] = state_dict[k].shape[1]
|
||||||
|
attention_resolutions.append(attn_res)
|
||||||
|
attn_res *= 2
|
||||||
|
|
||||||
|
match["attention_resolutions"] = attention_resolutions
|
||||||
|
|
||||||
|
match["model_channels"] = state_dict["conv_in.weight"].shape[0]
|
||||||
|
match["in_channels"] = state_dict["conv_in.weight"].shape[1]
|
||||||
|
match["adm_in_channels"] = None
|
||||||
|
if "class_embedding.linear_1.weight" in state_dict:
|
||||||
|
match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
|
||||||
|
elif "add_embedding.linear_1.weight" in state_dict:
|
||||||
|
match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
|
||||||
|
|
||||||
|
SDXL = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'num_classes': 'sequential', 'adm_in_channels': 2816, 'use_fp16': use_fp16, 'in_channels': 4, 'model_channels': 320,
|
||||||
|
'num_res_blocks': 2, 'attention_resolutions': [2, 4], 'transformer_depth': [0, 2, 10], 'channel_mult': [1, 2, 4],
|
||||||
|
'transformer_depth_middle': 10, 'use_linear_in_transformer': True, 'context_dim': 2048, "num_head_channels": 64}
|
||||||
|
|
||||||
|
SDXL_refiner = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'num_classes': 'sequential', 'adm_in_channels': 2560, 'use_fp16': use_fp16, 'in_channels': 4, 'model_channels': 384,
|
||||||
|
'num_res_blocks': 2, 'attention_resolutions': [2, 4], 'transformer_depth': [0, 4, 4, 0], 'channel_mult': [1, 2, 4, 4],
|
||||||
|
'transformer_depth_middle': 4, 'use_linear_in_transformer': True, 'context_dim': 1280, "num_head_channels": 64}
|
||||||
|
|
||||||
|
SD21 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'adm_in_channels': None, 'use_fp16': use_fp16, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': 2,
|
||||||
|
'attention_resolutions': [1, 2, 4], 'transformer_depth': [1, 1, 1, 0], 'channel_mult': [1, 2, 4, 4],
|
||||||
|
'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 1024, "num_head_channels": 64}
|
||||||
|
|
||||||
|
SD21_uncliph = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'num_classes': 'sequential', 'adm_in_channels': 2048, 'use_fp16': use_fp16, 'in_channels': 4, 'model_channels': 320,
|
||||||
|
'num_res_blocks': 2, 'attention_resolutions': [1, 2, 4], 'transformer_depth': [1, 1, 1, 0], 'channel_mult': [1, 2, 4, 4],
|
||||||
|
'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 1024, "num_head_channels": 64}
|
||||||
|
|
||||||
|
SD21_unclipl = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'num_classes': 'sequential', 'adm_in_channels': 1536, 'use_fp16': use_fp16, 'in_channels': 4, 'model_channels': 320,
|
||||||
|
'num_res_blocks': 2, 'attention_resolutions': [1, 2, 4], 'transformer_depth': [1, 1, 1, 0], 'channel_mult': [1, 2, 4, 4],
|
||||||
|
'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 1024}
|
||||||
|
|
||||||
|
SD15 = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'adm_in_channels': None, 'use_fp16': use_fp16, 'in_channels': 4, 'model_channels': 320, 'num_res_blocks': 2,
|
||||||
|
'attention_resolutions': [1, 2, 4], 'transformer_depth': [1, 1, 1, 0], 'channel_mult': [1, 2, 4, 4],
|
||||||
|
'transformer_depth_middle': 1, 'use_linear_in_transformer': False, 'context_dim': 768, "num_heads": 8}
|
||||||
|
|
||||||
|
SDXL_mid_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'num_classes': 'sequential', 'adm_in_channels': 2816, 'use_fp16': use_fp16, 'in_channels': 4, 'model_channels': 320,
|
||||||
|
'num_res_blocks': 2, 'attention_resolutions': [4], 'transformer_depth': [0, 0, 1], 'channel_mult': [1, 2, 4],
|
||||||
|
'transformer_depth_middle': 1, 'use_linear_in_transformer': True, 'context_dim': 2048, "num_head_channels": 64}
|
||||||
|
|
||||||
|
SDXL_small_cnet = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'num_classes': 'sequential', 'adm_in_channels': 2816, 'use_fp16': use_fp16, 'in_channels': 4, 'model_channels': 320,
|
||||||
|
'num_res_blocks': 2, 'attention_resolutions': [], 'transformer_depth': [0, 0, 0], 'channel_mult': [1, 2, 4],
|
||||||
|
'transformer_depth_middle': 0, 'use_linear_in_transformer': True, "num_head_channels": 64, 'context_dim': 1}
|
||||||
|
|
||||||
|
SDXL_diffusers_inpaint = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False,
|
||||||
|
'num_classes': 'sequential', 'adm_in_channels': 2816, 'use_fp16': use_fp16, 'in_channels': 9, 'model_channels': 320,
|
||||||
|
'num_res_blocks': 2, 'attention_resolutions': [2, 4], 'transformer_depth': [0, 2, 10], 'channel_mult': [1, 2, 4],
|
||||||
|
'transformer_depth_middle': 10, 'use_linear_in_transformer': True, 'context_dim': 2048, "num_head_channels": 64}
|
||||||
|
|
||||||
|
supported_models = [SDXL, SDXL_refiner, SD21, SD15, SD21_uncliph, SD21_unclipl, SDXL_mid_cnet, SDXL_small_cnet, SDXL_diffusers_inpaint]
|
||||||
|
|
||||||
|
for unet_config in supported_models:
|
||||||
|
matches = True
|
||||||
|
for k in match:
|
||||||
|
if match[k] != unet_config[k]:
|
||||||
|
matches = False
|
||||||
|
break
|
||||||
|
if matches:
|
||||||
|
return unet_config
|
||||||
|
return None
|
||||||
|
|
||||||
|
def model_config_from_diffusers_unet(state_dict, use_fp16):
|
||||||
|
unet_config = unet_config_from_diffusers_unet(state_dict, use_fp16)
|
||||||
|
if unet_config is not None:
|
||||||
|
return model_config_from_unet_config(unet_config)
|
||||||
return None
|
return None
|
||||||
|
|||||||
@ -1,7 +1,9 @@
|
|||||||
import psutil
|
import psutil
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from comfy.cli_args import args
|
from comfy.cli_args import args
|
||||||
|
import comfy.utils
|
||||||
import torch
|
import torch
|
||||||
|
import sys
|
||||||
|
|
||||||
class VRAMState(Enum):
|
class VRAMState(Enum):
|
||||||
DISABLED = 0 #No vram present: no need to move models to vram
|
DISABLED = 0 #No vram present: no need to move models to vram
|
||||||
@ -49,14 +51,22 @@ except:
|
|||||||
try:
|
try:
|
||||||
if torch.backends.mps.is_available():
|
if torch.backends.mps.is_available():
|
||||||
cpu_state = CPUState.MPS
|
cpu_state = CPUState.MPS
|
||||||
|
import torch.mps
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
if args.cpu:
|
if args.cpu:
|
||||||
cpu_state = CPUState.CPU
|
cpu_state = CPUState.CPU
|
||||||
|
|
||||||
def get_torch_device():
|
def is_intel_xpu():
|
||||||
|
global cpu_state
|
||||||
global xpu_available
|
global xpu_available
|
||||||
|
if cpu_state == CPUState.GPU:
|
||||||
|
if xpu_available:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_torch_device():
|
||||||
global directml_enabled
|
global directml_enabled
|
||||||
global cpu_state
|
global cpu_state
|
||||||
if directml_enabled:
|
if directml_enabled:
|
||||||
@ -67,13 +77,12 @@ def get_torch_device():
|
|||||||
if cpu_state == CPUState.CPU:
|
if cpu_state == CPUState.CPU:
|
||||||
return torch.device("cpu")
|
return torch.device("cpu")
|
||||||
else:
|
else:
|
||||||
if xpu_available:
|
if is_intel_xpu():
|
||||||
return torch.device("xpu")
|
return torch.device("xpu")
|
||||||
else:
|
else:
|
||||||
return torch.device(torch.cuda.current_device())
|
return torch.device(torch.cuda.current_device())
|
||||||
|
|
||||||
def get_total_memory(dev=None, torch_total_too=False):
|
def get_total_memory(dev=None, torch_total_too=False):
|
||||||
global xpu_available
|
|
||||||
global directml_enabled
|
global directml_enabled
|
||||||
if dev is None:
|
if dev is None:
|
||||||
dev = get_torch_device()
|
dev = get_torch_device()
|
||||||
@ -85,9 +94,11 @@ def get_total_memory(dev=None, torch_total_too=False):
|
|||||||
if directml_enabled:
|
if directml_enabled:
|
||||||
mem_total = 1024 * 1024 * 1024 #TODO
|
mem_total = 1024 * 1024 * 1024 #TODO
|
||||||
mem_total_torch = mem_total
|
mem_total_torch = mem_total
|
||||||
elif xpu_available:
|
elif is_intel_xpu():
|
||||||
|
stats = torch.xpu.memory_stats(dev)
|
||||||
|
mem_reserved = stats['reserved_bytes.all.current']
|
||||||
mem_total = torch.xpu.get_device_properties(dev).total_memory
|
mem_total = torch.xpu.get_device_properties(dev).total_memory
|
||||||
mem_total_torch = mem_total
|
mem_total_torch = mem_reserved
|
||||||
else:
|
else:
|
||||||
stats = torch.cuda.memory_stats(dev)
|
stats = torch.cuda.memory_stats(dev)
|
||||||
mem_reserved = stats['reserved_bytes.all.current']
|
mem_reserved = stats['reserved_bytes.all.current']
|
||||||
@ -107,9 +118,6 @@ if not args.normalvram and not args.cpu:
|
|||||||
if lowvram_available and total_vram <= 4096:
|
if lowvram_available and total_vram <= 4096:
|
||||||
print("Trying to enable lowvram mode because your GPU seems to have 4GB or less. If you don't want this use: --normalvram")
|
print("Trying to enable lowvram mode because your GPU seems to have 4GB or less. If you don't want this use: --normalvram")
|
||||||
set_vram_to = VRAMState.LOW_VRAM
|
set_vram_to = VRAMState.LOW_VRAM
|
||||||
elif total_vram > total_ram * 1.1 and total_vram > 14336:
|
|
||||||
print("Enabling highvram mode because your GPU has more vram than your computer has ram. If you don't want this use: --normalvram")
|
|
||||||
vram_state = VRAMState.HIGH_VRAM
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
OOM_EXCEPTION = torch.cuda.OutOfMemoryError
|
OOM_EXCEPTION = torch.cuda.OutOfMemoryError
|
||||||
@ -144,17 +152,32 @@ def is_nvidia():
|
|||||||
if cpu_state == CPUState.GPU:
|
if cpu_state == CPUState.GPU:
|
||||||
if torch.version.cuda:
|
if torch.version.cuda:
|
||||||
return True
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
ENABLE_PYTORCH_ATTENTION = args.use_pytorch_cross_attention
|
ENABLE_PYTORCH_ATTENTION = args.use_pytorch_cross_attention
|
||||||
|
VAE_DTYPE = torch.float32
|
||||||
|
|
||||||
if ENABLE_PYTORCH_ATTENTION == False and XFORMERS_IS_AVAILABLE == False and args.use_split_cross_attention == False and args.use_quad_cross_attention == False:
|
try:
|
||||||
try:
|
if is_nvidia():
|
||||||
if is_nvidia():
|
torch_version = torch.version.__version__
|
||||||
torch_version = torch.version.__version__
|
if int(torch_version[0]) >= 2:
|
||||||
if int(torch_version[0]) >= 2:
|
if ENABLE_PYTORCH_ATTENTION == False and XFORMERS_IS_AVAILABLE == False and args.use_split_cross_attention == False and args.use_quad_cross_attention == False:
|
||||||
ENABLE_PYTORCH_ATTENTION = True
|
ENABLE_PYTORCH_ATTENTION = True
|
||||||
except:
|
if torch.cuda.is_bf16_supported():
|
||||||
pass
|
VAE_DTYPE = torch.bfloat16
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if is_intel_xpu():
|
||||||
|
VAE_DTYPE = torch.bfloat16
|
||||||
|
|
||||||
|
if args.fp16_vae:
|
||||||
|
VAE_DTYPE = torch.float16
|
||||||
|
elif args.bf16_vae:
|
||||||
|
VAE_DTYPE = torch.bfloat16
|
||||||
|
elif args.fp32_vae:
|
||||||
|
VAE_DTYPE = torch.float32
|
||||||
|
|
||||||
|
|
||||||
if ENABLE_PYTORCH_ATTENTION:
|
if ENABLE_PYTORCH_ATTENTION:
|
||||||
torch.backends.cuda.enable_math_sdp(True)
|
torch.backends.cuda.enable_math_sdp(True)
|
||||||
@ -171,10 +194,15 @@ elif args.highvram or args.gpu_only:
|
|||||||
vram_state = VRAMState.HIGH_VRAM
|
vram_state = VRAMState.HIGH_VRAM
|
||||||
|
|
||||||
FORCE_FP32 = False
|
FORCE_FP32 = False
|
||||||
|
FORCE_FP16 = False
|
||||||
if args.force_fp32:
|
if args.force_fp32:
|
||||||
print("Forcing FP32, if this improves things please report it.")
|
print("Forcing FP32, if this improves things please report it.")
|
||||||
FORCE_FP32 = True
|
FORCE_FP32 = True
|
||||||
|
|
||||||
|
if args.force_fp16:
|
||||||
|
print("Forcing FP16.")
|
||||||
|
FORCE_FP16 = True
|
||||||
|
|
||||||
if lowvram_available:
|
if lowvram_available:
|
||||||
try:
|
try:
|
||||||
import accelerate
|
import accelerate
|
||||||
@ -195,13 +223,23 @@ if cpu_state == CPUState.MPS:
|
|||||||
|
|
||||||
print(f"Set vram state to: {vram_state.name}")
|
print(f"Set vram state to: {vram_state.name}")
|
||||||
|
|
||||||
|
DISABLE_SMART_MEMORY = args.disable_smart_memory
|
||||||
|
|
||||||
|
if DISABLE_SMART_MEMORY:
|
||||||
|
print("Disabling smart memory management")
|
||||||
|
|
||||||
def get_torch_device_name(device):
|
def get_torch_device_name(device):
|
||||||
if hasattr(device, 'type'):
|
if hasattr(device, 'type'):
|
||||||
if device.type == "cuda":
|
if device.type == "cuda":
|
||||||
return "{} {}".format(device, torch.cuda.get_device_name(device))
|
try:
|
||||||
|
allocator_backend = torch.cuda.get_allocator_backend()
|
||||||
|
except:
|
||||||
|
allocator_backend = ""
|
||||||
|
return "{} {} : {}".format(device, torch.cuda.get_device_name(device), allocator_backend)
|
||||||
else:
|
else:
|
||||||
return "{}".format(device.type)
|
return "{}".format(device.type)
|
||||||
|
elif is_intel_xpu():
|
||||||
|
return "{} {}".format(device, torch.xpu.get_device_name(device))
|
||||||
else:
|
else:
|
||||||
return "CUDA {}: {}".format(device, torch.cuda.get_device_name(device))
|
return "CUDA {}: {}".format(device, torch.cuda.get_device_name(device))
|
||||||
|
|
||||||
@ -210,125 +248,229 @@ try:
|
|||||||
except:
|
except:
|
||||||
print("Could not pick default device.")
|
print("Could not pick default device.")
|
||||||
|
|
||||||
|
print("VAE dtype:", VAE_DTYPE)
|
||||||
|
|
||||||
current_loaded_model = None
|
current_loaded_models = []
|
||||||
current_gpu_controlnets = []
|
|
||||||
|
|
||||||
model_accelerated = False
|
class LoadedModel:
|
||||||
|
def __init__(self, model):
|
||||||
|
self.model = model
|
||||||
|
self.model_accelerated = False
|
||||||
|
self.device = model.load_device
|
||||||
|
|
||||||
|
def model_memory(self):
|
||||||
|
return self.model.model_size()
|
||||||
|
|
||||||
|
def model_memory_required(self, device):
|
||||||
|
if device == self.model.current_device:
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
return self.model_memory()
|
||||||
|
|
||||||
|
def model_load(self, lowvram_model_memory=0):
|
||||||
|
patch_model_to = None
|
||||||
|
if lowvram_model_memory == 0:
|
||||||
|
patch_model_to = self.device
|
||||||
|
|
||||||
|
self.model.model_patches_to(self.device)
|
||||||
|
self.model.model_patches_to(self.model.model_dtype())
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.real_model = self.model.patch_model(device_to=patch_model_to) #TODO: do something with loras and offloading to CPU
|
||||||
|
except Exception as e:
|
||||||
|
self.model.unpatch_model(self.model.offload_device)
|
||||||
|
self.model_unload()
|
||||||
|
raise e
|
||||||
|
|
||||||
|
if lowvram_model_memory > 0:
|
||||||
|
print("loading in lowvram mode", lowvram_model_memory/(1024 * 1024))
|
||||||
|
device_map = accelerate.infer_auto_device_map(self.real_model, max_memory={0: "{}MiB".format(lowvram_model_memory // (1024 * 1024)), "cpu": "16GiB"})
|
||||||
|
accelerate.dispatch_model(self.real_model, device_map=device_map, main_device=self.device)
|
||||||
|
self.model_accelerated = True
|
||||||
|
|
||||||
|
if is_intel_xpu() and not args.disable_ipex_optimize:
|
||||||
|
self.real_model = torch.xpu.optimize(self.real_model.eval(), inplace=True, auto_kernel_selection=True, graph_mode=True)
|
||||||
|
|
||||||
|
return self.real_model
|
||||||
|
|
||||||
|
def model_unload(self):
|
||||||
|
if self.model_accelerated:
|
||||||
|
accelerate.hooks.remove_hook_from_submodules(self.real_model)
|
||||||
|
self.model_accelerated = False
|
||||||
|
|
||||||
|
self.model.unpatch_model(self.model.offload_device)
|
||||||
|
self.model.model_patches_to(self.model.offload_device)
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
return self.model is other.model
|
||||||
|
|
||||||
|
def minimum_inference_memory():
|
||||||
|
return (1024 * 1024 * 1024)
|
||||||
|
|
||||||
|
def unload_model_clones(model):
|
||||||
|
to_unload = []
|
||||||
|
for i in range(len(current_loaded_models)):
|
||||||
|
if model.is_clone(current_loaded_models[i].model):
|
||||||
|
to_unload = [i] + to_unload
|
||||||
|
|
||||||
|
for i in to_unload:
|
||||||
|
print("unload clone", i)
|
||||||
|
current_loaded_models.pop(i).model_unload()
|
||||||
|
|
||||||
|
def free_memory(memory_required, device, keep_loaded=[]):
|
||||||
|
unloaded_model = False
|
||||||
|
for i in range(len(current_loaded_models) -1, -1, -1):
|
||||||
|
if not DISABLE_SMART_MEMORY:
|
||||||
|
if get_free_memory(device) > memory_required:
|
||||||
|
break
|
||||||
|
shift_model = current_loaded_models[i]
|
||||||
|
if shift_model.device == device:
|
||||||
|
if shift_model not in keep_loaded:
|
||||||
|
m = current_loaded_models.pop(i)
|
||||||
|
m.model_unload()
|
||||||
|
del m
|
||||||
|
unloaded_model = True
|
||||||
|
|
||||||
|
if unloaded_model:
|
||||||
|
soft_empty_cache()
|
||||||
|
|
||||||
|
|
||||||
def unload_model():
|
def load_models_gpu(models, memory_required=0):
|
||||||
global current_loaded_model
|
|
||||||
global model_accelerated
|
|
||||||
global current_gpu_controlnets
|
|
||||||
global vram_state
|
global vram_state
|
||||||
|
|
||||||
if current_loaded_model is not None:
|
inference_memory = minimum_inference_memory()
|
||||||
if model_accelerated:
|
extra_mem = max(inference_memory, memory_required)
|
||||||
accelerate.hooks.remove_hook_from_submodules(current_loaded_model.model)
|
|
||||||
model_accelerated = False
|
|
||||||
|
|
||||||
#never unload models from GPU on high vram
|
models_to_load = []
|
||||||
if vram_state != VRAMState.HIGH_VRAM:
|
models_already_loaded = []
|
||||||
current_loaded_model.model.cpu()
|
for x in models:
|
||||||
current_loaded_model.model_patches_to("cpu")
|
loaded_model = LoadedModel(x)
|
||||||
current_loaded_model.unpatch_model()
|
|
||||||
current_loaded_model = None
|
|
||||||
|
|
||||||
if vram_state != VRAMState.HIGH_VRAM:
|
if loaded_model in current_loaded_models:
|
||||||
if len(current_gpu_controlnets) > 0:
|
index = current_loaded_models.index(loaded_model)
|
||||||
for n in current_gpu_controlnets:
|
current_loaded_models.insert(0, current_loaded_models.pop(index))
|
||||||
n.cpu()
|
models_already_loaded.append(loaded_model)
|
||||||
current_gpu_controlnets = []
|
else:
|
||||||
|
models_to_load.append(loaded_model)
|
||||||
|
|
||||||
|
if len(models_to_load) == 0:
|
||||||
|
devs = set(map(lambda a: a.device, models_already_loaded))
|
||||||
|
for d in devs:
|
||||||
|
if d != torch.device("cpu"):
|
||||||
|
free_memory(extra_mem, d, models_already_loaded)
|
||||||
|
return
|
||||||
|
|
||||||
|
print("loading new")
|
||||||
|
|
||||||
|
total_memory_required = {}
|
||||||
|
for loaded_model in models_to_load:
|
||||||
|
unload_model_clones(loaded_model.model)
|
||||||
|
total_memory_required[loaded_model.device] = total_memory_required.get(loaded_model.device, 0) + loaded_model.model_memory_required(loaded_model.device)
|
||||||
|
|
||||||
|
for device in total_memory_required:
|
||||||
|
if device != torch.device("cpu"):
|
||||||
|
free_memory(total_memory_required[device] * 1.3 + extra_mem, device, models_already_loaded)
|
||||||
|
|
||||||
|
for loaded_model in models_to_load:
|
||||||
|
model = loaded_model.model
|
||||||
|
torch_dev = model.load_device
|
||||||
|
if is_device_cpu(torch_dev):
|
||||||
|
vram_set_state = VRAMState.DISABLED
|
||||||
|
else:
|
||||||
|
vram_set_state = vram_state
|
||||||
|
lowvram_model_memory = 0
|
||||||
|
if lowvram_available and (vram_set_state == VRAMState.LOW_VRAM or vram_set_state == VRAMState.NORMAL_VRAM):
|
||||||
|
model_size = loaded_model.model_memory_required(torch_dev)
|
||||||
|
current_free_mem = get_free_memory(torch_dev)
|
||||||
|
lowvram_model_memory = int(max(256 * (1024 * 1024), (current_free_mem - 1024 * (1024 * 1024)) / 1.3 ))
|
||||||
|
if model_size > (current_free_mem - inference_memory): #only switch to lowvram if really necessary
|
||||||
|
vram_set_state = VRAMState.LOW_VRAM
|
||||||
|
else:
|
||||||
|
lowvram_model_memory = 0
|
||||||
|
|
||||||
|
if vram_set_state == VRAMState.NO_VRAM:
|
||||||
|
lowvram_model_memory = 256 * 1024 * 1024
|
||||||
|
|
||||||
|
cur_loaded_model = loaded_model.model_load(lowvram_model_memory)
|
||||||
|
current_loaded_models.insert(0, loaded_model)
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
def load_model_gpu(model):
|
def load_model_gpu(model):
|
||||||
global current_loaded_model
|
return load_models_gpu([model])
|
||||||
global vram_state
|
|
||||||
global model_accelerated
|
|
||||||
|
|
||||||
if model is current_loaded_model:
|
def cleanup_models():
|
||||||
return
|
to_delete = []
|
||||||
unload_model()
|
for i in range(len(current_loaded_models)):
|
||||||
try:
|
print(sys.getrefcount(current_loaded_models[i].model))
|
||||||
real_model = model.patch_model()
|
if sys.getrefcount(current_loaded_models[i].model) <= 2:
|
||||||
except Exception as e:
|
to_delete = [i] + to_delete
|
||||||
model.unpatch_model()
|
|
||||||
raise e
|
|
||||||
|
|
||||||
torch_dev = get_torch_device()
|
for i in to_delete:
|
||||||
model.model_patches_to(torch_dev)
|
x = current_loaded_models.pop(i)
|
||||||
|
x.model_unload()
|
||||||
|
del x
|
||||||
|
|
||||||
vram_set_state = vram_state
|
def dtype_size(dtype):
|
||||||
if lowvram_available and (vram_set_state == VRAMState.LOW_VRAM or vram_set_state == VRAMState.NORMAL_VRAM):
|
dtype_size = 4
|
||||||
model_size = model.model_size()
|
if dtype == torch.float16 or dtype == torch.bfloat16:
|
||||||
current_free_mem = get_free_memory(torch_dev)
|
dtype_size = 2
|
||||||
lowvram_model_memory = int(max(256 * (1024 * 1024), (current_free_mem - 1024 * (1024 * 1024)) / 1.3 ))
|
return dtype_size
|
||||||
if model_size > (current_free_mem - (512 * 1024 * 1024)): #only switch to lowvram if really necessary
|
|
||||||
vram_set_state = VRAMState.LOW_VRAM
|
|
||||||
|
|
||||||
current_loaded_model = model
|
def unet_offload_device():
|
||||||
|
if vram_state == VRAMState.HIGH_VRAM:
|
||||||
if vram_set_state == VRAMState.DISABLED:
|
return get_torch_device()
|
||||||
pass
|
|
||||||
elif vram_set_state == VRAMState.NORMAL_VRAM or vram_set_state == VRAMState.HIGH_VRAM or vram_set_state == VRAMState.SHARED:
|
|
||||||
model_accelerated = False
|
|
||||||
real_model.to(get_torch_device())
|
|
||||||
else:
|
else:
|
||||||
if vram_set_state == VRAMState.NO_VRAM:
|
return torch.device("cpu")
|
||||||
device_map = accelerate.infer_auto_device_map(real_model, max_memory={0: "256MiB", "cpu": "16GiB"})
|
|
||||||
elif vram_set_state == VRAMState.LOW_VRAM:
|
|
||||||
device_map = accelerate.infer_auto_device_map(real_model, max_memory={0: "{}MiB".format(lowvram_model_memory // (1024 * 1024)), "cpu": "16GiB"})
|
|
||||||
|
|
||||||
accelerate.dispatch_model(real_model, device_map=device_map, main_device=get_torch_device())
|
def unet_inital_load_device(parameters, dtype):
|
||||||
model_accelerated = True
|
torch_dev = get_torch_device()
|
||||||
return current_loaded_model
|
if vram_state == VRAMState.HIGH_VRAM:
|
||||||
|
return torch_dev
|
||||||
|
|
||||||
def load_controlnet_gpu(control_models):
|
cpu_dev = torch.device("cpu")
|
||||||
global current_gpu_controlnets
|
if DISABLE_SMART_MEMORY:
|
||||||
global vram_state
|
return cpu_dev
|
||||||
if vram_state == VRAMState.DISABLED:
|
|
||||||
return
|
|
||||||
|
|
||||||
if vram_state == VRAMState.LOW_VRAM or vram_state == VRAMState.NO_VRAM:
|
model_size = dtype_size(dtype) * parameters
|
||||||
for m in control_models:
|
|
||||||
if hasattr(m, 'set_lowvram'):
|
|
||||||
m.set_lowvram(True)
|
|
||||||
#don't load controlnets like this if low vram because they will be loaded right before running and unloaded right after
|
|
||||||
return
|
|
||||||
|
|
||||||
models = []
|
mem_dev = get_free_memory(torch_dev)
|
||||||
for m in control_models:
|
mem_cpu = get_free_memory(cpu_dev)
|
||||||
models += m.get_models()
|
if mem_dev > mem_cpu and model_size < mem_dev:
|
||||||
|
return torch_dev
|
||||||
|
else:
|
||||||
|
return cpu_dev
|
||||||
|
|
||||||
for m in current_gpu_controlnets:
|
def text_encoder_offload_device():
|
||||||
if m not in models:
|
|
||||||
m.cpu()
|
|
||||||
|
|
||||||
device = get_torch_device()
|
|
||||||
current_gpu_controlnets = []
|
|
||||||
for m in models:
|
|
||||||
current_gpu_controlnets.append(m.to(device))
|
|
||||||
|
|
||||||
|
|
||||||
def load_if_low_vram(model):
|
|
||||||
global vram_state
|
|
||||||
if vram_state == VRAMState.LOW_VRAM or vram_state == VRAMState.NO_VRAM:
|
|
||||||
return model.to(get_torch_device())
|
|
||||||
return model
|
|
||||||
|
|
||||||
def unload_if_low_vram(model):
|
|
||||||
global vram_state
|
|
||||||
if vram_state == VRAMState.LOW_VRAM or vram_state == VRAMState.NO_VRAM:
|
|
||||||
return model.cpu()
|
|
||||||
return model
|
|
||||||
|
|
||||||
def text_encoder_device():
|
|
||||||
if args.gpu_only:
|
if args.gpu_only:
|
||||||
return get_torch_device()
|
return get_torch_device()
|
||||||
else:
|
else:
|
||||||
return torch.device("cpu")
|
return torch.device("cpu")
|
||||||
|
|
||||||
|
def text_encoder_device():
|
||||||
|
if args.gpu_only:
|
||||||
|
return get_torch_device()
|
||||||
|
elif vram_state == VRAMState.HIGH_VRAM or vram_state == VRAMState.NORMAL_VRAM:
|
||||||
|
if should_use_fp16(prioritize_performance=False):
|
||||||
|
return get_torch_device()
|
||||||
|
else:
|
||||||
|
return torch.device("cpu")
|
||||||
|
else:
|
||||||
|
return torch.device("cpu")
|
||||||
|
|
||||||
|
def vae_device():
|
||||||
|
return get_torch_device()
|
||||||
|
|
||||||
|
def vae_offload_device():
|
||||||
|
if args.gpu_only:
|
||||||
|
return get_torch_device()
|
||||||
|
else:
|
||||||
|
return torch.device("cpu")
|
||||||
|
|
||||||
|
def vae_dtype():
|
||||||
|
global VAE_DTYPE
|
||||||
|
return VAE_DTYPE
|
||||||
|
|
||||||
def get_autocast_device(dev):
|
def get_autocast_device(dev):
|
||||||
if hasattr(dev, 'type'):
|
if hasattr(dev, 'type'):
|
||||||
return dev.type
|
return dev.type
|
||||||
@ -336,12 +478,11 @@ def get_autocast_device(dev):
|
|||||||
|
|
||||||
|
|
||||||
def xformers_enabled():
|
def xformers_enabled():
|
||||||
global xpu_available
|
|
||||||
global directml_enabled
|
global directml_enabled
|
||||||
global cpu_state
|
global cpu_state
|
||||||
if cpu_state != CPUState.GPU:
|
if cpu_state != CPUState.GPU:
|
||||||
return False
|
return False
|
||||||
if xpu_available:
|
if is_intel_xpu():
|
||||||
return False
|
return False
|
||||||
if directml_enabled:
|
if directml_enabled:
|
||||||
return False
|
return False
|
||||||
@ -368,7 +509,6 @@ def pytorch_attention_flash_attention():
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
def get_free_memory(dev=None, torch_free_too=False):
|
def get_free_memory(dev=None, torch_free_too=False):
|
||||||
global xpu_available
|
|
||||||
global directml_enabled
|
global directml_enabled
|
||||||
if dev is None:
|
if dev is None:
|
||||||
dev = get_torch_device()
|
dev = get_torch_device()
|
||||||
@ -380,9 +520,13 @@ def get_free_memory(dev=None, torch_free_too=False):
|
|||||||
if directml_enabled:
|
if directml_enabled:
|
||||||
mem_free_total = 1024 * 1024 * 1024 #TODO
|
mem_free_total = 1024 * 1024 * 1024 #TODO
|
||||||
mem_free_torch = mem_free_total
|
mem_free_torch = mem_free_total
|
||||||
elif xpu_available:
|
elif is_intel_xpu():
|
||||||
mem_free_total = torch.xpu.get_device_properties(dev).total_memory - torch.xpu.memory_allocated(dev)
|
stats = torch.xpu.memory_stats(dev)
|
||||||
mem_free_torch = mem_free_total
|
mem_active = stats['active_bytes.all.current']
|
||||||
|
mem_allocated = stats['allocated_bytes.all.current']
|
||||||
|
mem_reserved = stats['reserved_bytes.all.current']
|
||||||
|
mem_free_torch = mem_reserved - mem_active
|
||||||
|
mem_free_total = torch.xpu.get_device_properties(dev).total_memory - mem_allocated
|
||||||
else:
|
else:
|
||||||
stats = torch.cuda.memory_stats(dev)
|
stats = torch.cuda.memory_stats(dev)
|
||||||
mem_active = stats['active_bytes.all.current']
|
mem_active = stats['active_bytes.all.current']
|
||||||
@ -396,6 +540,13 @@ def get_free_memory(dev=None, torch_free_too=False):
|
|||||||
else:
|
else:
|
||||||
return mem_free_total
|
return mem_free_total
|
||||||
|
|
||||||
|
def batch_area_memory(area):
|
||||||
|
if xformers_enabled() or pytorch_attention_flash_attention():
|
||||||
|
#TODO: these formulas are copied from maximum_batch_area below
|
||||||
|
return (area / 20) * (1024 * 1024)
|
||||||
|
else:
|
||||||
|
return (((area * 0.6) / 0.9) + 1024) * (1024 * 1024)
|
||||||
|
|
||||||
def maximum_batch_area():
|
def maximum_batch_area():
|
||||||
global vram_state
|
global vram_state
|
||||||
if vram_state == VRAMState.NO_VRAM:
|
if vram_state == VRAMState.NO_VRAM:
|
||||||
@ -418,46 +569,94 @@ def mps_mode():
|
|||||||
global cpu_state
|
global cpu_state
|
||||||
return cpu_state == CPUState.MPS
|
return cpu_state == CPUState.MPS
|
||||||
|
|
||||||
def should_use_fp16():
|
def is_device_cpu(device):
|
||||||
global xpu_available
|
if hasattr(device, 'type'):
|
||||||
|
if (device.type == 'cpu'):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def is_device_mps(device):
|
||||||
|
if hasattr(device, 'type'):
|
||||||
|
if (device.type == 'mps'):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def should_use_fp16(device=None, model_params=0, prioritize_performance=True):
|
||||||
global directml_enabled
|
global directml_enabled
|
||||||
|
|
||||||
|
if device is not None:
|
||||||
|
if is_device_cpu(device):
|
||||||
|
return False
|
||||||
|
|
||||||
|
if FORCE_FP16:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if device is not None: #TODO
|
||||||
|
if is_device_mps(device):
|
||||||
|
return False
|
||||||
|
|
||||||
if FORCE_FP32:
|
if FORCE_FP32:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if directml_enabled:
|
if directml_enabled:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if cpu_mode() or mps_mode() or xpu_available:
|
if cpu_mode() or mps_mode():
|
||||||
return False #TODO ?
|
return False #TODO ?
|
||||||
|
|
||||||
|
if is_intel_xpu():
|
||||||
|
return True
|
||||||
|
|
||||||
if torch.cuda.is_bf16_supported():
|
if torch.cuda.is_bf16_supported():
|
||||||
return True
|
return True
|
||||||
|
|
||||||
props = torch.cuda.get_device_properties("cuda")
|
props = torch.cuda.get_device_properties("cuda")
|
||||||
|
if props.major < 6:
|
||||||
|
return False
|
||||||
|
|
||||||
|
fp16_works = False
|
||||||
|
#FP16 is confirmed working on a 1080 (GP104) but it's a bit slower than FP32 so it should only be enabled
|
||||||
|
#when the model doesn't actually fit on the card
|
||||||
|
#TODO: actually test if GP106 and others have the same type of behavior
|
||||||
|
nvidia_10_series = ["1080", "1070", "titan x", "p3000", "p3200", "p4000", "p4200", "p5000", "p5200", "p6000", "1060", "1050"]
|
||||||
|
for x in nvidia_10_series:
|
||||||
|
if x in props.name.lower():
|
||||||
|
fp16_works = True
|
||||||
|
|
||||||
|
if fp16_works:
|
||||||
|
free_model_memory = (get_free_memory() * 0.9 - minimum_inference_memory())
|
||||||
|
if (not prioritize_performance) or model_params * 4 > free_model_memory:
|
||||||
|
return True
|
||||||
|
|
||||||
if props.major < 7:
|
if props.major < 7:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
#FP32 is faster on those cards?
|
#FP16 is just broken on these cards
|
||||||
nvidia_16_series = ["1660", "1650", "1630", "T500", "T550", "T600"]
|
nvidia_16_series = ["1660", "1650", "1630", "T500", "T550", "T600", "MX550", "MX450", "CMP 30HX"]
|
||||||
for x in nvidia_16_series:
|
for x in nvidia_16_series:
|
||||||
if x in props.name:
|
if x in props.name:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def soft_empty_cache():
|
def soft_empty_cache(force=False):
|
||||||
global xpu_available
|
|
||||||
global cpu_state
|
global cpu_state
|
||||||
if cpu_state == CPUState.MPS:
|
if cpu_state == CPUState.MPS:
|
||||||
torch.mps.empty_cache()
|
torch.mps.empty_cache()
|
||||||
elif xpu_available:
|
elif is_intel_xpu():
|
||||||
torch.xpu.empty_cache()
|
torch.xpu.empty_cache()
|
||||||
elif torch.cuda.is_available():
|
elif torch.cuda.is_available():
|
||||||
if is_nvidia(): #This seems to make things worse on ROCm so I only do it for cuda
|
if force or is_nvidia(): #This seems to make things worse on ROCm so I only do it for cuda
|
||||||
torch.cuda.empty_cache()
|
torch.cuda.empty_cache()
|
||||||
torch.cuda.ipc_collect()
|
torch.cuda.ipc_collect()
|
||||||
|
|
||||||
|
def resolve_lowvram_weight(weight, model, key):
|
||||||
|
if weight.device == torch.device("meta"): #lowvram NOTE: this depends on the inner working of the accelerate library so it might break.
|
||||||
|
key_split = key.split('.') # I have no idea why they don't just leave the weight there instead of using the meta device.
|
||||||
|
op = comfy.utils.get_attr(model, '.'.join(key_split[:-1]))
|
||||||
|
weight = op._hf_hook.weights_map[key_split[-1]]
|
||||||
|
return weight
|
||||||
|
|
||||||
#TODO: might be cleaner to put this somewhere else
|
#TODO: might be cleaner to put this somewhere else
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
|
|||||||
270
comfy/model_patcher.py
Normal file
270
comfy/model_patcher.py
Normal file
@ -0,0 +1,270 @@
|
|||||||
|
import torch
|
||||||
|
import copy
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
import comfy.utils
|
||||||
|
|
||||||
|
class ModelPatcher:
|
||||||
|
def __init__(self, model, load_device, offload_device, size=0, current_device=None):
|
||||||
|
self.size = size
|
||||||
|
self.model = model
|
||||||
|
self.patches = {}
|
||||||
|
self.backup = {}
|
||||||
|
self.model_options = {"transformer_options":{}}
|
||||||
|
self.model_size()
|
||||||
|
self.load_device = load_device
|
||||||
|
self.offload_device = offload_device
|
||||||
|
if current_device is None:
|
||||||
|
self.current_device = self.offload_device
|
||||||
|
else:
|
||||||
|
self.current_device = current_device
|
||||||
|
|
||||||
|
def model_size(self):
|
||||||
|
if self.size > 0:
|
||||||
|
return self.size
|
||||||
|
model_sd = self.model.state_dict()
|
||||||
|
size = 0
|
||||||
|
for k in model_sd:
|
||||||
|
t = model_sd[k]
|
||||||
|
size += t.nelement() * t.element_size()
|
||||||
|
self.size = size
|
||||||
|
self.model_keys = set(model_sd.keys())
|
||||||
|
return size
|
||||||
|
|
||||||
|
def clone(self):
|
||||||
|
n = ModelPatcher(self.model, self.load_device, self.offload_device, self.size, self.current_device)
|
||||||
|
n.patches = {}
|
||||||
|
for k in self.patches:
|
||||||
|
n.patches[k] = self.patches[k][:]
|
||||||
|
|
||||||
|
n.model_options = copy.deepcopy(self.model_options)
|
||||||
|
n.model_keys = self.model_keys
|
||||||
|
return n
|
||||||
|
|
||||||
|
def is_clone(self, other):
|
||||||
|
if hasattr(other, 'model') and self.model is other.model:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def set_model_sampler_cfg_function(self, sampler_cfg_function):
|
||||||
|
if len(inspect.signature(sampler_cfg_function).parameters) == 3:
|
||||||
|
self.model_options["sampler_cfg_function"] = lambda args: sampler_cfg_function(args["cond"], args["uncond"], args["cond_scale"]) #Old way
|
||||||
|
else:
|
||||||
|
self.model_options["sampler_cfg_function"] = sampler_cfg_function
|
||||||
|
|
||||||
|
def set_model_unet_function_wrapper(self, unet_wrapper_function):
|
||||||
|
self.model_options["model_function_wrapper"] = unet_wrapper_function
|
||||||
|
|
||||||
|
def set_model_patch(self, patch, name):
|
||||||
|
to = self.model_options["transformer_options"]
|
||||||
|
if "patches" not in to:
|
||||||
|
to["patches"] = {}
|
||||||
|
to["patches"][name] = to["patches"].get(name, []) + [patch]
|
||||||
|
|
||||||
|
def set_model_patch_replace(self, patch, name, block_name, number):
|
||||||
|
to = self.model_options["transformer_options"]
|
||||||
|
if "patches_replace" not in to:
|
||||||
|
to["patches_replace"] = {}
|
||||||
|
if name not in to["patches_replace"]:
|
||||||
|
to["patches_replace"][name] = {}
|
||||||
|
to["patches_replace"][name][(block_name, number)] = patch
|
||||||
|
|
||||||
|
def set_model_attn1_patch(self, patch):
|
||||||
|
self.set_model_patch(patch, "attn1_patch")
|
||||||
|
|
||||||
|
def set_model_attn2_patch(self, patch):
|
||||||
|
self.set_model_patch(patch, "attn2_patch")
|
||||||
|
|
||||||
|
def set_model_attn1_replace(self, patch, block_name, number):
|
||||||
|
self.set_model_patch_replace(patch, "attn1", block_name, number)
|
||||||
|
|
||||||
|
def set_model_attn2_replace(self, patch, block_name, number):
|
||||||
|
self.set_model_patch_replace(patch, "attn2", block_name, number)
|
||||||
|
|
||||||
|
def set_model_attn1_output_patch(self, patch):
|
||||||
|
self.set_model_patch(patch, "attn1_output_patch")
|
||||||
|
|
||||||
|
def set_model_attn2_output_patch(self, patch):
|
||||||
|
self.set_model_patch(patch, "attn2_output_patch")
|
||||||
|
|
||||||
|
def model_patches_to(self, device):
|
||||||
|
to = self.model_options["transformer_options"]
|
||||||
|
if "patches" in to:
|
||||||
|
patches = to["patches"]
|
||||||
|
for name in patches:
|
||||||
|
patch_list = patches[name]
|
||||||
|
for i in range(len(patch_list)):
|
||||||
|
if hasattr(patch_list[i], "to"):
|
||||||
|
patch_list[i] = patch_list[i].to(device)
|
||||||
|
if "patches_replace" in to:
|
||||||
|
patches = to["patches_replace"]
|
||||||
|
for name in patches:
|
||||||
|
patch_list = patches[name]
|
||||||
|
for k in patch_list:
|
||||||
|
if hasattr(patch_list[k], "to"):
|
||||||
|
patch_list[k] = patch_list[k].to(device)
|
||||||
|
|
||||||
|
def model_dtype(self):
|
||||||
|
if hasattr(self.model, "get_dtype"):
|
||||||
|
return self.model.get_dtype()
|
||||||
|
|
||||||
|
def add_patches(self, patches, strength_patch=1.0, strength_model=1.0):
|
||||||
|
p = set()
|
||||||
|
for k in patches:
|
||||||
|
if k in self.model_keys:
|
||||||
|
p.add(k)
|
||||||
|
current_patches = self.patches.get(k, [])
|
||||||
|
current_patches.append((strength_patch, patches[k], strength_model))
|
||||||
|
self.patches[k] = current_patches
|
||||||
|
|
||||||
|
return list(p)
|
||||||
|
|
||||||
|
def get_key_patches(self, filter_prefix=None):
|
||||||
|
model_sd = self.model_state_dict()
|
||||||
|
p = {}
|
||||||
|
for k in model_sd:
|
||||||
|
if filter_prefix is not None:
|
||||||
|
if not k.startswith(filter_prefix):
|
||||||
|
continue
|
||||||
|
if k in self.patches:
|
||||||
|
p[k] = [model_sd[k]] + self.patches[k]
|
||||||
|
else:
|
||||||
|
p[k] = (model_sd[k],)
|
||||||
|
return p
|
||||||
|
|
||||||
|
def model_state_dict(self, filter_prefix=None):
|
||||||
|
sd = self.model.state_dict()
|
||||||
|
keys = list(sd.keys())
|
||||||
|
if filter_prefix is not None:
|
||||||
|
for k in keys:
|
||||||
|
if not k.startswith(filter_prefix):
|
||||||
|
sd.pop(k)
|
||||||
|
return sd
|
||||||
|
|
||||||
|
def patch_model(self, device_to=None):
|
||||||
|
model_sd = self.model_state_dict()
|
||||||
|
for key in self.patches:
|
||||||
|
if key not in model_sd:
|
||||||
|
print("could not patch. key doesn't exist in model:", key)
|
||||||
|
continue
|
||||||
|
|
||||||
|
weight = model_sd[key]
|
||||||
|
|
||||||
|
if key not in self.backup:
|
||||||
|
self.backup[key] = weight.to(self.offload_device)
|
||||||
|
|
||||||
|
if device_to is not None:
|
||||||
|
temp_weight = weight.float().to(device_to, copy=True)
|
||||||
|
else:
|
||||||
|
temp_weight = weight.to(torch.float32, copy=True)
|
||||||
|
out_weight = self.calculate_weight(self.patches[key], temp_weight, key).to(weight.dtype)
|
||||||
|
comfy.utils.set_attr(self.model, key, out_weight)
|
||||||
|
del temp_weight
|
||||||
|
|
||||||
|
if device_to is not None:
|
||||||
|
self.model.to(device_to)
|
||||||
|
self.current_device = device_to
|
||||||
|
|
||||||
|
return self.model
|
||||||
|
|
||||||
|
def calculate_weight(self, patches, weight, key):
|
||||||
|
for p in patches:
|
||||||
|
alpha = p[0]
|
||||||
|
v = p[1]
|
||||||
|
strength_model = p[2]
|
||||||
|
|
||||||
|
if strength_model != 1.0:
|
||||||
|
weight *= strength_model
|
||||||
|
|
||||||
|
if isinstance(v, list):
|
||||||
|
v = (self.calculate_weight(v[1:], v[0].clone(), key), )
|
||||||
|
|
||||||
|
if len(v) == 1:
|
||||||
|
w1 = v[0]
|
||||||
|
if alpha != 0.0:
|
||||||
|
if w1.shape != weight.shape:
|
||||||
|
print("WARNING SHAPE MISMATCH {} WEIGHT NOT MERGED {} != {}".format(key, w1.shape, weight.shape))
|
||||||
|
else:
|
||||||
|
weight += alpha * w1.type(weight.dtype).to(weight.device)
|
||||||
|
elif len(v) == 4: #lora/locon
|
||||||
|
mat1 = v[0].float().to(weight.device)
|
||||||
|
mat2 = v[1].float().to(weight.device)
|
||||||
|
if v[2] is not None:
|
||||||
|
alpha *= v[2] / mat2.shape[0]
|
||||||
|
if v[3] is not None:
|
||||||
|
#locon mid weights, hopefully the math is fine because I didn't properly test it
|
||||||
|
mat3 = v[3].float().to(weight.device)
|
||||||
|
final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]]
|
||||||
|
mat2 = torch.mm(mat2.transpose(0, 1).flatten(start_dim=1), mat3.transpose(0, 1).flatten(start_dim=1)).reshape(final_shape).transpose(0, 1)
|
||||||
|
try:
|
||||||
|
weight += (alpha * torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1))).reshape(weight.shape).type(weight.dtype)
|
||||||
|
except Exception as e:
|
||||||
|
print("ERROR", key, e)
|
||||||
|
elif len(v) == 8: #lokr
|
||||||
|
w1 = v[0]
|
||||||
|
w2 = v[1]
|
||||||
|
w1_a = v[3]
|
||||||
|
w1_b = v[4]
|
||||||
|
w2_a = v[5]
|
||||||
|
w2_b = v[6]
|
||||||
|
t2 = v[7]
|
||||||
|
dim = None
|
||||||
|
|
||||||
|
if w1 is None:
|
||||||
|
dim = w1_b.shape[0]
|
||||||
|
w1 = torch.mm(w1_a.float(), w1_b.float())
|
||||||
|
else:
|
||||||
|
w1 = w1.float().to(weight.device)
|
||||||
|
|
||||||
|
if w2 is None:
|
||||||
|
dim = w2_b.shape[0]
|
||||||
|
if t2 is None:
|
||||||
|
w2 = torch.mm(w2_a.float().to(weight.device), w2_b.float().to(weight.device))
|
||||||
|
else:
|
||||||
|
w2 = torch.einsum('i j k l, j r, i p -> p r k l', t2.float().to(weight.device), w2_b.float().to(weight.device), w2_a.float().to(weight.device))
|
||||||
|
else:
|
||||||
|
w2 = w2.float().to(weight.device)
|
||||||
|
|
||||||
|
if len(w2.shape) == 4:
|
||||||
|
w1 = w1.unsqueeze(2).unsqueeze(2)
|
||||||
|
if v[2] is not None and dim is not None:
|
||||||
|
alpha *= v[2] / dim
|
||||||
|
|
||||||
|
try:
|
||||||
|
weight += alpha * torch.kron(w1, w2).reshape(weight.shape).type(weight.dtype)
|
||||||
|
except Exception as e:
|
||||||
|
print("ERROR", key, e)
|
||||||
|
else: #loha
|
||||||
|
w1a = v[0]
|
||||||
|
w1b = v[1]
|
||||||
|
if v[2] is not None:
|
||||||
|
alpha *= v[2] / w1b.shape[0]
|
||||||
|
w2a = v[3]
|
||||||
|
w2b = v[4]
|
||||||
|
if v[5] is not None: #cp decomposition
|
||||||
|
t1 = v[5]
|
||||||
|
t2 = v[6]
|
||||||
|
m1 = torch.einsum('i j k l, j r, i p -> p r k l', t1.float().to(weight.device), w1b.float().to(weight.device), w1a.float().to(weight.device))
|
||||||
|
m2 = torch.einsum('i j k l, j r, i p -> p r k l', t2.float().to(weight.device), w2b.float().to(weight.device), w2a.float().to(weight.device))
|
||||||
|
else:
|
||||||
|
m1 = torch.mm(w1a.float().to(weight.device), w1b.float().to(weight.device))
|
||||||
|
m2 = torch.mm(w2a.float().to(weight.device), w2b.float().to(weight.device))
|
||||||
|
|
||||||
|
try:
|
||||||
|
weight += (alpha * m1 * m2).reshape(weight.shape).type(weight.dtype)
|
||||||
|
except Exception as e:
|
||||||
|
print("ERROR", key, e)
|
||||||
|
|
||||||
|
return weight
|
||||||
|
|
||||||
|
def unpatch_model(self, device_to=None):
|
||||||
|
keys = list(self.backup.keys())
|
||||||
|
|
||||||
|
for k in keys:
|
||||||
|
comfy.utils.set_attr(self.model, k, self.backup[k])
|
||||||
|
|
||||||
|
self.backup = {}
|
||||||
|
|
||||||
|
if device_to is not None:
|
||||||
|
self.model.to(device_to)
|
||||||
|
self.current_device = device_to
|
||||||
18
comfy/ops.py
18
comfy/ops.py
@ -21,11 +21,25 @@ class Conv2d(torch.nn.Conv2d):
|
|||||||
def reset_parameters(self):
|
def reset_parameters(self):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def conv_nd(dims, *args, **kwargs):
|
||||||
|
if dims == 2:
|
||||||
|
return Conv2d(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"unsupported dimensions: {dims}")
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def use_comfy_ops(): # Kind of an ugly hack but I can't think of a better way
|
def use_comfy_ops(device=None, dtype=None): # Kind of an ugly hack but I can't think of a better way
|
||||||
old_torch_nn_linear = torch.nn.Linear
|
old_torch_nn_linear = torch.nn.Linear
|
||||||
torch.nn.Linear = Linear
|
force_device = device
|
||||||
|
force_dtype = dtype
|
||||||
|
def linear_with_dtype(in_features: int, out_features: int, bias: bool = True, device=None, dtype=None):
|
||||||
|
if force_device is not None:
|
||||||
|
device = force_device
|
||||||
|
if force_dtype is not None:
|
||||||
|
dtype = force_dtype
|
||||||
|
return Linear(in_features, out_features, bias=bias, device=device, dtype=dtype)
|
||||||
|
|
||||||
|
torch.nn.Linear = linear_with_dtype
|
||||||
try:
|
try:
|
||||||
yield
|
yield
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import torch
|
import torch
|
||||||
import comfy.model_management
|
import comfy.model_management
|
||||||
import comfy.samplers
|
import comfy.samplers
|
||||||
|
import comfy.utils
|
||||||
import math
|
import math
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
@ -28,8 +29,7 @@ def prepare_mask(noise_mask, shape, device):
|
|||||||
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")
|
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")
|
||||||
noise_mask = noise_mask.round()
|
noise_mask = noise_mask.round()
|
||||||
noise_mask = torch.cat([noise_mask] * shape[1], dim=1)
|
noise_mask = torch.cat([noise_mask] * shape[1], dim=1)
|
||||||
if noise_mask.shape[0] < shape[0]:
|
noise_mask = comfy.utils.repeat_to_batch_size(noise_mask, shape[0])
|
||||||
noise_mask = noise_mask.repeat(math.ceil(shape[0] / noise_mask.shape[0]), 1, 1, 1)[:shape[0]]
|
|
||||||
noise_mask = noise_mask.to(device)
|
noise_mask = noise_mask.to(device)
|
||||||
return noise_mask
|
return noise_mask
|
||||||
|
|
||||||
@ -37,9 +37,7 @@ def broadcast_cond(cond, batch, device):
|
|||||||
"""broadcasts conditioning to the batch size"""
|
"""broadcasts conditioning to the batch size"""
|
||||||
copy = []
|
copy = []
|
||||||
for p in cond:
|
for p in cond:
|
||||||
t = p[0]
|
t = comfy.utils.repeat_to_batch_size(p[0], batch)
|
||||||
if t.shape[0] < batch:
|
|
||||||
t = torch.cat([t] * batch)
|
|
||||||
t = t.to(device)
|
t = t.to(device)
|
||||||
copy += [[t] + p[1:]]
|
copy += [[t] + p[1:]]
|
||||||
return copy
|
return copy
|
||||||
@ -51,19 +49,26 @@ def get_models_from_cond(cond, model_type):
|
|||||||
models += [c[1][model_type]]
|
models += [c[1][model_type]]
|
||||||
return models
|
return models
|
||||||
|
|
||||||
def load_additional_models(positive, negative):
|
def get_additional_models(positive, negative, dtype):
|
||||||
"""loads additional models in positive and negative conditioning"""
|
"""loads additional models in positive and negative conditioning"""
|
||||||
control_nets = get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control")
|
control_nets = set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control"))
|
||||||
|
|
||||||
|
inference_memory = 0
|
||||||
|
control_models = []
|
||||||
|
for m in control_nets:
|
||||||
|
control_models += m.get_models()
|
||||||
|
inference_memory += m.inference_memory_requirements(dtype)
|
||||||
|
|
||||||
gligen = get_models_from_cond(positive, "gligen") + get_models_from_cond(negative, "gligen")
|
gligen = get_models_from_cond(positive, "gligen") + get_models_from_cond(negative, "gligen")
|
||||||
gligen = [x[1] for x in gligen]
|
gligen = [x[1] for x in gligen]
|
||||||
models = control_nets + gligen
|
models = control_models + gligen
|
||||||
comfy.model_management.load_controlnet_gpu(models)
|
return models, inference_memory
|
||||||
return models
|
|
||||||
|
|
||||||
def cleanup_additional_models(models):
|
def cleanup_additional_models(models):
|
||||||
"""cleanup additional models that were loaded"""
|
"""cleanup additional models that were loaded"""
|
||||||
for m in models:
|
for m in models:
|
||||||
m.cleanup()
|
if hasattr(m, 'cleanup'):
|
||||||
|
m.cleanup()
|
||||||
|
|
||||||
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):
|
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):
|
||||||
device = comfy.model_management.get_torch_device()
|
device = comfy.model_management.get_torch_device()
|
||||||
@ -72,7 +77,8 @@ def sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative
|
|||||||
noise_mask = prepare_mask(noise_mask, noise.shape, device)
|
noise_mask = prepare_mask(noise_mask, noise.shape, device)
|
||||||
|
|
||||||
real_model = None
|
real_model = None
|
||||||
comfy.model_management.load_model_gpu(model)
|
models, inference_memory = get_additional_models(positive, negative, model.model_dtype())
|
||||||
|
comfy.model_management.load_models_gpu([model] + models, comfy.model_management.batch_area_memory(noise.shape[0] * noise.shape[2] * noise.shape[3]) + inference_memory)
|
||||||
real_model = model.model
|
real_model = model.model
|
||||||
|
|
||||||
noise = noise.to(device)
|
noise = noise.to(device)
|
||||||
@ -81,7 +87,6 @@ def sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative
|
|||||||
positive_copy = broadcast_cond(positive, noise.shape[0], device)
|
positive_copy = broadcast_cond(positive, noise.shape[0], device)
|
||||||
negative_copy = broadcast_cond(negative, noise.shape[0], device)
|
negative_copy = broadcast_cond(negative, noise.shape[0], device)
|
||||||
|
|
||||||
models = load_additional_models(positive, negative)
|
|
||||||
|
|
||||||
sampler = comfy.samplers.KSampler(real_model, steps=steps, device=device, sampler=sampler_name, scheduler=scheduler, denoise=denoise, model_options=model.model_options)
|
sampler = comfy.samplers.KSampler(real_model, steps=steps, device=device, sampler=sampler_name, scheduler=scheduler, denoise=denoise, model_options=model.model_options)
|
||||||
|
|
||||||
|
|||||||
@ -2,11 +2,11 @@ from .k_diffusion import sampling as k_diffusion_sampling
|
|||||||
from .k_diffusion import external as k_diffusion_external
|
from .k_diffusion import external as k_diffusion_external
|
||||||
from .extra_samplers import uni_pc
|
from .extra_samplers import uni_pc
|
||||||
import torch
|
import torch
|
||||||
import contextlib
|
|
||||||
from comfy import model_management
|
from comfy import model_management
|
||||||
from .ldm.models.diffusion.ddim import DDIMSampler
|
from .ldm.models.diffusion.ddim import DDIMSampler
|
||||||
from .ldm.modules.diffusionmodules.util import make_ddim_timesteps
|
from .ldm.modules.diffusionmodules.util import make_ddim_timesteps
|
||||||
import math
|
import math
|
||||||
|
from comfy import model_base
|
||||||
|
|
||||||
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
|
def lcm(a, b): #TODO: eventually replace by math.lcm (added in python3.9)
|
||||||
return abs(a*b) // math.gcd(a, b)
|
return abs(a*b) // math.gcd(a, b)
|
||||||
@ -17,6 +17,14 @@ def sampling_function(model_function, x, timestep, uncond, cond, cond_scale, con
|
|||||||
def get_area_and_mult(cond, x_in, cond_concat_in, timestep_in):
|
def get_area_and_mult(cond, x_in, cond_concat_in, timestep_in):
|
||||||
area = (x_in.shape[2], x_in.shape[3], 0, 0)
|
area = (x_in.shape[2], x_in.shape[3], 0, 0)
|
||||||
strength = 1.0
|
strength = 1.0
|
||||||
|
if 'timestep_start' in cond[1]:
|
||||||
|
timestep_start = cond[1]['timestep_start']
|
||||||
|
if timestep_in[0] > timestep_start:
|
||||||
|
return None
|
||||||
|
if 'timestep_end' in cond[1]:
|
||||||
|
timestep_end = cond[1]['timestep_end']
|
||||||
|
if timestep_in[0] < timestep_end:
|
||||||
|
return None
|
||||||
if 'area' in cond[1]:
|
if 'area' in cond[1]:
|
||||||
area = cond[1]['area']
|
area = cond[1]['area']
|
||||||
if 'strength' in cond[1]:
|
if 'strength' in cond[1]:
|
||||||
@ -80,9 +88,9 @@ def sampling_function(model_function, x, timestep, uncond, cond, cond_scale, con
|
|||||||
gligen_type = gligen[0]
|
gligen_type = gligen[0]
|
||||||
gligen_model = gligen[1]
|
gligen_model = gligen[1]
|
||||||
if gligen_type == "position":
|
if gligen_type == "position":
|
||||||
gligen_patch = gligen_model.set_position(input_x.shape, gligen[2], input_x.device)
|
gligen_patch = gligen_model.model.set_position(input_x.shape, gligen[2], input_x.device)
|
||||||
else:
|
else:
|
||||||
gligen_patch = gligen_model.set_empty(input_x.shape, input_x.device)
|
gligen_patch = gligen_model.model.set_empty(input_x.shape, input_x.device)
|
||||||
|
|
||||||
patches['middle_patch'] = [gligen_patch]
|
patches['middle_patch'] = [gligen_patch]
|
||||||
|
|
||||||
@ -157,9 +165,9 @@ def sampling_function(model_function, x, timestep, uncond, cond, cond_scale, con
|
|||||||
c_crossattn_out.append(c)
|
c_crossattn_out.append(c)
|
||||||
|
|
||||||
if len(c_crossattn_out) > 0:
|
if len(c_crossattn_out) > 0:
|
||||||
out['c_crossattn'] = [torch.cat(c_crossattn_out)]
|
out['c_crossattn'] = torch.cat(c_crossattn_out)
|
||||||
if len(c_concat) > 0:
|
if len(c_concat) > 0:
|
||||||
out['c_concat'] = [torch.cat(c_concat)]
|
out['c_concat'] = torch.cat(c_concat)
|
||||||
if len(c_adm) > 0:
|
if len(c_adm) > 0:
|
||||||
out['c_adm'] = torch.cat(c_adm)
|
out['c_adm'] = torch.cat(c_adm)
|
||||||
return out
|
return out
|
||||||
@ -181,12 +189,13 @@ def sampling_function(model_function, x, timestep, uncond, cond, cond_scale, con
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
to_run += [(p, COND)]
|
to_run += [(p, COND)]
|
||||||
for x in uncond:
|
if uncond is not None:
|
||||||
p = get_area_and_mult(x, x_in, cond_concat_in, timestep)
|
for x in uncond:
|
||||||
if p is None:
|
p = get_area_and_mult(x, x_in, cond_concat_in, timestep)
|
||||||
continue
|
if p is None:
|
||||||
|
continue
|
||||||
|
|
||||||
to_run += [(p, UNCOND)]
|
to_run += [(p, UNCOND)]
|
||||||
|
|
||||||
while len(to_run) > 0:
|
while len(to_run) > 0:
|
||||||
first = to_run[0]
|
first = to_run[0]
|
||||||
@ -248,11 +257,12 @@ def sampling_function(model_function, x, timestep, uncond, cond, cond_scale, con
|
|||||||
|
|
||||||
c['transformer_options'] = transformer_options
|
c['transformer_options'] = transformer_options
|
||||||
|
|
||||||
output = model_function(input_x, timestep_, **c).chunk(batch_chunks)
|
if 'model_function_wrapper' in model_options:
|
||||||
|
output = model_options['model_function_wrapper'](model_function, {"input": input_x, "timestep": timestep_, "c": c, "cond_or_uncond": cond_or_uncond}).chunk(batch_chunks)
|
||||||
|
else:
|
||||||
|
output = model_function(input_x, timestep_, **c).chunk(batch_chunks)
|
||||||
del input_x
|
del input_x
|
||||||
|
|
||||||
model_management.throw_exception_if_processing_interrupted()
|
|
||||||
|
|
||||||
for o in range(batch_chunks):
|
for o in range(batch_chunks):
|
||||||
if cond_or_uncond[o] == COND:
|
if cond_or_uncond[o] == COND:
|
||||||
out_cond[:,:,area[o][2]:area[o][0] + area[o][2],area[o][3]:area[o][1] + area[o][3]] += output[o] * mult[o]
|
out_cond[:,:,area[o][2]:area[o][0] + area[o][2],area[o][3]:area[o][1] + area[o][3]] += output[o] * mult[o]
|
||||||
@ -271,6 +281,9 @@ def sampling_function(model_function, x, timestep, uncond, cond, cond_scale, con
|
|||||||
|
|
||||||
|
|
||||||
max_total_area = model_management.maximum_batch_area()
|
max_total_area = model_management.maximum_batch_area()
|
||||||
|
if math.isclose(cond_scale, 1.0):
|
||||||
|
uncond = None
|
||||||
|
|
||||||
cond, uncond = calc_cond_uncond_batch(model_function, cond, uncond, x, timestep, max_total_area, cond_concat, model_options)
|
cond, uncond = calc_cond_uncond_batch(model_function, cond, uncond, x, timestep, max_total_area, cond_concat, model_options)
|
||||||
if "sampler_cfg_function" in model_options:
|
if "sampler_cfg_function" in model_options:
|
||||||
args = {"cond": cond, "uncond": uncond, "cond_scale": cond_scale, "timestep": timestep}
|
args = {"cond": cond, "uncond": uncond, "cond_scale": cond_scale, "timestep": timestep}
|
||||||
@ -332,6 +345,17 @@ def ddim_scheduler(model, steps):
|
|||||||
sigs += [0.0]
|
sigs += [0.0]
|
||||||
return torch.FloatTensor(sigs)
|
return torch.FloatTensor(sigs)
|
||||||
|
|
||||||
|
def sgm_scheduler(model, steps):
|
||||||
|
sigs = []
|
||||||
|
timesteps = torch.linspace(model.inner_model.inner_model.num_timesteps - 1, 0, steps + 1)[:-1].type(torch.int)
|
||||||
|
for x in range(len(timesteps)):
|
||||||
|
ts = timesteps[x]
|
||||||
|
if ts > 999:
|
||||||
|
ts = 999
|
||||||
|
sigs.append(model.t_to_sigma(torch.tensor(ts)))
|
||||||
|
sigs += [0.0]
|
||||||
|
return torch.FloatTensor(sigs)
|
||||||
|
|
||||||
def blank_inpaint_image_like(latent_image):
|
def blank_inpaint_image_like(latent_image):
|
||||||
blank_image = torch.ones_like(latent_image)
|
blank_image = torch.ones_like(latent_image)
|
||||||
# these are the values for "zero" in pixel space translated to latent space
|
# these are the values for "zero" in pixel space translated to latent space
|
||||||
@ -364,18 +388,27 @@ def get_mask_aabb(masks):
|
|||||||
|
|
||||||
return bounding_boxes, is_empty
|
return bounding_boxes, is_empty
|
||||||
|
|
||||||
def resolve_cond_masks(conditions, h, w, device):
|
def resolve_areas_and_cond_masks(conditions, h, w, device):
|
||||||
# We need to decide on an area outside the sampling loop in order to properly generate opposite areas of equal sizes.
|
# We need to decide on an area outside the sampling loop in order to properly generate opposite areas of equal sizes.
|
||||||
# While we're doing this, we can also resolve the mask device and scaling for performance reasons
|
# While we're doing this, we can also resolve the mask device and scaling for performance reasons
|
||||||
for i in range(len(conditions)):
|
for i in range(len(conditions)):
|
||||||
c = conditions[i]
|
c = conditions[i]
|
||||||
|
if 'area' in c[1]:
|
||||||
|
area = c[1]['area']
|
||||||
|
if area[0] == "percentage":
|
||||||
|
modified = c[1].copy()
|
||||||
|
area = (max(1, round(area[1] * h)), max(1, round(area[2] * w)), round(area[3] * h), round(area[4] * w))
|
||||||
|
modified['area'] = area
|
||||||
|
c = [c[0], modified]
|
||||||
|
conditions[i] = c
|
||||||
|
|
||||||
if 'mask' in c[1]:
|
if 'mask' in c[1]:
|
||||||
mask = c[1]['mask']
|
mask = c[1]['mask']
|
||||||
mask = mask.to(device=device)
|
mask = mask.to(device=device)
|
||||||
modified = c[1].copy()
|
modified = c[1].copy()
|
||||||
if len(mask.shape) == 2:
|
if len(mask.shape) == 2:
|
||||||
mask = mask.unsqueeze(0)
|
mask = mask.unsqueeze(0)
|
||||||
if mask.shape[2] != h or mask.shape[3] != w:
|
if mask.shape[1] != h or mask.shape[2] != w:
|
||||||
mask = torch.nn.functional.interpolate(mask.unsqueeze(1), size=(h, w), mode='bilinear', align_corners=False).squeeze(1)
|
mask = torch.nn.functional.interpolate(mask.unsqueeze(1), size=(h, w), mode='bilinear', align_corners=False).squeeze(1)
|
||||||
|
|
||||||
if modified.get("set_area_to_bounds", False):
|
if modified.get("set_area_to_bounds", False):
|
||||||
@ -425,6 +458,35 @@ def create_cond_with_same_area_if_none(conds, c):
|
|||||||
n = c[1].copy()
|
n = c[1].copy()
|
||||||
conds += [[smallest[0], n]]
|
conds += [[smallest[0], n]]
|
||||||
|
|
||||||
|
def calculate_start_end_timesteps(model, conds):
|
||||||
|
for t in range(len(conds)):
|
||||||
|
x = conds[t]
|
||||||
|
|
||||||
|
timestep_start = None
|
||||||
|
timestep_end = None
|
||||||
|
if 'start_percent' in x[1]:
|
||||||
|
timestep_start = model.sigma_to_t(model.t_to_sigma(torch.tensor(x[1]['start_percent'] * 999.0)))
|
||||||
|
if 'end_percent' in x[1]:
|
||||||
|
timestep_end = model.sigma_to_t(model.t_to_sigma(torch.tensor(x[1]['end_percent'] * 999.0)))
|
||||||
|
|
||||||
|
if (timestep_start is not None) or (timestep_end is not None):
|
||||||
|
n = x[1].copy()
|
||||||
|
if (timestep_start is not None):
|
||||||
|
n['timestep_start'] = timestep_start
|
||||||
|
if (timestep_end is not None):
|
||||||
|
n['timestep_end'] = timestep_end
|
||||||
|
conds[t] = [x[0], n]
|
||||||
|
|
||||||
|
def pre_run_control(model, conds):
|
||||||
|
for t in range(len(conds)):
|
||||||
|
x = conds[t]
|
||||||
|
|
||||||
|
timestep_start = None
|
||||||
|
timestep_end = None
|
||||||
|
percent_to_timestep_function = lambda a: model.sigma_to_t(model.t_to_sigma(torch.tensor(a) * 999.0))
|
||||||
|
if 'control' in x[1]:
|
||||||
|
x[1]['control'].pre_run(model.inner_model.inner_model, percent_to_timestep_function)
|
||||||
|
|
||||||
def apply_empty_x_to_equal_area(conds, uncond, name, uncond_fill_func):
|
def apply_empty_x_to_equal_area(conds, uncond, name, uncond_fill_func):
|
||||||
cond_cnets = []
|
cond_cnets = []
|
||||||
cond_other = []
|
cond_other = []
|
||||||
@ -481,19 +543,19 @@ def encode_adm(model, conds, batch_size, width, height, device, prompt_type):
|
|||||||
|
|
||||||
|
|
||||||
class KSampler:
|
class KSampler:
|
||||||
SCHEDULERS = ["normal", "karras", "exponential", "simple", "ddim_uniform"]
|
SCHEDULERS = ["normal", "karras", "exponential", "sgm_uniform", "simple", "ddim_uniform"]
|
||||||
SAMPLERS = ["euler", "euler_ancestral", "heun", "dpm_2", "dpm_2_ancestral",
|
SAMPLERS = ["euler", "euler_ancestral", "heun", "dpm_2", "dpm_2_ancestral",
|
||||||
"lms", "dpm_fast", "dpm_adaptive", "dpmpp_2s_ancestral", "dpmpp_sde",
|
"lms", "dpm_fast", "dpm_adaptive", "dpmpp_2s_ancestral", "dpmpp_sde", "dpmpp_sde_gpu",
|
||||||
"dpmpp_2m", "dpmpp_2m_sde", "ddim", "uni_pc", "uni_pc_bh2"]
|
"dpmpp_2m", "dpmpp_2m_sde", "dpmpp_2m_sde_gpu", "dpmpp_3m_sde", "dpmpp_3m_sde_gpu", "ddim", "uni_pc", "uni_pc_bh2"]
|
||||||
|
|
||||||
def __init__(self, model, steps, device, sampler=None, scheduler=None, denoise=None, model_options={}):
|
def __init__(self, model, steps, device, sampler=None, scheduler=None, denoise=None, model_options={}):
|
||||||
self.model = model
|
self.model = model
|
||||||
self.model_denoise = CFGNoisePredictor(self.model)
|
self.model_denoise = CFGNoisePredictor(self.model)
|
||||||
if self.model.parameterization == "v":
|
if self.model.model_type == model_base.ModelType.V_PREDICTION:
|
||||||
self.model_wrap = CompVisVDenoiser(self.model_denoise, quantize=True)
|
self.model_wrap = CompVisVDenoiser(self.model_denoise, quantize=True)
|
||||||
else:
|
else:
|
||||||
self.model_wrap = k_diffusion_external.CompVisDenoiser(self.model_denoise, quantize=True)
|
self.model_wrap = k_diffusion_external.CompVisDenoiser(self.model_denoise, quantize=True)
|
||||||
self.model_wrap.parameterization = self.model.parameterization
|
|
||||||
self.model_k = KSamplerX0Inpaint(self.model_wrap)
|
self.model_k = KSamplerX0Inpaint(self.model_wrap)
|
||||||
self.device = device
|
self.device = device
|
||||||
if scheduler not in self.SCHEDULERS:
|
if scheduler not in self.SCHEDULERS:
|
||||||
@ -526,6 +588,8 @@ class KSampler:
|
|||||||
sigmas = simple_scheduler(self.model_wrap, steps)
|
sigmas = simple_scheduler(self.model_wrap, steps)
|
||||||
elif self.scheduler == "ddim_uniform":
|
elif self.scheduler == "ddim_uniform":
|
||||||
sigmas = ddim_scheduler(self.model_wrap, steps)
|
sigmas = ddim_scheduler(self.model_wrap, steps)
|
||||||
|
elif self.scheduler == "sgm_uniform":
|
||||||
|
sigmas = sgm_scheduler(self.model_wrap, steps)
|
||||||
else:
|
else:
|
||||||
print("error invalid scheduler", self.scheduler)
|
print("error invalid scheduler", self.scheduler)
|
||||||
|
|
||||||
@ -565,8 +629,11 @@ class KSampler:
|
|||||||
positive = positive[:]
|
positive = positive[:]
|
||||||
negative = negative[:]
|
negative = negative[:]
|
||||||
|
|
||||||
resolve_cond_masks(positive, noise.shape[2], noise.shape[3], self.device)
|
resolve_areas_and_cond_masks(positive, noise.shape[2], noise.shape[3], self.device)
|
||||||
resolve_cond_masks(negative, noise.shape[2], noise.shape[3], self.device)
|
resolve_areas_and_cond_masks(negative, noise.shape[2], noise.shape[3], self.device)
|
||||||
|
|
||||||
|
calculate_start_end_timesteps(self.model_wrap, negative)
|
||||||
|
calculate_start_end_timesteps(self.model_wrap, positive)
|
||||||
|
|
||||||
#make sure each cond area has an opposite one with the same area
|
#make sure each cond area has an opposite one with the same area
|
||||||
for c in positive:
|
for c in positive:
|
||||||
@ -574,13 +641,10 @@ class KSampler:
|
|||||||
for c in negative:
|
for c in negative:
|
||||||
create_cond_with_same_area_if_none(positive, c)
|
create_cond_with_same_area_if_none(positive, c)
|
||||||
|
|
||||||
apply_empty_x_to_equal_area(positive, negative, 'control', lambda cond_cnets, x: cond_cnets[x])
|
pre_run_control(self.model_wrap, negative + positive)
|
||||||
apply_empty_x_to_equal_area(positive, negative, 'gligen', lambda cond_cnets, x: cond_cnets[x])
|
|
||||||
|
|
||||||
if self.model.get_dtype() == torch.float16:
|
apply_empty_x_to_equal_area(list(filter(lambda c: c[1].get('control_apply_to_uncond', False) == True, positive)), negative, 'control', lambda cond_cnets, x: cond_cnets[x])
|
||||||
precision_scope = torch.autocast
|
apply_empty_x_to_equal_area(positive, negative, 'gligen', lambda cond_cnets, x: cond_cnets[x])
|
||||||
else:
|
|
||||||
precision_scope = contextlib.nullcontext
|
|
||||||
|
|
||||||
if self.model.is_adm():
|
if self.model.is_adm():
|
||||||
positive = encode_adm(self.model, positive, noise.shape[0], noise.shape[3], noise.shape[2], self.device, "positive")
|
positive = encode_adm(self.model, positive, noise.shape[0], noise.shape[3], noise.shape[2], self.device, "positive")
|
||||||
@ -612,67 +676,67 @@ class KSampler:
|
|||||||
else:
|
else:
|
||||||
max_denoise = True
|
max_denoise = True
|
||||||
|
|
||||||
with precision_scope(model_management.get_autocast_device(self.device)):
|
|
||||||
if self.sampler == "uni_pc":
|
|
||||||
samples = uni_pc.sample_unipc(self.model_wrap, noise, latent_image, sigmas, sampling_function=sampling_function, max_denoise=max_denoise, extra_args=extra_args, noise_mask=denoise_mask, callback=callback, disable=disable_pbar)
|
|
||||||
elif self.sampler == "uni_pc_bh2":
|
|
||||||
samples = uni_pc.sample_unipc(self.model_wrap, noise, latent_image, sigmas, sampling_function=sampling_function, max_denoise=max_denoise, extra_args=extra_args, noise_mask=denoise_mask, callback=callback, variant='bh2', disable=disable_pbar)
|
|
||||||
elif self.sampler == "ddim":
|
|
||||||
timesteps = []
|
|
||||||
for s in range(sigmas.shape[0]):
|
|
||||||
timesteps.insert(0, self.model_wrap.sigma_to_t(sigmas[s]))
|
|
||||||
noise_mask = None
|
|
||||||
if denoise_mask is not None:
|
|
||||||
noise_mask = 1.0 - denoise_mask
|
|
||||||
|
|
||||||
ddim_callback = None
|
if self.sampler == "uni_pc":
|
||||||
if callback is not None:
|
samples = uni_pc.sample_unipc(self.model_wrap, noise, latent_image, sigmas, sampling_function=sampling_function, max_denoise=max_denoise, extra_args=extra_args, noise_mask=denoise_mask, callback=callback, disable=disable_pbar)
|
||||||
total_steps = len(timesteps) - 1
|
elif self.sampler == "uni_pc_bh2":
|
||||||
ddim_callback = lambda pred_x0, i: callback(i, pred_x0, None, total_steps)
|
samples = uni_pc.sample_unipc(self.model_wrap, noise, latent_image, sigmas, sampling_function=sampling_function, max_denoise=max_denoise, extra_args=extra_args, noise_mask=denoise_mask, callback=callback, variant='bh2', disable=disable_pbar)
|
||||||
|
elif self.sampler == "ddim":
|
||||||
|
timesteps = []
|
||||||
|
for s in range(sigmas.shape[0]):
|
||||||
|
timesteps.insert(0, self.model_wrap.sigma_to_discrete_timestep(sigmas[s]))
|
||||||
|
noise_mask = None
|
||||||
|
if denoise_mask is not None:
|
||||||
|
noise_mask = 1.0 - denoise_mask
|
||||||
|
|
||||||
sampler = DDIMSampler(self.model, device=self.device)
|
ddim_callback = None
|
||||||
sampler.make_schedule_timesteps(ddim_timesteps=timesteps, verbose=False)
|
if callback is not None:
|
||||||
z_enc = sampler.stochastic_encode(latent_image, torch.tensor([len(timesteps) - 1] * noise.shape[0]).to(self.device), noise=noise, max_denoise=max_denoise)
|
total_steps = len(timesteps) - 1
|
||||||
samples, _ = sampler.sample_custom(ddim_timesteps=timesteps,
|
ddim_callback = lambda pred_x0, i: callback(i, pred_x0, None, total_steps)
|
||||||
conditioning=positive,
|
|
||||||
batch_size=noise.shape[0],
|
|
||||||
shape=noise.shape[1:],
|
|
||||||
verbose=False,
|
|
||||||
unconditional_guidance_scale=cfg,
|
|
||||||
unconditional_conditioning=negative,
|
|
||||||
eta=0.0,
|
|
||||||
x_T=z_enc,
|
|
||||||
x0=latent_image,
|
|
||||||
img_callback=ddim_callback,
|
|
||||||
denoise_function=sampling_function,
|
|
||||||
extra_args=extra_args,
|
|
||||||
mask=noise_mask,
|
|
||||||
to_zero=sigmas[-1]==0,
|
|
||||||
end_step=sigmas.shape[0] - 1,
|
|
||||||
disable_pbar=disable_pbar)
|
|
||||||
|
|
||||||
|
sampler = DDIMSampler(self.model, device=self.device)
|
||||||
|
sampler.make_schedule_timesteps(ddim_timesteps=timesteps, verbose=False)
|
||||||
|
z_enc = sampler.stochastic_encode(latent_image, torch.tensor([len(timesteps) - 1] * noise.shape[0]).to(self.device), noise=noise, max_denoise=max_denoise)
|
||||||
|
samples, _ = sampler.sample_custom(ddim_timesteps=timesteps,
|
||||||
|
conditioning=positive,
|
||||||
|
batch_size=noise.shape[0],
|
||||||
|
shape=noise.shape[1:],
|
||||||
|
verbose=False,
|
||||||
|
unconditional_guidance_scale=cfg,
|
||||||
|
unconditional_conditioning=negative,
|
||||||
|
eta=0.0,
|
||||||
|
x_T=z_enc,
|
||||||
|
x0=latent_image,
|
||||||
|
img_callback=ddim_callback,
|
||||||
|
denoise_function=self.model_wrap.predict_eps_discrete_timestep,
|
||||||
|
extra_args=extra_args,
|
||||||
|
mask=noise_mask,
|
||||||
|
to_zero=sigmas[-1]==0,
|
||||||
|
end_step=sigmas.shape[0] - 1,
|
||||||
|
disable_pbar=disable_pbar)
|
||||||
|
|
||||||
|
else:
|
||||||
|
extra_args["denoise_mask"] = denoise_mask
|
||||||
|
self.model_k.latent_image = latent_image
|
||||||
|
self.model_k.noise = noise
|
||||||
|
|
||||||
|
if max_denoise:
|
||||||
|
noise = noise * torch.sqrt(1.0 + sigmas[0] ** 2.0)
|
||||||
else:
|
else:
|
||||||
extra_args["denoise_mask"] = denoise_mask
|
noise = noise * sigmas[0]
|
||||||
self.model_k.latent_image = latent_image
|
|
||||||
self.model_k.noise = noise
|
|
||||||
|
|
||||||
if max_denoise:
|
k_callback = None
|
||||||
noise = noise * torch.sqrt(1.0 + sigmas[0] ** 2.0)
|
total_steps = len(sigmas) - 1
|
||||||
else:
|
if callback is not None:
|
||||||
noise = noise * sigmas[0]
|
k_callback = lambda x: callback(x["i"], x["denoised"], x["x"], total_steps)
|
||||||
|
|
||||||
k_callback = None
|
if latent_image is not None:
|
||||||
total_steps = len(sigmas) - 1
|
noise += latent_image
|
||||||
if callback is not None:
|
if self.sampler == "dpm_fast":
|
||||||
k_callback = lambda x: callback(x["i"], x["denoised"], x["x"], total_steps)
|
samples = k_diffusion_sampling.sample_dpm_fast(self.model_k, noise, sigma_min, sigmas[0], total_steps, extra_args=extra_args, callback=k_callback, disable=disable_pbar)
|
||||||
|
elif self.sampler == "dpm_adaptive":
|
||||||
if latent_image is not None:
|
samples = k_diffusion_sampling.sample_dpm_adaptive(self.model_k, noise, sigma_min, sigmas[0], extra_args=extra_args, callback=k_callback, disable=disable_pbar)
|
||||||
noise += latent_image
|
else:
|
||||||
if self.sampler == "dpm_fast":
|
samples = getattr(k_diffusion_sampling, "sample_{}".format(self.sampler))(self.model_k, noise, sigmas, extra_args=extra_args, callback=k_callback, disable=disable_pbar)
|
||||||
samples = k_diffusion_sampling.sample_dpm_fast(self.model_k, noise, sigma_min, sigmas[0], total_steps, extra_args=extra_args, callback=k_callback, disable=disable_pbar)
|
|
||||||
elif self.sampler == "dpm_adaptive":
|
|
||||||
samples = k_diffusion_sampling.sample_dpm_adaptive(self.model_k, noise, sigma_min, sigmas[0], extra_args=extra_args, callback=k_callback, disable=disable_pbar)
|
|
||||||
else:
|
|
||||||
samples = getattr(k_diffusion_sampling, "sample_{}".format(self.sampler))(self.model_k, noise, sigmas, extra_args=extra_args, callback=k_callback, disable=disable_pbar)
|
|
||||||
|
|
||||||
return self.model.process_latent_out(samples.to(torch.float32))
|
return self.model.process_latent_out(samples.to(torch.float32))
|
||||||
|
|||||||
955
comfy/sd.py
955
comfy/sd.py
File diff suppressed because it is too large
Load Diff
@ -5,24 +5,34 @@ import comfy.ops
|
|||||||
import torch
|
import torch
|
||||||
import traceback
|
import traceback
|
||||||
import zipfile
|
import zipfile
|
||||||
|
from . import model_management
|
||||||
|
import contextlib
|
||||||
|
|
||||||
class ClipTokenWeightEncoder:
|
class ClipTokenWeightEncoder:
|
||||||
def encode_token_weights(self, token_weight_pairs):
|
def encode_token_weights(self, token_weight_pairs):
|
||||||
z_empty, _ = self.encode(self.empty_tokens)
|
to_encode = list(self.empty_tokens)
|
||||||
output = []
|
|
||||||
first_pooled = None
|
|
||||||
for x in token_weight_pairs:
|
for x in token_weight_pairs:
|
||||||
tokens = [list(map(lambda a: a[0], x))]
|
tokens = list(map(lambda a: a[0], x))
|
||||||
z, pooled = self.encode(tokens)
|
to_encode.append(tokens)
|
||||||
if first_pooled is None:
|
|
||||||
first_pooled = pooled
|
out, pooled = self.encode(to_encode)
|
||||||
|
z_empty = out[0:1]
|
||||||
|
if pooled.shape[0] > 1:
|
||||||
|
first_pooled = pooled[1:2]
|
||||||
|
else:
|
||||||
|
first_pooled = pooled[0:1]
|
||||||
|
|
||||||
|
output = []
|
||||||
|
for k in range(1, out.shape[0]):
|
||||||
|
z = out[k:k+1]
|
||||||
for i in range(len(z)):
|
for i in range(len(z)):
|
||||||
for j in range(len(z[i])):
|
for j in range(len(z[i])):
|
||||||
weight = x[j][1]
|
weight = token_weight_pairs[k - 1][j][1]
|
||||||
z[i][j] = (z[i][j] - z_empty[0][j]) * weight + z_empty[0][j]
|
z[i][j] = (z[i][j] - z_empty[0][j]) * weight + z_empty[0][j]
|
||||||
output += [z]
|
output.append(z)
|
||||||
|
|
||||||
if (len(output) == 0):
|
if (len(output) == 0):
|
||||||
return self.encode(self.empty_tokens)
|
return z_empty.cpu(), first_pooled.cpu()
|
||||||
return torch.cat(output, dim=-2).cpu(), first_pooled.cpu()
|
return torch.cat(output, dim=-2).cpu(), first_pooled.cpu()
|
||||||
|
|
||||||
class SD1ClipModel(torch.nn.Module, ClipTokenWeightEncoder):
|
class SD1ClipModel(torch.nn.Module, ClipTokenWeightEncoder):
|
||||||
@ -33,32 +43,38 @@ class SD1ClipModel(torch.nn.Module, ClipTokenWeightEncoder):
|
|||||||
"hidden"
|
"hidden"
|
||||||
]
|
]
|
||||||
def __init__(self, version="openai/clip-vit-large-patch14", device="cpu", max_length=77,
|
def __init__(self, version="openai/clip-vit-large-patch14", device="cpu", max_length=77,
|
||||||
freeze=True, layer="last", layer_idx=None, textmodel_json_config=None, textmodel_path=None): # clip-vit-base-patch32
|
freeze=True, layer="last", layer_idx=None, textmodel_json_config=None, textmodel_path=None, dtype=None): # clip-vit-base-patch32
|
||||||
super().__init__()
|
super().__init__()
|
||||||
assert layer in self.LAYERS
|
assert layer in self.LAYERS
|
||||||
|
self.num_layers = 12
|
||||||
if textmodel_path is not None:
|
if textmodel_path is not None:
|
||||||
self.transformer = CLIPTextModel.from_pretrained(textmodel_path)
|
self.transformer = CLIPTextModel.from_pretrained(textmodel_path)
|
||||||
else:
|
else:
|
||||||
if textmodel_json_config is None:
|
if textmodel_json_config is None:
|
||||||
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd1_clip_config.json")
|
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd1_clip_config.json")
|
||||||
config = CLIPTextConfig.from_json_file(textmodel_json_config)
|
config = CLIPTextConfig.from_json_file(textmodel_json_config)
|
||||||
with comfy.ops.use_comfy_ops():
|
self.num_layers = config.num_hidden_layers
|
||||||
|
with comfy.ops.use_comfy_ops(device, dtype):
|
||||||
with modeling_utils.no_init_weights():
|
with modeling_utils.no_init_weights():
|
||||||
self.transformer = CLIPTextModel(config)
|
self.transformer = CLIPTextModel(config)
|
||||||
|
|
||||||
self.device = device
|
if dtype is not None:
|
||||||
|
self.transformer.to(dtype)
|
||||||
self.max_length = max_length
|
self.max_length = max_length
|
||||||
if freeze:
|
if freeze:
|
||||||
self.freeze()
|
self.freeze()
|
||||||
self.layer = layer
|
self.layer = layer
|
||||||
self.layer_idx = None
|
self.layer_idx = None
|
||||||
self.empty_tokens = [[49406] + [49407] * 76]
|
self.empty_tokens = [[49406] + [49407] * 76]
|
||||||
self.text_projection = None
|
self.text_projection = torch.nn.Parameter(torch.eye(self.transformer.get_input_embeddings().weight.shape[1]))
|
||||||
|
self.logit_scale = torch.nn.Parameter(torch.tensor(4.6055))
|
||||||
|
|
||||||
self.layer_norm_hidden_state = True
|
self.layer_norm_hidden_state = True
|
||||||
if layer == "hidden":
|
if layer == "hidden":
|
||||||
assert layer_idx is not None
|
assert layer_idx is not None
|
||||||
assert abs(layer_idx) <= 12
|
assert abs(layer_idx) <= self.num_layers
|
||||||
self.clip_layer(layer_idx)
|
self.clip_layer(layer_idx)
|
||||||
|
self.layer_default = (self.layer, self.layer_idx)
|
||||||
|
|
||||||
def freeze(self):
|
def freeze(self):
|
||||||
self.transformer = self.transformer.eval()
|
self.transformer = self.transformer.eval()
|
||||||
@ -67,21 +83,27 @@ class SD1ClipModel(torch.nn.Module, ClipTokenWeightEncoder):
|
|||||||
param.requires_grad = False
|
param.requires_grad = False
|
||||||
|
|
||||||
def clip_layer(self, layer_idx):
|
def clip_layer(self, layer_idx):
|
||||||
if abs(layer_idx) >= 12:
|
if abs(layer_idx) >= self.num_layers:
|
||||||
self.layer = "last"
|
self.layer = "last"
|
||||||
else:
|
else:
|
||||||
self.layer = "hidden"
|
self.layer = "hidden"
|
||||||
self.layer_idx = layer_idx
|
self.layer_idx = layer_idx
|
||||||
|
|
||||||
|
def reset_clip_layer(self):
|
||||||
|
self.layer = self.layer_default[0]
|
||||||
|
self.layer_idx = self.layer_default[1]
|
||||||
|
|
||||||
def set_up_textual_embeddings(self, tokens, current_embeds):
|
def set_up_textual_embeddings(self, tokens, current_embeds):
|
||||||
out_tokens = []
|
out_tokens = []
|
||||||
next_new_token = token_dict_size = current_embeds.weight.shape[0]
|
next_new_token = token_dict_size = current_embeds.weight.shape[0] - 1
|
||||||
embedding_weights = []
|
embedding_weights = []
|
||||||
|
|
||||||
for x in tokens:
|
for x in tokens:
|
||||||
tokens_temp = []
|
tokens_temp = []
|
||||||
for y in x:
|
for y in x:
|
||||||
if isinstance(y, int):
|
if isinstance(y, int):
|
||||||
|
if y == token_dict_size: #EOS token
|
||||||
|
y = -1
|
||||||
tokens_temp += [y]
|
tokens_temp += [y]
|
||||||
else:
|
else:
|
||||||
if y.shape[0] == current_embeds.weight.shape[1]:
|
if y.shape[0] == current_embeds.weight.shape[1]:
|
||||||
@ -94,41 +116,59 @@ class SD1ClipModel(torch.nn.Module, ClipTokenWeightEncoder):
|
|||||||
tokens_temp += [self.empty_tokens[0][-1]]
|
tokens_temp += [self.empty_tokens[0][-1]]
|
||||||
out_tokens += [tokens_temp]
|
out_tokens += [tokens_temp]
|
||||||
|
|
||||||
|
n = token_dict_size
|
||||||
if len(embedding_weights) > 0:
|
if len(embedding_weights) > 0:
|
||||||
new_embedding = torch.nn.Embedding(next_new_token, current_embeds.weight.shape[1])
|
new_embedding = torch.nn.Embedding(next_new_token + 1, current_embeds.weight.shape[1], device=current_embeds.weight.device, dtype=current_embeds.weight.dtype)
|
||||||
new_embedding.weight[:token_dict_size] = current_embeds.weight[:]
|
new_embedding.weight[:token_dict_size] = current_embeds.weight[:-1]
|
||||||
n = token_dict_size
|
|
||||||
for x in embedding_weights:
|
for x in embedding_weights:
|
||||||
new_embedding.weight[n] = x
|
new_embedding.weight[n] = x
|
||||||
n += 1
|
n += 1
|
||||||
|
new_embedding.weight[n] = current_embeds.weight[-1] #EOS embedding
|
||||||
self.transformer.set_input_embeddings(new_embedding)
|
self.transformer.set_input_embeddings(new_embedding)
|
||||||
return out_tokens
|
|
||||||
|
processed_tokens = []
|
||||||
|
for x in out_tokens:
|
||||||
|
processed_tokens += [list(map(lambda a: n if a == -1 else a, x))] #The EOS token should always be the largest one
|
||||||
|
|
||||||
|
return processed_tokens
|
||||||
|
|
||||||
def forward(self, tokens):
|
def forward(self, tokens):
|
||||||
backup_embeds = self.transformer.get_input_embeddings()
|
backup_embeds = self.transformer.get_input_embeddings()
|
||||||
|
device = backup_embeds.weight.device
|
||||||
tokens = self.set_up_textual_embeddings(tokens, backup_embeds)
|
tokens = self.set_up_textual_embeddings(tokens, backup_embeds)
|
||||||
tokens = torch.LongTensor(tokens).to(self.device)
|
tokens = torch.LongTensor(tokens).to(device)
|
||||||
outputs = self.transformer(input_ids=tokens, output_hidden_states=self.layer=="hidden")
|
|
||||||
self.transformer.set_input_embeddings(backup_embeds)
|
|
||||||
|
|
||||||
if self.layer == "last":
|
if backup_embeds.weight.dtype != torch.float32:
|
||||||
z = outputs.last_hidden_state
|
precision_scope = torch.autocast
|
||||||
elif self.layer == "pooled":
|
|
||||||
z = outputs.pooler_output[:, None, :]
|
|
||||||
else:
|
else:
|
||||||
z = outputs.hidden_states[self.layer_idx]
|
precision_scope = lambda a, b: contextlib.nullcontext(a)
|
||||||
if self.layer_norm_hidden_state:
|
|
||||||
z = self.transformer.text_model.final_layer_norm(z)
|
|
||||||
|
|
||||||
pooled_output = outputs.pooler_output
|
with precision_scope(model_management.get_autocast_device(device), torch.float32):
|
||||||
if self.text_projection is not None:
|
outputs = self.transformer(input_ids=tokens, output_hidden_states=self.layer=="hidden")
|
||||||
pooled_output = pooled_output @ self.text_projection
|
self.transformer.set_input_embeddings(backup_embeds)
|
||||||
return z, pooled_output
|
|
||||||
|
if self.layer == "last":
|
||||||
|
z = outputs.last_hidden_state
|
||||||
|
elif self.layer == "pooled":
|
||||||
|
z = outputs.pooler_output[:, None, :]
|
||||||
|
else:
|
||||||
|
z = outputs.hidden_states[self.layer_idx]
|
||||||
|
if self.layer_norm_hidden_state:
|
||||||
|
z = self.transformer.text_model.final_layer_norm(z)
|
||||||
|
|
||||||
|
pooled_output = outputs.pooler_output
|
||||||
|
if self.text_projection is not None:
|
||||||
|
pooled_output = pooled_output.float().to(self.text_projection.device) @ self.text_projection.float()
|
||||||
|
return z.float(), pooled_output.float()
|
||||||
|
|
||||||
def encode(self, tokens):
|
def encode(self, tokens):
|
||||||
return self(tokens)
|
return self(tokens)
|
||||||
|
|
||||||
def load_sd(self, sd):
|
def load_sd(self, sd):
|
||||||
|
if "text_projection" in sd:
|
||||||
|
self.text_projection[:] = sd.pop("text_projection")
|
||||||
|
if "text_projection.weight" in sd:
|
||||||
|
self.text_projection[:] = sd.pop("text_projection.weight").transpose(0, 1)
|
||||||
return self.transformer.load_state_dict(sd, strict=False)
|
return self.transformer.load_state_dict(sd, strict=False)
|
||||||
|
|
||||||
def parse_parentheses(string):
|
def parse_parentheses(string):
|
||||||
@ -216,7 +256,7 @@ def expand_directory_list(directories):
|
|||||||
dirs.add(root)
|
dirs.add(root)
|
||||||
return list(dirs)
|
return list(dirs)
|
||||||
|
|
||||||
def load_embed(embedding_name, embedding_directory, embedding_size):
|
def load_embed(embedding_name, embedding_directory, embedding_size, embed_key=None):
|
||||||
if isinstance(embedding_directory, str):
|
if isinstance(embedding_directory, str):
|
||||||
embedding_directory = [embedding_directory]
|
embedding_directory = [embedding_directory]
|
||||||
|
|
||||||
@ -275,13 +315,15 @@ def load_embed(embedding_name, embedding_directory, embedding_size):
|
|||||||
continue
|
continue
|
||||||
out_list.append(t.reshape(-1, t.shape[-1]))
|
out_list.append(t.reshape(-1, t.shape[-1]))
|
||||||
embed_out = torch.cat(out_list, dim=0)
|
embed_out = torch.cat(out_list, dim=0)
|
||||||
|
elif embed_key is not None and embed_key in embed:
|
||||||
|
embed_out = embed[embed_key]
|
||||||
else:
|
else:
|
||||||
values = embed.values()
|
values = embed.values()
|
||||||
embed_out = next(iter(values))
|
embed_out = next(iter(values))
|
||||||
return embed_out
|
return embed_out
|
||||||
|
|
||||||
class SD1Tokenizer:
|
class SD1Tokenizer:
|
||||||
def __init__(self, tokenizer_path=None, max_length=77, pad_with_end=True, embedding_directory=None, embedding_size=768):
|
def __init__(self, tokenizer_path=None, max_length=77, pad_with_end=True, embedding_directory=None, embedding_size=768, embedding_key='clip_l'):
|
||||||
if tokenizer_path is None:
|
if tokenizer_path is None:
|
||||||
tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd1_tokenizer")
|
tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd1_tokenizer")
|
||||||
self.tokenizer = CLIPTokenizer.from_pretrained(tokenizer_path)
|
self.tokenizer = CLIPTokenizer.from_pretrained(tokenizer_path)
|
||||||
@ -298,17 +340,18 @@ class SD1Tokenizer:
|
|||||||
self.max_word_length = 8
|
self.max_word_length = 8
|
||||||
self.embedding_identifier = "embedding:"
|
self.embedding_identifier = "embedding:"
|
||||||
self.embedding_size = embedding_size
|
self.embedding_size = embedding_size
|
||||||
|
self.embedding_key = embedding_key
|
||||||
|
|
||||||
def _try_get_embedding(self, embedding_name:str):
|
def _try_get_embedding(self, embedding_name:str):
|
||||||
'''
|
'''
|
||||||
Takes a potential embedding name and tries to retrieve it.
|
Takes a potential embedding name and tries to retrieve it.
|
||||||
Returns a Tuple consisting of the embedding and any leftover string, embedding can be None.
|
Returns a Tuple consisting of the embedding and any leftover string, embedding can be None.
|
||||||
'''
|
'''
|
||||||
embed = load_embed(embedding_name, self.embedding_directory, self.embedding_size)
|
embed = load_embed(embedding_name, self.embedding_directory, self.embedding_size, self.embedding_key)
|
||||||
if embed is None:
|
if embed is None:
|
||||||
stripped = embedding_name.strip(',')
|
stripped = embedding_name.strip(',')
|
||||||
if len(stripped) < len(embedding_name):
|
if len(stripped) < len(embedding_name):
|
||||||
embed = load_embed(stripped, self.embedding_directory, self.embedding_size)
|
embed = load_embed(stripped, self.embedding_directory, self.embedding_size, self.embedding_key)
|
||||||
return (embed, embedding_name[len(stripped):])
|
return (embed, embedding_name[len(stripped):])
|
||||||
return (embed, "")
|
return (embed, "")
|
||||||
|
|
||||||
|
|||||||
@ -3,21 +3,14 @@ import torch
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
class SD2ClipModel(sd1_clip.SD1ClipModel):
|
class SD2ClipModel(sd1_clip.SD1ClipModel):
|
||||||
def __init__(self, arch="ViT-H-14", device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None):
|
def __init__(self, arch="ViT-H-14", device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, textmodel_path=None, dtype=None):
|
||||||
|
if layer == "penultimate":
|
||||||
|
layer="hidden"
|
||||||
|
layer_idx=23
|
||||||
|
|
||||||
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd2_clip_config.json")
|
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd2_clip_config.json")
|
||||||
super().__init__(device=device, freeze=freeze, textmodel_json_config=textmodel_json_config)
|
super().__init__(device=device, freeze=freeze, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, textmodel_path=textmodel_path, dtype=dtype)
|
||||||
self.empty_tokens = [[49406] + [49407] + [0] * 75]
|
self.empty_tokens = [[49406] + [49407] + [0] * 75]
|
||||||
if layer == "last":
|
|
||||||
pass
|
|
||||||
elif layer == "penultimate":
|
|
||||||
layer_idx = -1
|
|
||||||
self.clip_layer(layer_idx)
|
|
||||||
elif self.layer == "hidden":
|
|
||||||
assert layer_idx is not None
|
|
||||||
assert abs(layer_idx) < 24
|
|
||||||
self.clip_layer(layer_idx)
|
|
||||||
else:
|
|
||||||
raise NotImplementedError()
|
|
||||||
|
|
||||||
def clip_layer(self, layer_idx):
|
def clip_layer(self, layer_idx):
|
||||||
if layer_idx < 0:
|
if layer_idx < 0:
|
||||||
|
|||||||
@ -17,7 +17,7 @@
|
|||||||
"num_attention_heads": 16,
|
"num_attention_heads": 16,
|
||||||
"num_hidden_layers": 24,
|
"num_hidden_layers": 24,
|
||||||
"pad_token_id": 1,
|
"pad_token_id": 1,
|
||||||
"projection_dim": 512,
|
"projection_dim": 1024,
|
||||||
"torch_dtype": "float32",
|
"torch_dtype": "float32",
|
||||||
"vocab_size": 49408
|
"vocab_size": 49408
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,42 +3,22 @@ import torch
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
class SDXLClipG(sd1_clip.SD1ClipModel):
|
class SDXLClipG(sd1_clip.SD1ClipModel):
|
||||||
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None):
|
def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, textmodel_path=None, dtype=None):
|
||||||
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_config_bigg.json")
|
if layer == "penultimate":
|
||||||
super().__init__(device=device, freeze=freeze, textmodel_json_config=textmodel_json_config)
|
layer="hidden"
|
||||||
self.empty_tokens = [[49406] + [49407] + [0] * 75]
|
layer_idx=-2
|
||||||
self.text_projection = torch.nn.Parameter(torch.empty(1280, 1280))
|
|
||||||
self.layer_norm_hidden_state = False
|
|
||||||
if layer == "last":
|
|
||||||
pass
|
|
||||||
elif layer == "penultimate":
|
|
||||||
layer_idx = -1
|
|
||||||
self.clip_layer(layer_idx)
|
|
||||||
elif self.layer == "hidden":
|
|
||||||
assert layer_idx is not None
|
|
||||||
assert abs(layer_idx) < 32
|
|
||||||
self.clip_layer(layer_idx)
|
|
||||||
else:
|
|
||||||
raise NotImplementedError()
|
|
||||||
|
|
||||||
def clip_layer(self, layer_idx):
|
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_config_bigg.json")
|
||||||
if layer_idx < 0:
|
super().__init__(device=device, freeze=freeze, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, textmodel_path=textmodel_path, dtype=dtype)
|
||||||
layer_idx -= 1 #The real last layer of SD2.x clip is the penultimate one. The last one might contain garbage.
|
self.empty_tokens = [[49406] + [49407] + [0] * 75]
|
||||||
if abs(layer_idx) >= 32:
|
self.layer_norm_hidden_state = False
|
||||||
self.layer = "hidden"
|
|
||||||
self.layer_idx = -2
|
|
||||||
else:
|
|
||||||
self.layer = "hidden"
|
|
||||||
self.layer_idx = layer_idx
|
|
||||||
|
|
||||||
def load_sd(self, sd):
|
def load_sd(self, sd):
|
||||||
if "text_projection" in sd:
|
|
||||||
self.text_projection[:] = sd.pop("text_projection")
|
|
||||||
return super().load_sd(sd)
|
return super().load_sd(sd)
|
||||||
|
|
||||||
class SDXLClipGTokenizer(sd1_clip.SD1Tokenizer):
|
class SDXLClipGTokenizer(sd1_clip.SD1Tokenizer):
|
||||||
def __init__(self, tokenizer_path=None, embedding_directory=None):
|
def __init__(self, tokenizer_path=None, embedding_directory=None):
|
||||||
super().__init__(tokenizer_path, pad_with_end=False, embedding_directory=embedding_directory, embedding_size=1280)
|
super().__init__(tokenizer_path, pad_with_end=False, embedding_directory=embedding_directory, embedding_size=1280, embedding_key='clip_g')
|
||||||
|
|
||||||
|
|
||||||
class SDXLTokenizer(sd1_clip.SD1Tokenizer):
|
class SDXLTokenizer(sd1_clip.SD1Tokenizer):
|
||||||
@ -56,16 +36,20 @@ class SDXLTokenizer(sd1_clip.SD1Tokenizer):
|
|||||||
return self.clip_g.untokenize(token_weight_pair)
|
return self.clip_g.untokenize(token_weight_pair)
|
||||||
|
|
||||||
class SDXLClipModel(torch.nn.Module):
|
class SDXLClipModel(torch.nn.Module):
|
||||||
def __init__(self, device="cpu"):
|
def __init__(self, device="cpu", dtype=None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.clip_l = sd1_clip.SD1ClipModel(layer="hidden", layer_idx=11, device=device)
|
self.clip_l = sd1_clip.SD1ClipModel(layer="hidden", layer_idx=11, device=device, dtype=dtype)
|
||||||
self.clip_l.layer_norm_hidden_state = False
|
self.clip_l.layer_norm_hidden_state = False
|
||||||
self.clip_g = SDXLClipG(device=device)
|
self.clip_g = SDXLClipG(device=device, dtype=dtype)
|
||||||
|
|
||||||
def clip_layer(self, layer_idx):
|
def clip_layer(self, layer_idx):
|
||||||
self.clip_l.clip_layer(layer_idx)
|
self.clip_l.clip_layer(layer_idx)
|
||||||
self.clip_g.clip_layer(layer_idx)
|
self.clip_g.clip_layer(layer_idx)
|
||||||
|
|
||||||
|
def reset_clip_layer(self):
|
||||||
|
self.clip_g.reset_clip_layer()
|
||||||
|
self.clip_l.reset_clip_layer()
|
||||||
|
|
||||||
def encode_token_weights(self, token_weight_pairs):
|
def encode_token_weights(self, token_weight_pairs):
|
||||||
token_weight_pairs_g = token_weight_pairs["g"]
|
token_weight_pairs_g = token_weight_pairs["g"]
|
||||||
token_weight_pairs_l = token_weight_pairs["l"]
|
token_weight_pairs_l = token_weight_pairs["l"]
|
||||||
@ -80,13 +64,16 @@ class SDXLClipModel(torch.nn.Module):
|
|||||||
return self.clip_l.load_sd(sd)
|
return self.clip_l.load_sd(sd)
|
||||||
|
|
||||||
class SDXLRefinerClipModel(torch.nn.Module):
|
class SDXLRefinerClipModel(torch.nn.Module):
|
||||||
def __init__(self, device="cpu"):
|
def __init__(self, device="cpu", dtype=None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.clip_g = SDXLClipG(device=device)
|
self.clip_g = SDXLClipG(device=device, dtype=dtype)
|
||||||
|
|
||||||
def clip_layer(self, layer_idx):
|
def clip_layer(self, layer_idx):
|
||||||
self.clip_g.clip_layer(layer_idx)
|
self.clip_g.clip_layer(layer_idx)
|
||||||
|
|
||||||
|
def reset_clip_layer(self):
|
||||||
|
self.clip_g.reset_clip_layer()
|
||||||
|
|
||||||
def encode_token_weights(self, token_weight_pairs):
|
def encode_token_weights(self, token_weight_pairs):
|
||||||
token_weight_pairs_g = token_weight_pairs["g"]
|
token_weight_pairs_g = token_weight_pairs["g"]
|
||||||
g_out, g_pooled = self.clip_g.encode_token_weights(token_weight_pairs_g)
|
g_out, g_pooled = self.clip_g.encode_token_weights(token_weight_pairs_g)
|
||||||
|
|||||||
@ -53,13 +53,13 @@ class SD20(supported_models_base.BASE):
|
|||||||
|
|
||||||
latent_format = latent_formats.SD15
|
latent_format = latent_formats.SD15
|
||||||
|
|
||||||
def v_prediction(self, state_dict):
|
def model_type(self, state_dict, prefix=""):
|
||||||
if self.unet_config["in_channels"] == 4: #SD2.0 inpainting models are not v prediction
|
if self.unet_config["in_channels"] == 4: #SD2.0 inpainting models are not v prediction
|
||||||
k = "model.diffusion_model.output_blocks.11.1.transformer_blocks.0.norm1.bias"
|
k = "{}output_blocks.11.1.transformer_blocks.0.norm1.bias".format(prefix)
|
||||||
out = state_dict[k]
|
out = state_dict[k]
|
||||||
if torch.std(out, unbiased=False) > 0.09: # not sure how well this will actually work. I guess we will find out.
|
if torch.std(out, unbiased=False) > 0.09: # not sure how well this will actually work. I guess we will find out.
|
||||||
return True
|
return model_base.ModelType.V_PREDICTION
|
||||||
return False
|
return model_base.ModelType.EPS
|
||||||
|
|
||||||
def process_clip_state_dict(self, state_dict):
|
def process_clip_state_dict(self, state_dict):
|
||||||
state_dict = utils.transformers_convert(state_dict, "cond_stage_model.model.", "cond_stage_model.transformer.text_model.", 24)
|
state_dict = utils.transformers_convert(state_dict, "cond_stage_model.model.", "cond_stage_model.transformer.text_model.", 24)
|
||||||
@ -68,7 +68,7 @@ class SD20(supported_models_base.BASE):
|
|||||||
def process_clip_state_dict_for_saving(self, state_dict):
|
def process_clip_state_dict_for_saving(self, state_dict):
|
||||||
replace_prefix = {}
|
replace_prefix = {}
|
||||||
replace_prefix[""] = "cond_stage_model.model."
|
replace_prefix[""] = "cond_stage_model.model."
|
||||||
state_dict = supported_models_base.state_dict_prefix_replace(state_dict, replace_prefix)
|
state_dict = utils.state_dict_prefix_replace(state_dict, replace_prefix)
|
||||||
state_dict = diffusers_convert.convert_text_enc_state_dict_v20(state_dict)
|
state_dict = diffusers_convert.convert_text_enc_state_dict_v20(state_dict)
|
||||||
return state_dict
|
return state_dict
|
||||||
|
|
||||||
@ -109,8 +109,8 @@ class SDXLRefiner(supported_models_base.BASE):
|
|||||||
|
|
||||||
latent_format = latent_formats.SDXL
|
latent_format = latent_formats.SDXL
|
||||||
|
|
||||||
def get_model(self, state_dict):
|
def get_model(self, state_dict, prefix="", device=None):
|
||||||
return model_base.SDXLRefiner(self)
|
return model_base.SDXLRefiner(self, device=device)
|
||||||
|
|
||||||
def process_clip_state_dict(self, state_dict):
|
def process_clip_state_dict(self, state_dict):
|
||||||
keys_to_replace = {}
|
keys_to_replace = {}
|
||||||
@ -118,15 +118,18 @@ class SDXLRefiner(supported_models_base.BASE):
|
|||||||
|
|
||||||
state_dict = utils.transformers_convert(state_dict, "conditioner.embedders.0.model.", "cond_stage_model.clip_g.transformer.text_model.", 32)
|
state_dict = utils.transformers_convert(state_dict, "conditioner.embedders.0.model.", "cond_stage_model.clip_g.transformer.text_model.", 32)
|
||||||
keys_to_replace["conditioner.embedders.0.model.text_projection"] = "cond_stage_model.clip_g.text_projection"
|
keys_to_replace["conditioner.embedders.0.model.text_projection"] = "cond_stage_model.clip_g.text_projection"
|
||||||
|
keys_to_replace["conditioner.embedders.0.model.logit_scale"] = "cond_stage_model.clip_g.logit_scale"
|
||||||
|
|
||||||
state_dict = supported_models_base.state_dict_key_replace(state_dict, keys_to_replace)
|
state_dict = utils.state_dict_key_replace(state_dict, keys_to_replace)
|
||||||
return state_dict
|
return state_dict
|
||||||
|
|
||||||
def process_clip_state_dict_for_saving(self, state_dict):
|
def process_clip_state_dict_for_saving(self, state_dict):
|
||||||
replace_prefix = {}
|
replace_prefix = {}
|
||||||
state_dict_g = diffusers_convert.convert_text_enc_state_dict_v20(state_dict, "clip_g")
|
state_dict_g = diffusers_convert.convert_text_enc_state_dict_v20(state_dict, "clip_g")
|
||||||
|
if "clip_g.transformer.text_model.embeddings.position_ids" in state_dict_g:
|
||||||
|
state_dict_g.pop("clip_g.transformer.text_model.embeddings.position_ids")
|
||||||
replace_prefix["clip_g"] = "conditioner.embedders.0.model"
|
replace_prefix["clip_g"] = "conditioner.embedders.0.model"
|
||||||
state_dict_g = supported_models_base.state_dict_prefix_replace(state_dict_g, replace_prefix)
|
state_dict_g = utils.state_dict_prefix_replace(state_dict_g, replace_prefix)
|
||||||
return state_dict_g
|
return state_dict_g
|
||||||
|
|
||||||
def clip_target(self):
|
def clip_target(self):
|
||||||
@ -143,8 +146,17 @@ class SDXL(supported_models_base.BASE):
|
|||||||
|
|
||||||
latent_format = latent_formats.SDXL
|
latent_format = latent_formats.SDXL
|
||||||
|
|
||||||
def get_model(self, state_dict):
|
def model_type(self, state_dict, prefix=""):
|
||||||
return model_base.SDXL(self)
|
if "v_pred" in state_dict:
|
||||||
|
return model_base.ModelType.V_PREDICTION
|
||||||
|
else:
|
||||||
|
return model_base.ModelType.EPS
|
||||||
|
|
||||||
|
def get_model(self, state_dict, prefix="", device=None):
|
||||||
|
out = model_base.SDXL(self, model_type=self.model_type(state_dict, prefix), device=device)
|
||||||
|
if self.inpaint_model():
|
||||||
|
out.set_inpaint()
|
||||||
|
return out
|
||||||
|
|
||||||
def process_clip_state_dict(self, state_dict):
|
def process_clip_state_dict(self, state_dict):
|
||||||
keys_to_replace = {}
|
keys_to_replace = {}
|
||||||
@ -153,22 +165,25 @@ class SDXL(supported_models_base.BASE):
|
|||||||
replace_prefix["conditioner.embedders.0.transformer.text_model"] = "cond_stage_model.clip_l.transformer.text_model"
|
replace_prefix["conditioner.embedders.0.transformer.text_model"] = "cond_stage_model.clip_l.transformer.text_model"
|
||||||
state_dict = utils.transformers_convert(state_dict, "conditioner.embedders.1.model.", "cond_stage_model.clip_g.transformer.text_model.", 32)
|
state_dict = utils.transformers_convert(state_dict, "conditioner.embedders.1.model.", "cond_stage_model.clip_g.transformer.text_model.", 32)
|
||||||
keys_to_replace["conditioner.embedders.1.model.text_projection"] = "cond_stage_model.clip_g.text_projection"
|
keys_to_replace["conditioner.embedders.1.model.text_projection"] = "cond_stage_model.clip_g.text_projection"
|
||||||
|
keys_to_replace["conditioner.embedders.1.model.logit_scale"] = "cond_stage_model.clip_g.logit_scale"
|
||||||
|
|
||||||
state_dict = supported_models_base.state_dict_prefix_replace(state_dict, replace_prefix)
|
state_dict = utils.state_dict_prefix_replace(state_dict, replace_prefix)
|
||||||
state_dict = supported_models_base.state_dict_key_replace(state_dict, keys_to_replace)
|
state_dict = utils.state_dict_key_replace(state_dict, keys_to_replace)
|
||||||
return state_dict
|
return state_dict
|
||||||
|
|
||||||
def process_clip_state_dict_for_saving(self, state_dict):
|
def process_clip_state_dict_for_saving(self, state_dict):
|
||||||
replace_prefix = {}
|
replace_prefix = {}
|
||||||
keys_to_replace = {}
|
keys_to_replace = {}
|
||||||
state_dict_g = diffusers_convert.convert_text_enc_state_dict_v20(state_dict, "clip_g")
|
state_dict_g = diffusers_convert.convert_text_enc_state_dict_v20(state_dict, "clip_g")
|
||||||
|
if "clip_g.transformer.text_model.embeddings.position_ids" in state_dict_g:
|
||||||
|
state_dict_g.pop("clip_g.transformer.text_model.embeddings.position_ids")
|
||||||
for k in state_dict:
|
for k in state_dict:
|
||||||
if k.startswith("clip_l"):
|
if k.startswith("clip_l"):
|
||||||
state_dict_g[k] = state_dict[k]
|
state_dict_g[k] = state_dict[k]
|
||||||
|
|
||||||
replace_prefix["clip_g"] = "conditioner.embedders.1.model"
|
replace_prefix["clip_g"] = "conditioner.embedders.1.model"
|
||||||
replace_prefix["clip_l"] = "conditioner.embedders.0"
|
replace_prefix["clip_l"] = "conditioner.embedders.0"
|
||||||
state_dict_g = supported_models_base.state_dict_prefix_replace(state_dict_g, replace_prefix)
|
state_dict_g = utils.state_dict_prefix_replace(state_dict_g, replace_prefix)
|
||||||
return state_dict_g
|
return state_dict_g
|
||||||
|
|
||||||
def clip_target(self):
|
def clip_target(self):
|
||||||
|
|||||||
@ -1,21 +1,7 @@
|
|||||||
import torch
|
import torch
|
||||||
from . import model_base
|
from . import model_base
|
||||||
from . import utils
|
from . import utils
|
||||||
|
from . import latent_formats
|
||||||
|
|
||||||
def state_dict_key_replace(state_dict, keys_to_replace):
|
|
||||||
for x in keys_to_replace:
|
|
||||||
if x in state_dict:
|
|
||||||
state_dict[keys_to_replace[x]] = state_dict.pop(x)
|
|
||||||
return state_dict
|
|
||||||
|
|
||||||
def state_dict_prefix_replace(state_dict, replace_prefix):
|
|
||||||
for rp in replace_prefix:
|
|
||||||
replace = list(map(lambda a: (a, "{}{}".format(replace_prefix[rp], a[len(rp):])), filter(lambda a: a.startswith(rp), state_dict.keys())))
|
|
||||||
for x in replace:
|
|
||||||
state_dict[x[1]] = state_dict.pop(x[0])
|
|
||||||
return state_dict
|
|
||||||
|
|
||||||
|
|
||||||
class ClipTarget:
|
class ClipTarget:
|
||||||
def __init__(self, tokenizer, clip):
|
def __init__(self, tokenizer, clip):
|
||||||
@ -33,6 +19,8 @@ class BASE:
|
|||||||
clip_prefix = []
|
clip_prefix = []
|
||||||
clip_vision_prefix = None
|
clip_vision_prefix = None
|
||||||
noise_aug_config = None
|
noise_aug_config = None
|
||||||
|
beta_schedule = "linear"
|
||||||
|
latent_format = latent_formats.LatentFormat
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def matches(s, unet_config):
|
def matches(s, unet_config):
|
||||||
@ -41,8 +29,8 @@ class BASE:
|
|||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def v_prediction(self, state_dict):
|
def model_type(self, state_dict, prefix=""):
|
||||||
return False
|
return model_base.ModelType.EPS
|
||||||
|
|
||||||
def inpaint_model(self):
|
def inpaint_model(self):
|
||||||
return self.unet_config["in_channels"] > 4
|
return self.unet_config["in_channels"] > 4
|
||||||
@ -53,26 +41,27 @@ class BASE:
|
|||||||
for x in self.unet_extra_config:
|
for x in self.unet_extra_config:
|
||||||
self.unet_config[x] = self.unet_extra_config[x]
|
self.unet_config[x] = self.unet_extra_config[x]
|
||||||
|
|
||||||
def get_model(self, state_dict):
|
def get_model(self, state_dict, prefix="", device=None):
|
||||||
if self.inpaint_model():
|
if self.noise_aug_config is not None:
|
||||||
return model_base.SDInpaint(self, v_prediction=self.v_prediction(state_dict))
|
out = model_base.SD21UNCLIP(self, self.noise_aug_config, model_type=self.model_type(state_dict, prefix), device=device)
|
||||||
elif self.noise_aug_config is not None:
|
|
||||||
return model_base.SD21UNCLIP(self, self.noise_aug_config, v_prediction=self.v_prediction(state_dict))
|
|
||||||
else:
|
else:
|
||||||
return model_base.BaseModel(self, v_prediction=self.v_prediction(state_dict))
|
out = model_base.BaseModel(self, model_type=self.model_type(state_dict, prefix), device=device)
|
||||||
|
if self.inpaint_model():
|
||||||
|
out.set_inpaint()
|
||||||
|
return out
|
||||||
|
|
||||||
def process_clip_state_dict(self, state_dict):
|
def process_clip_state_dict(self, state_dict):
|
||||||
return state_dict
|
return state_dict
|
||||||
|
|
||||||
def process_clip_state_dict_for_saving(self, state_dict):
|
def process_clip_state_dict_for_saving(self, state_dict):
|
||||||
replace_prefix = {"": "cond_stage_model."}
|
replace_prefix = {"": "cond_stage_model."}
|
||||||
return state_dict_prefix_replace(state_dict, replace_prefix)
|
return utils.state_dict_prefix_replace(state_dict, replace_prefix)
|
||||||
|
|
||||||
def process_unet_state_dict_for_saving(self, state_dict):
|
def process_unet_state_dict_for_saving(self, state_dict):
|
||||||
replace_prefix = {"": "model.diffusion_model."}
|
replace_prefix = {"": "model.diffusion_model."}
|
||||||
return state_dict_prefix_replace(state_dict, replace_prefix)
|
return utils.state_dict_prefix_replace(state_dict, replace_prefix)
|
||||||
|
|
||||||
def process_vae_state_dict_for_saving(self, state_dict):
|
def process_vae_state_dict_for_saving(self, state_dict):
|
||||||
replace_prefix = {"": "first_stage_model."}
|
replace_prefix = {"": "first_stage_model."}
|
||||||
return state_dict_prefix_replace(state_dict, replace_prefix)
|
return utils.state_dict_prefix_replace(state_dict, replace_prefix)
|
||||||
|
|
||||||
|
|||||||
@ -101,17 +101,30 @@ class ResnetBlock(nn.Module):
|
|||||||
|
|
||||||
|
|
||||||
class Adapter(nn.Module):
|
class Adapter(nn.Module):
|
||||||
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64, ksize=3, sk=False, use_conv=True):
|
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64, ksize=3, sk=False, use_conv=True, xl=True):
|
||||||
super(Adapter, self).__init__()
|
super(Adapter, self).__init__()
|
||||||
self.unshuffle = nn.PixelUnshuffle(8)
|
self.unshuffle_amount = 8
|
||||||
|
resblock_no_downsample = []
|
||||||
|
resblock_downsample = [3, 2, 1]
|
||||||
|
self.xl = xl
|
||||||
|
if self.xl:
|
||||||
|
self.unshuffle_amount = 16
|
||||||
|
resblock_no_downsample = [1]
|
||||||
|
resblock_downsample = [2]
|
||||||
|
|
||||||
|
self.input_channels = cin // (self.unshuffle_amount * self.unshuffle_amount)
|
||||||
|
self.unshuffle = nn.PixelUnshuffle(self.unshuffle_amount)
|
||||||
self.channels = channels
|
self.channels = channels
|
||||||
self.nums_rb = nums_rb
|
self.nums_rb = nums_rb
|
||||||
self.body = []
|
self.body = []
|
||||||
for i in range(len(channels)):
|
for i in range(len(channels)):
|
||||||
for j in range(nums_rb):
|
for j in range(nums_rb):
|
||||||
if (i != 0) and (j == 0):
|
if (i in resblock_downsample) and (j == 0):
|
||||||
self.body.append(
|
self.body.append(
|
||||||
ResnetBlock(channels[i - 1], channels[i], down=True, ksize=ksize, sk=sk, use_conv=use_conv))
|
ResnetBlock(channels[i - 1], channels[i], down=True, ksize=ksize, sk=sk, use_conv=use_conv))
|
||||||
|
elif (i in resblock_no_downsample) and (j == 0):
|
||||||
|
self.body.append(
|
||||||
|
ResnetBlock(channels[i - 1], channels[i], down=False, ksize=ksize, sk=sk, use_conv=use_conv))
|
||||||
else:
|
else:
|
||||||
self.body.append(
|
self.body.append(
|
||||||
ResnetBlock(channels[i], channels[i], down=False, ksize=ksize, sk=sk, use_conv=use_conv))
|
ResnetBlock(channels[i], channels[i], down=False, ksize=ksize, sk=sk, use_conv=use_conv))
|
||||||
@ -128,6 +141,16 @@ class Adapter(nn.Module):
|
|||||||
for j in range(self.nums_rb):
|
for j in range(self.nums_rb):
|
||||||
idx = i * self.nums_rb + j
|
idx = i * self.nums_rb + j
|
||||||
x = self.body[idx](x)
|
x = self.body[idx](x)
|
||||||
|
if self.xl:
|
||||||
|
features.append(None)
|
||||||
|
if i == 0:
|
||||||
|
features.append(None)
|
||||||
|
features.append(None)
|
||||||
|
if i == 2:
|
||||||
|
features.append(None)
|
||||||
|
else:
|
||||||
|
features.append(None)
|
||||||
|
features.append(None)
|
||||||
features.append(x)
|
features.append(x)
|
||||||
|
|
||||||
return features
|
return features
|
||||||
@ -241,10 +264,14 @@ class extractor(nn.Module):
|
|||||||
class Adapter_light(nn.Module):
|
class Adapter_light(nn.Module):
|
||||||
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64):
|
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64):
|
||||||
super(Adapter_light, self).__init__()
|
super(Adapter_light, self).__init__()
|
||||||
self.unshuffle = nn.PixelUnshuffle(8)
|
self.unshuffle_amount = 8
|
||||||
|
self.unshuffle = nn.PixelUnshuffle(self.unshuffle_amount)
|
||||||
|
self.input_channels = cin // (self.unshuffle_amount * self.unshuffle_amount)
|
||||||
self.channels = channels
|
self.channels = channels
|
||||||
self.nums_rb = nums_rb
|
self.nums_rb = nums_rb
|
||||||
self.body = []
|
self.body = []
|
||||||
|
self.xl = False
|
||||||
|
|
||||||
for i in range(len(channels)):
|
for i in range(len(channels)):
|
||||||
if i == 0:
|
if i == 0:
|
||||||
self.body.append(extractor(in_c=cin, inter_c=channels[i]//4, out_c=channels[i], nums_rb=nums_rb, down=False))
|
self.body.append(extractor(in_c=cin, inter_c=channels[i]//4, out_c=channels[i], nums_rb=nums_rb, down=False))
|
||||||
@ -259,6 +286,8 @@ class Adapter_light(nn.Module):
|
|||||||
features = []
|
features = []
|
||||||
for i in range(len(self.channels)):
|
for i in range(len(self.channels)):
|
||||||
x = self.body[i](x)
|
x = self.body[i](x)
|
||||||
|
features.append(None)
|
||||||
|
features.append(None)
|
||||||
features.append(x)
|
features.append(x)
|
||||||
|
|
||||||
return features
|
return features
|
||||||
|
|||||||
196
comfy/utils.py
196
comfy/utils.py
@ -4,18 +4,20 @@ import struct
|
|||||||
import comfy.checkpoint_pickle
|
import comfy.checkpoint_pickle
|
||||||
import safetensors.torch
|
import safetensors.torch
|
||||||
|
|
||||||
def load_torch_file(ckpt, safe_load=False):
|
def load_torch_file(ckpt, safe_load=False, device=None):
|
||||||
|
if device is None:
|
||||||
|
device = torch.device("cpu")
|
||||||
if ckpt.lower().endswith(".safetensors"):
|
if ckpt.lower().endswith(".safetensors"):
|
||||||
sd = safetensors.torch.load_file(ckpt, device="cpu")
|
sd = safetensors.torch.load_file(ckpt, device=device.type)
|
||||||
else:
|
else:
|
||||||
if safe_load:
|
if safe_load:
|
||||||
if not 'weights_only' in torch.load.__code__.co_varnames:
|
if not 'weights_only' in torch.load.__code__.co_varnames:
|
||||||
print("Warning torch.load doesn't support weights_only on this pytorch version, loading unsafely.")
|
print("Warning torch.load doesn't support weights_only on this pytorch version, loading unsafely.")
|
||||||
safe_load = False
|
safe_load = False
|
||||||
if safe_load:
|
if safe_load:
|
||||||
pl_sd = torch.load(ckpt, map_location="cpu", weights_only=True)
|
pl_sd = torch.load(ckpt, map_location=device, weights_only=True)
|
||||||
else:
|
else:
|
||||||
pl_sd = torch.load(ckpt, map_location="cpu", pickle_module=comfy.checkpoint_pickle)
|
pl_sd = torch.load(ckpt, map_location=device, pickle_module=comfy.checkpoint_pickle)
|
||||||
if "global_step" in pl_sd:
|
if "global_step" in pl_sd:
|
||||||
print(f"Global Step: {pl_sd['global_step']}")
|
print(f"Global Step: {pl_sd['global_step']}")
|
||||||
if "state_dict" in pl_sd:
|
if "state_dict" in pl_sd:
|
||||||
@ -30,6 +32,27 @@ def save_torch_file(sd, ckpt, metadata=None):
|
|||||||
else:
|
else:
|
||||||
safetensors.torch.save_file(sd, ckpt)
|
safetensors.torch.save_file(sd, ckpt)
|
||||||
|
|
||||||
|
def calculate_parameters(sd, prefix=""):
|
||||||
|
params = 0
|
||||||
|
for k in sd.keys():
|
||||||
|
if k.startswith(prefix):
|
||||||
|
params += sd[k].nelement()
|
||||||
|
return params
|
||||||
|
|
||||||
|
def state_dict_key_replace(state_dict, keys_to_replace):
|
||||||
|
for x in keys_to_replace:
|
||||||
|
if x in state_dict:
|
||||||
|
state_dict[keys_to_replace[x]] = state_dict.pop(x)
|
||||||
|
return state_dict
|
||||||
|
|
||||||
|
def state_dict_prefix_replace(state_dict, replace_prefix):
|
||||||
|
for rp in replace_prefix:
|
||||||
|
replace = list(map(lambda a: (a, "{}{}".format(replace_prefix[rp], a[len(rp):])), filter(lambda a: a.startswith(rp), state_dict.keys())))
|
||||||
|
for x in replace:
|
||||||
|
state_dict[x[1]] = state_dict.pop(x[0])
|
||||||
|
return state_dict
|
||||||
|
|
||||||
|
|
||||||
def transformers_convert(sd, prefix_from, prefix_to, number):
|
def transformers_convert(sd, prefix_from, prefix_to, number):
|
||||||
keys_to_replace = {
|
keys_to_replace = {
|
||||||
"{}positional_embedding": "{}embeddings.position_embedding.weight",
|
"{}positional_embedding": "{}embeddings.position_embedding.weight",
|
||||||
@ -70,6 +93,157 @@ def transformers_convert(sd, prefix_from, prefix_to, number):
|
|||||||
sd[k_to] = weights[shape_from*x:shape_from*(x + 1)]
|
sd[k_to] = weights[shape_from*x:shape_from*(x + 1)]
|
||||||
return sd
|
return sd
|
||||||
|
|
||||||
|
UNET_MAP_ATTENTIONS = {
|
||||||
|
"proj_in.weight",
|
||||||
|
"proj_in.bias",
|
||||||
|
"proj_out.weight",
|
||||||
|
"proj_out.bias",
|
||||||
|
"norm.weight",
|
||||||
|
"norm.bias",
|
||||||
|
}
|
||||||
|
|
||||||
|
TRANSFORMER_BLOCKS = {
|
||||||
|
"norm1.weight",
|
||||||
|
"norm1.bias",
|
||||||
|
"norm2.weight",
|
||||||
|
"norm2.bias",
|
||||||
|
"norm3.weight",
|
||||||
|
"norm3.bias",
|
||||||
|
"attn1.to_q.weight",
|
||||||
|
"attn1.to_k.weight",
|
||||||
|
"attn1.to_v.weight",
|
||||||
|
"attn1.to_out.0.weight",
|
||||||
|
"attn1.to_out.0.bias",
|
||||||
|
"attn2.to_q.weight",
|
||||||
|
"attn2.to_k.weight",
|
||||||
|
"attn2.to_v.weight",
|
||||||
|
"attn2.to_out.0.weight",
|
||||||
|
"attn2.to_out.0.bias",
|
||||||
|
"ff.net.0.proj.weight",
|
||||||
|
"ff.net.0.proj.bias",
|
||||||
|
"ff.net.2.weight",
|
||||||
|
"ff.net.2.bias",
|
||||||
|
}
|
||||||
|
|
||||||
|
UNET_MAP_RESNET = {
|
||||||
|
"in_layers.2.weight": "conv1.weight",
|
||||||
|
"in_layers.2.bias": "conv1.bias",
|
||||||
|
"emb_layers.1.weight": "time_emb_proj.weight",
|
||||||
|
"emb_layers.1.bias": "time_emb_proj.bias",
|
||||||
|
"out_layers.3.weight": "conv2.weight",
|
||||||
|
"out_layers.3.bias": "conv2.bias",
|
||||||
|
"skip_connection.weight": "conv_shortcut.weight",
|
||||||
|
"skip_connection.bias": "conv_shortcut.bias",
|
||||||
|
"in_layers.0.weight": "norm1.weight",
|
||||||
|
"in_layers.0.bias": "norm1.bias",
|
||||||
|
"out_layers.0.weight": "norm2.weight",
|
||||||
|
"out_layers.0.bias": "norm2.bias",
|
||||||
|
}
|
||||||
|
|
||||||
|
UNET_MAP_BASIC = {
|
||||||
|
("label_emb.0.0.weight", "class_embedding.linear_1.weight"),
|
||||||
|
("label_emb.0.0.bias", "class_embedding.linear_1.bias"),
|
||||||
|
("label_emb.0.2.weight", "class_embedding.linear_2.weight"),
|
||||||
|
("label_emb.0.2.bias", "class_embedding.linear_2.bias"),
|
||||||
|
("label_emb.0.0.weight", "add_embedding.linear_1.weight"),
|
||||||
|
("label_emb.0.0.bias", "add_embedding.linear_1.bias"),
|
||||||
|
("label_emb.0.2.weight", "add_embedding.linear_2.weight"),
|
||||||
|
("label_emb.0.2.bias", "add_embedding.linear_2.bias"),
|
||||||
|
("input_blocks.0.0.weight", "conv_in.weight"),
|
||||||
|
("input_blocks.0.0.bias", "conv_in.bias"),
|
||||||
|
("out.0.weight", "conv_norm_out.weight"),
|
||||||
|
("out.0.bias", "conv_norm_out.bias"),
|
||||||
|
("out.2.weight", "conv_out.weight"),
|
||||||
|
("out.2.bias", "conv_out.bias"),
|
||||||
|
("time_embed.0.weight", "time_embedding.linear_1.weight"),
|
||||||
|
("time_embed.0.bias", "time_embedding.linear_1.bias"),
|
||||||
|
("time_embed.2.weight", "time_embedding.linear_2.weight"),
|
||||||
|
("time_embed.2.bias", "time_embedding.linear_2.bias")
|
||||||
|
}
|
||||||
|
|
||||||
|
def unet_to_diffusers(unet_config):
|
||||||
|
num_res_blocks = unet_config["num_res_blocks"]
|
||||||
|
attention_resolutions = unet_config["attention_resolutions"]
|
||||||
|
channel_mult = unet_config["channel_mult"]
|
||||||
|
transformer_depth = unet_config["transformer_depth"]
|
||||||
|
num_blocks = len(channel_mult)
|
||||||
|
if isinstance(num_res_blocks, int):
|
||||||
|
num_res_blocks = [num_res_blocks] * num_blocks
|
||||||
|
if isinstance(transformer_depth, int):
|
||||||
|
transformer_depth = [transformer_depth] * num_blocks
|
||||||
|
|
||||||
|
transformers_per_layer = []
|
||||||
|
res = 1
|
||||||
|
for i in range(num_blocks):
|
||||||
|
transformers = 0
|
||||||
|
if res in attention_resolutions:
|
||||||
|
transformers = transformer_depth[i]
|
||||||
|
transformers_per_layer.append(transformers)
|
||||||
|
res *= 2
|
||||||
|
|
||||||
|
transformers_mid = unet_config.get("transformer_depth_middle", transformer_depth[-1])
|
||||||
|
|
||||||
|
diffusers_unet_map = {}
|
||||||
|
for x in range(num_blocks):
|
||||||
|
n = 1 + (num_res_blocks[x] + 1) * x
|
||||||
|
for i in range(num_res_blocks[x]):
|
||||||
|
for b in UNET_MAP_RESNET:
|
||||||
|
diffusers_unet_map["down_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.{}".format(n, b)
|
||||||
|
if transformers_per_layer[x] > 0:
|
||||||
|
for b in UNET_MAP_ATTENTIONS:
|
||||||
|
diffusers_unet_map["down_blocks.{}.attentions.{}.{}".format(x, i, b)] = "input_blocks.{}.1.{}".format(n, b)
|
||||||
|
for t in range(transformers_per_layer[x]):
|
||||||
|
for b in TRANSFORMER_BLOCKS:
|
||||||
|
diffusers_unet_map["down_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "input_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
|
||||||
|
n += 1
|
||||||
|
for k in ["weight", "bias"]:
|
||||||
|
diffusers_unet_map["down_blocks.{}.downsamplers.0.conv.{}".format(x, k)] = "input_blocks.{}.0.op.{}".format(n, k)
|
||||||
|
|
||||||
|
i = 0
|
||||||
|
for b in UNET_MAP_ATTENTIONS:
|
||||||
|
diffusers_unet_map["mid_block.attentions.{}.{}".format(i, b)] = "middle_block.1.{}".format(b)
|
||||||
|
for t in range(transformers_mid):
|
||||||
|
for b in TRANSFORMER_BLOCKS:
|
||||||
|
diffusers_unet_map["mid_block.attentions.{}.transformer_blocks.{}.{}".format(i, t, b)] = "middle_block.1.transformer_blocks.{}.{}".format(t, b)
|
||||||
|
|
||||||
|
for i, n in enumerate([0, 2]):
|
||||||
|
for b in UNET_MAP_RESNET:
|
||||||
|
diffusers_unet_map["mid_block.resnets.{}.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.{}".format(n, b)
|
||||||
|
|
||||||
|
num_res_blocks = list(reversed(num_res_blocks))
|
||||||
|
transformers_per_layer = list(reversed(transformers_per_layer))
|
||||||
|
for x in range(num_blocks):
|
||||||
|
n = (num_res_blocks[x] + 1) * x
|
||||||
|
l = num_res_blocks[x] + 1
|
||||||
|
for i in range(l):
|
||||||
|
c = 0
|
||||||
|
for b in UNET_MAP_RESNET:
|
||||||
|
diffusers_unet_map["up_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "output_blocks.{}.0.{}".format(n, b)
|
||||||
|
c += 1
|
||||||
|
if transformers_per_layer[x] > 0:
|
||||||
|
c += 1
|
||||||
|
for b in UNET_MAP_ATTENTIONS:
|
||||||
|
diffusers_unet_map["up_blocks.{}.attentions.{}.{}".format(x, i, b)] = "output_blocks.{}.1.{}".format(n, b)
|
||||||
|
for t in range(transformers_per_layer[x]):
|
||||||
|
for b in TRANSFORMER_BLOCKS:
|
||||||
|
diffusers_unet_map["up_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "output_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
|
||||||
|
if i == l - 1:
|
||||||
|
for k in ["weight", "bias"]:
|
||||||
|
diffusers_unet_map["up_blocks.{}.upsamplers.0.conv.{}".format(x, k)] = "output_blocks.{}.{}.conv.{}".format(n, c, k)
|
||||||
|
n += 1
|
||||||
|
|
||||||
|
for k in UNET_MAP_BASIC:
|
||||||
|
diffusers_unet_map[k[1]] = k[0]
|
||||||
|
|
||||||
|
return diffusers_unet_map
|
||||||
|
|
||||||
|
def repeat_to_batch_size(tensor, batch_size):
|
||||||
|
if tensor.shape[0] > batch_size:
|
||||||
|
return tensor[:batch_size]
|
||||||
|
elif tensor.shape[0] < batch_size:
|
||||||
|
return tensor.repeat([math.ceil(batch_size / tensor.shape[0])] + [1] * (len(tensor.shape) - 1))[:batch_size]
|
||||||
|
return tensor
|
||||||
|
|
||||||
def convert_sd_to(state_dict, dtype):
|
def convert_sd_to(state_dict, dtype):
|
||||||
keys = list(state_dict.keys())
|
keys = list(state_dict.keys())
|
||||||
for k in keys:
|
for k in keys:
|
||||||
@ -84,6 +258,20 @@ def safetensors_header(safetensors_path, max_size=100*1024*1024):
|
|||||||
return None
|
return None
|
||||||
return f.read(length_of_header)
|
return f.read(length_of_header)
|
||||||
|
|
||||||
|
def set_attr(obj, attr, value):
|
||||||
|
attrs = attr.split(".")
|
||||||
|
for name in attrs[:-1]:
|
||||||
|
obj = getattr(obj, name)
|
||||||
|
prev = getattr(obj, attrs[-1])
|
||||||
|
setattr(obj, attrs[-1], torch.nn.Parameter(value))
|
||||||
|
del prev
|
||||||
|
|
||||||
|
def get_attr(obj, attr):
|
||||||
|
attrs = attr.split(".")
|
||||||
|
for name in attrs:
|
||||||
|
obj = getattr(obj, name)
|
||||||
|
return obj
|
||||||
|
|
||||||
def bislerp(samples, width, height):
|
def bislerp(samples, width, height):
|
||||||
def slerp(b1, b2, r):
|
def slerp(b1, b2, r):
|
||||||
'''slerps batches b1, b2 according to ratio r, batches should be flat e.g. NxC'''
|
'''slerps batches b1, b2 according to ratio r, batches should be flat e.g. NxC'''
|
||||||
|
|||||||
1182
comfy_extras/chainner_models/architecture/DAT.py
Normal file
1182
comfy_extras/chainner_models/architecture/DAT.py
Normal file
File diff suppressed because it is too large
Load Diff
201
comfy_extras/chainner_models/architecture/LICENSE-DAT
Normal file
201
comfy_extras/chainner_models/architecture/LICENSE-DAT
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
201
comfy_extras/chainner_models/architecture/LICENSE-SCUNet
Normal file
201
comfy_extras/chainner_models/architecture/LICENSE-SCUNet
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright 2022 Kai Zhang (cskaizhang@gmail.com, https://cszn.github.io/). All rights reserved.
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
@ -1,161 +0,0 @@
|
|||||||
## creative commons
|
|
||||||
|
|
||||||
# Attribution-NonCommercial 4.0 International
|
|
||||||
|
|
||||||
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
|
|
||||||
|
|
||||||
### Using Creative Commons Public Licenses
|
|
||||||
|
|
||||||
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
|
||||||
|
|
||||||
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
|
|
||||||
|
|
||||||
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
|
|
||||||
|
|
||||||
## Creative Commons Attribution-NonCommercial 4.0 International Public License
|
|
||||||
|
|
||||||
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
|
||||||
|
|
||||||
### Section 1 – Definitions.
|
|
||||||
|
|
||||||
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
|
||||||
|
|
||||||
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
|
||||||
|
|
||||||
c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
|
||||||
|
|
||||||
d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
|
||||||
|
|
||||||
e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
|
||||||
|
|
||||||
f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
|
||||||
|
|
||||||
g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
|
||||||
|
|
||||||
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
|
|
||||||
|
|
||||||
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
|
|
||||||
|
|
||||||
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
|
||||||
|
|
||||||
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
|
||||||
|
|
||||||
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
|
||||||
|
|
||||||
### Section 2 – Scope.
|
|
||||||
|
|
||||||
a. ___License grant.___
|
|
||||||
|
|
||||||
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
|
||||||
|
|
||||||
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
|
||||||
|
|
||||||
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
|
||||||
|
|
||||||
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
|
||||||
|
|
||||||
3. __Term.__ The term of this Public License is specified in Section 6(a).
|
|
||||||
|
|
||||||
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
|
||||||
|
|
||||||
5. __Downstream recipients.__
|
|
||||||
|
|
||||||
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
|
||||||
|
|
||||||
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
|
||||||
|
|
||||||
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
|
||||||
|
|
||||||
b. ___Other rights.___
|
|
||||||
|
|
||||||
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
|
||||||
|
|
||||||
2. Patent and trademark rights are not licensed under this Public License.
|
|
||||||
|
|
||||||
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
|
|
||||||
|
|
||||||
### Section 3 – License Conditions.
|
|
||||||
|
|
||||||
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
|
||||||
|
|
||||||
a. ___Attribution.___
|
|
||||||
|
|
||||||
1. If You Share the Licensed Material (including in modified form), You must:
|
|
||||||
|
|
||||||
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
|
||||||
|
|
||||||
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
|
||||||
|
|
||||||
ii. a copyright notice;
|
|
||||||
|
|
||||||
iii. a notice that refers to this Public License;
|
|
||||||
|
|
||||||
iv. a notice that refers to the disclaimer of warranties;
|
|
||||||
|
|
||||||
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
|
||||||
|
|
||||||
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
|
||||||
|
|
||||||
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
|
||||||
|
|
||||||
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
|
||||||
|
|
||||||
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
|
||||||
|
|
||||||
4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
|
|
||||||
|
|
||||||
### Section 4 – Sui Generis Database Rights.
|
|
||||||
|
|
||||||
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
|
||||||
|
|
||||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
|
|
||||||
|
|
||||||
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
|
|
||||||
|
|
||||||
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
|
||||||
|
|
||||||
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
|
||||||
|
|
||||||
### Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
|
||||||
|
|
||||||
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
|
|
||||||
|
|
||||||
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
|
|
||||||
|
|
||||||
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
|
||||||
|
|
||||||
### Section 6 – Term and Termination.
|
|
||||||
|
|
||||||
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
|
||||||
|
|
||||||
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
|
||||||
|
|
||||||
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
|
||||||
|
|
||||||
2. upon express reinstatement by the Licensor.
|
|
||||||
|
|
||||||
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
|
||||||
|
|
||||||
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
|
||||||
|
|
||||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
|
||||||
|
|
||||||
### Section 7 – Other Terms and Conditions.
|
|
||||||
|
|
||||||
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
|
||||||
|
|
||||||
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
|
||||||
|
|
||||||
### Section 8 – Interpretation.
|
|
||||||
|
|
||||||
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
|
||||||
|
|
||||||
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
|
||||||
|
|
||||||
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
|
||||||
|
|
||||||
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
|
||||||
|
|
||||||
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
|
||||||
>
|
|
||||||
> Creative Commons may be contacted at creativecommons.org
|
|
||||||
File diff suppressed because it is too large
Load Diff
@ -56,7 +56,17 @@ class OmniSR(nn.Module):
|
|||||||
residual_layer = []
|
residual_layer = []
|
||||||
self.res_num = res_num
|
self.res_num = res_num
|
||||||
|
|
||||||
self.window_size = 8 # we can just assume this for now, but there's probably a way to calculate it (just need to get the sqrt of the right layer)
|
if (
|
||||||
|
"residual_layer.0.residual_layer.0.layer.2.fn.rel_pos_bias.weight"
|
||||||
|
in state_dict.keys()
|
||||||
|
):
|
||||||
|
rel_pos_bias_weight = state_dict[
|
||||||
|
"residual_layer.0.residual_layer.0.layer.2.fn.rel_pos_bias.weight"
|
||||||
|
].shape[0]
|
||||||
|
self.window_size = int((math.sqrt(rel_pos_bias_weight) + 1) / 2)
|
||||||
|
else:
|
||||||
|
self.window_size = 8
|
||||||
|
|
||||||
self.up_scale = up_scale
|
self.up_scale = up_scale
|
||||||
|
|
||||||
for _ in range(res_num):
|
for _ in range(res_num):
|
||||||
|
|||||||
455
comfy_extras/chainner_models/architecture/SCUNet.py
Normal file
455
comfy_extras/chainner_models/architecture/SCUNet.py
Normal file
@ -0,0 +1,455 @@
|
|||||||
|
# pylint: skip-file
|
||||||
|
# -----------------------------------------------------------------------------------
|
||||||
|
# SCUNet: Practical Blind Denoising via Swin-Conv-UNet and Data Synthesis, https://arxiv.org/abs/2203.13278
|
||||||
|
# Zhang, Kai and Li, Yawei and Liang, Jingyun and Cao, Jiezhang and Zhang, Yulun and Tang, Hao and Timofte, Radu and Van Gool, Luc
|
||||||
|
# -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
from einops import rearrange
|
||||||
|
from einops.layers.torch import Rearrange
|
||||||
|
|
||||||
|
from .timm.drop import DropPath
|
||||||
|
from .timm.weight_init import trunc_normal_
|
||||||
|
|
||||||
|
|
||||||
|
# Borrowed from https://github.com/cszn/SCUNet/blob/main/models/network_scunet.py
|
||||||
|
class WMSA(nn.Module):
|
||||||
|
"""Self-attention module in Swin Transformer"""
|
||||||
|
|
||||||
|
def __init__(self, input_dim, output_dim, head_dim, window_size, type):
|
||||||
|
super(WMSA, self).__init__()
|
||||||
|
self.input_dim = input_dim
|
||||||
|
self.output_dim = output_dim
|
||||||
|
self.head_dim = head_dim
|
||||||
|
self.scale = self.head_dim**-0.5
|
||||||
|
self.n_heads = input_dim // head_dim
|
||||||
|
self.window_size = window_size
|
||||||
|
self.type = type
|
||||||
|
self.embedding_layer = nn.Linear(self.input_dim, 3 * self.input_dim, bias=True)
|
||||||
|
|
||||||
|
self.relative_position_params = nn.Parameter(
|
||||||
|
torch.zeros((2 * window_size - 1) * (2 * window_size - 1), self.n_heads)
|
||||||
|
)
|
||||||
|
# TODO recover
|
||||||
|
# self.relative_position_params = nn.Parameter(torch.zeros(self.n_heads, 2 * window_size - 1, 2 * window_size -1))
|
||||||
|
self.relative_position_params = nn.Parameter(
|
||||||
|
torch.zeros((2 * window_size - 1) * (2 * window_size - 1), self.n_heads)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.linear = nn.Linear(self.input_dim, self.output_dim)
|
||||||
|
|
||||||
|
trunc_normal_(self.relative_position_params, std=0.02)
|
||||||
|
self.relative_position_params = torch.nn.Parameter(
|
||||||
|
self.relative_position_params.view(
|
||||||
|
2 * window_size - 1, 2 * window_size - 1, self.n_heads
|
||||||
|
)
|
||||||
|
.transpose(1, 2)
|
||||||
|
.transpose(0, 1)
|
||||||
|
)
|
||||||
|
|
||||||
|
def generate_mask(self, h, w, p, shift):
|
||||||
|
"""generating the mask of SW-MSA
|
||||||
|
Args:
|
||||||
|
shift: shift parameters in CyclicShift.
|
||||||
|
Returns:
|
||||||
|
attn_mask: should be (1 1 w p p),
|
||||||
|
"""
|
||||||
|
# supporting square.
|
||||||
|
attn_mask = torch.zeros(
|
||||||
|
h,
|
||||||
|
w,
|
||||||
|
p,
|
||||||
|
p,
|
||||||
|
p,
|
||||||
|
p,
|
||||||
|
dtype=torch.bool,
|
||||||
|
device=self.relative_position_params.device,
|
||||||
|
)
|
||||||
|
if self.type == "W":
|
||||||
|
return attn_mask
|
||||||
|
|
||||||
|
s = p - shift
|
||||||
|
attn_mask[-1, :, :s, :, s:, :] = True
|
||||||
|
attn_mask[-1, :, s:, :, :s, :] = True
|
||||||
|
attn_mask[:, -1, :, :s, :, s:] = True
|
||||||
|
attn_mask[:, -1, :, s:, :, :s] = True
|
||||||
|
attn_mask = rearrange(
|
||||||
|
attn_mask, "w1 w2 p1 p2 p3 p4 -> 1 1 (w1 w2) (p1 p2) (p3 p4)"
|
||||||
|
)
|
||||||
|
return attn_mask
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
"""Forward pass of Window Multi-head Self-attention module.
|
||||||
|
Args:
|
||||||
|
x: input tensor with shape of [b h w c];
|
||||||
|
attn_mask: attention mask, fill -inf where the value is True;
|
||||||
|
Returns:
|
||||||
|
output: tensor shape [b h w c]
|
||||||
|
"""
|
||||||
|
if self.type != "W":
|
||||||
|
x = torch.roll(
|
||||||
|
x,
|
||||||
|
shifts=(-(self.window_size // 2), -(self.window_size // 2)),
|
||||||
|
dims=(1, 2),
|
||||||
|
)
|
||||||
|
|
||||||
|
x = rearrange(
|
||||||
|
x,
|
||||||
|
"b (w1 p1) (w2 p2) c -> b w1 w2 p1 p2 c",
|
||||||
|
p1=self.window_size,
|
||||||
|
p2=self.window_size,
|
||||||
|
)
|
||||||
|
h_windows = x.size(1)
|
||||||
|
w_windows = x.size(2)
|
||||||
|
# square validation
|
||||||
|
# assert h_windows == w_windows
|
||||||
|
|
||||||
|
x = rearrange(
|
||||||
|
x,
|
||||||
|
"b w1 w2 p1 p2 c -> b (w1 w2) (p1 p2) c",
|
||||||
|
p1=self.window_size,
|
||||||
|
p2=self.window_size,
|
||||||
|
)
|
||||||
|
qkv = self.embedding_layer(x)
|
||||||
|
q, k, v = rearrange(
|
||||||
|
qkv, "b nw np (threeh c) -> threeh b nw np c", c=self.head_dim
|
||||||
|
).chunk(3, dim=0)
|
||||||
|
sim = torch.einsum("hbwpc,hbwqc->hbwpq", q, k) * self.scale
|
||||||
|
# Adding learnable relative embedding
|
||||||
|
sim = sim + rearrange(self.relative_embedding(), "h p q -> h 1 1 p q")
|
||||||
|
# Using Attn Mask to distinguish different subwindows.
|
||||||
|
if self.type != "W":
|
||||||
|
attn_mask = self.generate_mask(
|
||||||
|
h_windows, w_windows, self.window_size, shift=self.window_size // 2
|
||||||
|
)
|
||||||
|
sim = sim.masked_fill_(attn_mask, float("-inf"))
|
||||||
|
|
||||||
|
probs = nn.functional.softmax(sim, dim=-1)
|
||||||
|
output = torch.einsum("hbwij,hbwjc->hbwic", probs, v)
|
||||||
|
output = rearrange(output, "h b w p c -> b w p (h c)")
|
||||||
|
output = self.linear(output)
|
||||||
|
output = rearrange(
|
||||||
|
output,
|
||||||
|
"b (w1 w2) (p1 p2) c -> b (w1 p1) (w2 p2) c",
|
||||||
|
w1=h_windows,
|
||||||
|
p1=self.window_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.type != "W":
|
||||||
|
output = torch.roll(
|
||||||
|
output,
|
||||||
|
shifts=(self.window_size // 2, self.window_size // 2),
|
||||||
|
dims=(1, 2),
|
||||||
|
)
|
||||||
|
|
||||||
|
return output
|
||||||
|
|
||||||
|
def relative_embedding(self):
|
||||||
|
cord = torch.tensor(
|
||||||
|
np.array(
|
||||||
|
[
|
||||||
|
[i, j]
|
||||||
|
for i in range(self.window_size)
|
||||||
|
for j in range(self.window_size)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
relation = cord[:, None, :] - cord[None, :, :] + self.window_size - 1
|
||||||
|
# negative is allowed
|
||||||
|
return self.relative_position_params[
|
||||||
|
:, relation[:, :, 0].long(), relation[:, :, 1].long()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class Block(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
input_dim,
|
||||||
|
output_dim,
|
||||||
|
head_dim,
|
||||||
|
window_size,
|
||||||
|
drop_path,
|
||||||
|
type="W",
|
||||||
|
input_resolution=None,
|
||||||
|
):
|
||||||
|
"""SwinTransformer Block"""
|
||||||
|
super(Block, self).__init__()
|
||||||
|
self.input_dim = input_dim
|
||||||
|
self.output_dim = output_dim
|
||||||
|
assert type in ["W", "SW"]
|
||||||
|
self.type = type
|
||||||
|
if input_resolution <= window_size:
|
||||||
|
self.type = "W"
|
||||||
|
|
||||||
|
self.ln1 = nn.LayerNorm(input_dim)
|
||||||
|
self.msa = WMSA(input_dim, input_dim, head_dim, window_size, self.type)
|
||||||
|
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
||||||
|
self.ln2 = nn.LayerNorm(input_dim)
|
||||||
|
self.mlp = nn.Sequential(
|
||||||
|
nn.Linear(input_dim, 4 * input_dim),
|
||||||
|
nn.GELU(),
|
||||||
|
nn.Linear(4 * input_dim, output_dim),
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
x = x + self.drop_path(self.msa(self.ln1(x)))
|
||||||
|
x = x + self.drop_path(self.mlp(self.ln2(x)))
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
class ConvTransBlock(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
conv_dim,
|
||||||
|
trans_dim,
|
||||||
|
head_dim,
|
||||||
|
window_size,
|
||||||
|
drop_path,
|
||||||
|
type="W",
|
||||||
|
input_resolution=None,
|
||||||
|
):
|
||||||
|
"""SwinTransformer and Conv Block"""
|
||||||
|
super(ConvTransBlock, self).__init__()
|
||||||
|
self.conv_dim = conv_dim
|
||||||
|
self.trans_dim = trans_dim
|
||||||
|
self.head_dim = head_dim
|
||||||
|
self.window_size = window_size
|
||||||
|
self.drop_path = drop_path
|
||||||
|
self.type = type
|
||||||
|
self.input_resolution = input_resolution
|
||||||
|
|
||||||
|
assert self.type in ["W", "SW"]
|
||||||
|
if self.input_resolution <= self.window_size:
|
||||||
|
self.type = "W"
|
||||||
|
|
||||||
|
self.trans_block = Block(
|
||||||
|
self.trans_dim,
|
||||||
|
self.trans_dim,
|
||||||
|
self.head_dim,
|
||||||
|
self.window_size,
|
||||||
|
self.drop_path,
|
||||||
|
self.type,
|
||||||
|
self.input_resolution,
|
||||||
|
)
|
||||||
|
self.conv1_1 = nn.Conv2d(
|
||||||
|
self.conv_dim + self.trans_dim,
|
||||||
|
self.conv_dim + self.trans_dim,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
bias=True,
|
||||||
|
)
|
||||||
|
self.conv1_2 = nn.Conv2d(
|
||||||
|
self.conv_dim + self.trans_dim,
|
||||||
|
self.conv_dim + self.trans_dim,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
bias=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.conv_block = nn.Sequential(
|
||||||
|
nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False),
|
||||||
|
nn.ReLU(True),
|
||||||
|
nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
conv_x, trans_x = torch.split(
|
||||||
|
self.conv1_1(x), (self.conv_dim, self.trans_dim), dim=1
|
||||||
|
)
|
||||||
|
conv_x = self.conv_block(conv_x) + conv_x
|
||||||
|
trans_x = Rearrange("b c h w -> b h w c")(trans_x)
|
||||||
|
trans_x = self.trans_block(trans_x)
|
||||||
|
trans_x = Rearrange("b h w c -> b c h w")(trans_x)
|
||||||
|
res = self.conv1_2(torch.cat((conv_x, trans_x), dim=1))
|
||||||
|
x = x + res
|
||||||
|
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
class SCUNet(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
state_dict,
|
||||||
|
in_nc=3,
|
||||||
|
config=[4, 4, 4, 4, 4, 4, 4],
|
||||||
|
dim=64,
|
||||||
|
drop_path_rate=0.0,
|
||||||
|
input_resolution=256,
|
||||||
|
):
|
||||||
|
super(SCUNet, self).__init__()
|
||||||
|
self.model_arch = "SCUNet"
|
||||||
|
self.sub_type = "SR"
|
||||||
|
|
||||||
|
self.num_filters: int = 0
|
||||||
|
|
||||||
|
self.state = state_dict
|
||||||
|
self.config = config
|
||||||
|
self.dim = dim
|
||||||
|
self.head_dim = 32
|
||||||
|
self.window_size = 8
|
||||||
|
|
||||||
|
self.in_nc = in_nc
|
||||||
|
self.out_nc = self.in_nc
|
||||||
|
self.scale = 1
|
||||||
|
self.supports_fp16 = True
|
||||||
|
|
||||||
|
# drop path rate for each layer
|
||||||
|
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(config))]
|
||||||
|
|
||||||
|
self.m_head = [nn.Conv2d(in_nc, dim, 3, 1, 1, bias=False)]
|
||||||
|
|
||||||
|
begin = 0
|
||||||
|
self.m_down1 = [
|
||||||
|
ConvTransBlock(
|
||||||
|
dim // 2,
|
||||||
|
dim // 2,
|
||||||
|
self.head_dim,
|
||||||
|
self.window_size,
|
||||||
|
dpr[i + begin],
|
||||||
|
"W" if not i % 2 else "SW",
|
||||||
|
input_resolution,
|
||||||
|
)
|
||||||
|
for i in range(config[0])
|
||||||
|
] + [nn.Conv2d(dim, 2 * dim, 2, 2, 0, bias=False)]
|
||||||
|
|
||||||
|
begin += config[0]
|
||||||
|
self.m_down2 = [
|
||||||
|
ConvTransBlock(
|
||||||
|
dim,
|
||||||
|
dim,
|
||||||
|
self.head_dim,
|
||||||
|
self.window_size,
|
||||||
|
dpr[i + begin],
|
||||||
|
"W" if not i % 2 else "SW",
|
||||||
|
input_resolution // 2,
|
||||||
|
)
|
||||||
|
for i in range(config[1])
|
||||||
|
] + [nn.Conv2d(2 * dim, 4 * dim, 2, 2, 0, bias=False)]
|
||||||
|
|
||||||
|
begin += config[1]
|
||||||
|
self.m_down3 = [
|
||||||
|
ConvTransBlock(
|
||||||
|
2 * dim,
|
||||||
|
2 * dim,
|
||||||
|
self.head_dim,
|
||||||
|
self.window_size,
|
||||||
|
dpr[i + begin],
|
||||||
|
"W" if not i % 2 else "SW",
|
||||||
|
input_resolution // 4,
|
||||||
|
)
|
||||||
|
for i in range(config[2])
|
||||||
|
] + [nn.Conv2d(4 * dim, 8 * dim, 2, 2, 0, bias=False)]
|
||||||
|
|
||||||
|
begin += config[2]
|
||||||
|
self.m_body = [
|
||||||
|
ConvTransBlock(
|
||||||
|
4 * dim,
|
||||||
|
4 * dim,
|
||||||
|
self.head_dim,
|
||||||
|
self.window_size,
|
||||||
|
dpr[i + begin],
|
||||||
|
"W" if not i % 2 else "SW",
|
||||||
|
input_resolution // 8,
|
||||||
|
)
|
||||||
|
for i in range(config[3])
|
||||||
|
]
|
||||||
|
|
||||||
|
begin += config[3]
|
||||||
|
self.m_up3 = [
|
||||||
|
nn.ConvTranspose2d(8 * dim, 4 * dim, 2, 2, 0, bias=False),
|
||||||
|
] + [
|
||||||
|
ConvTransBlock(
|
||||||
|
2 * dim,
|
||||||
|
2 * dim,
|
||||||
|
self.head_dim,
|
||||||
|
self.window_size,
|
||||||
|
dpr[i + begin],
|
||||||
|
"W" if not i % 2 else "SW",
|
||||||
|
input_resolution // 4,
|
||||||
|
)
|
||||||
|
for i in range(config[4])
|
||||||
|
]
|
||||||
|
|
||||||
|
begin += config[4]
|
||||||
|
self.m_up2 = [
|
||||||
|
nn.ConvTranspose2d(4 * dim, 2 * dim, 2, 2, 0, bias=False),
|
||||||
|
] + [
|
||||||
|
ConvTransBlock(
|
||||||
|
dim,
|
||||||
|
dim,
|
||||||
|
self.head_dim,
|
||||||
|
self.window_size,
|
||||||
|
dpr[i + begin],
|
||||||
|
"W" if not i % 2 else "SW",
|
||||||
|
input_resolution // 2,
|
||||||
|
)
|
||||||
|
for i in range(config[5])
|
||||||
|
]
|
||||||
|
|
||||||
|
begin += config[5]
|
||||||
|
self.m_up1 = [
|
||||||
|
nn.ConvTranspose2d(2 * dim, dim, 2, 2, 0, bias=False),
|
||||||
|
] + [
|
||||||
|
ConvTransBlock(
|
||||||
|
dim // 2,
|
||||||
|
dim // 2,
|
||||||
|
self.head_dim,
|
||||||
|
self.window_size,
|
||||||
|
dpr[i + begin],
|
||||||
|
"W" if not i % 2 else "SW",
|
||||||
|
input_resolution,
|
||||||
|
)
|
||||||
|
for i in range(config[6])
|
||||||
|
]
|
||||||
|
|
||||||
|
self.m_tail = [nn.Conv2d(dim, in_nc, 3, 1, 1, bias=False)]
|
||||||
|
|
||||||
|
self.m_head = nn.Sequential(*self.m_head)
|
||||||
|
self.m_down1 = nn.Sequential(*self.m_down1)
|
||||||
|
self.m_down2 = nn.Sequential(*self.m_down2)
|
||||||
|
self.m_down3 = nn.Sequential(*self.m_down3)
|
||||||
|
self.m_body = nn.Sequential(*self.m_body)
|
||||||
|
self.m_up3 = nn.Sequential(*self.m_up3)
|
||||||
|
self.m_up2 = nn.Sequential(*self.m_up2)
|
||||||
|
self.m_up1 = nn.Sequential(*self.m_up1)
|
||||||
|
self.m_tail = nn.Sequential(*self.m_tail)
|
||||||
|
# self.apply(self._init_weights)
|
||||||
|
self.load_state_dict(state_dict, strict=True)
|
||||||
|
|
||||||
|
def check_image_size(self, x):
|
||||||
|
_, _, h, w = x.size()
|
||||||
|
mod_pad_h = (64 - h % 64) % 64
|
||||||
|
mod_pad_w = (64 - w % 64) % 64
|
||||||
|
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "reflect")
|
||||||
|
return x
|
||||||
|
|
||||||
|
def forward(self, x0):
|
||||||
|
h, w = x0.size()[-2:]
|
||||||
|
x0 = self.check_image_size(x0)
|
||||||
|
|
||||||
|
x1 = self.m_head(x0)
|
||||||
|
x2 = self.m_down1(x1)
|
||||||
|
x3 = self.m_down2(x2)
|
||||||
|
x4 = self.m_down3(x3)
|
||||||
|
x = self.m_body(x4)
|
||||||
|
x = self.m_up3(x + x4)
|
||||||
|
x = self.m_up2(x + x3)
|
||||||
|
x = self.m_up1(x + x2)
|
||||||
|
x = self.m_tail(x + x1)
|
||||||
|
|
||||||
|
x = x[:, :, :h, :w]
|
||||||
|
return x
|
||||||
|
|
||||||
|
def _init_weights(self, m):
|
||||||
|
if isinstance(m, nn.Linear):
|
||||||
|
trunc_normal_(m.weight, std=0.02)
|
||||||
|
if m.bias is not None:
|
||||||
|
nn.init.constant_(m.bias, 0)
|
||||||
|
elif isinstance(m, nn.LayerNorm):
|
||||||
|
nn.init.constant_(m.bias, 0)
|
||||||
|
nn.init.constant_(m.weight, 1.0)
|
||||||
@ -60,7 +60,6 @@ class SPSRNet(nn.Module):
|
|||||||
self.out_nc: int = self.state["f_HR_conv1.0.bias"].shape[0]
|
self.out_nc: int = self.state["f_HR_conv1.0.bias"].shape[0]
|
||||||
|
|
||||||
self.scale = self.get_scale(4)
|
self.scale = self.get_scale(4)
|
||||||
print(self.scale)
|
|
||||||
self.num_filters: int = self.state["model.0.weight"].shape[0]
|
self.num_filters: int = self.state["model.0.weight"].shape[0]
|
||||||
|
|
||||||
self.supports_fp16 = True
|
self.supports_fp16 = True
|
||||||
|
|||||||
@ -846,6 +846,7 @@ class SwinIR(nn.Module):
|
|||||||
num_in_ch = in_chans
|
num_in_ch = in_chans
|
||||||
num_out_ch = in_chans
|
num_out_ch = in_chans
|
||||||
supports_fp16 = True
|
supports_fp16 = True
|
||||||
|
self.start_unshuffle = 1
|
||||||
|
|
||||||
self.model_arch = "SwinIR"
|
self.model_arch = "SwinIR"
|
||||||
self.sub_type = "SR"
|
self.sub_type = "SR"
|
||||||
@ -874,6 +875,11 @@ class SwinIR(nn.Module):
|
|||||||
else 64
|
else 64
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if "conv_first.1.weight" in self.state:
|
||||||
|
self.state["conv_first.weight"] = self.state.pop("conv_first.1.weight")
|
||||||
|
self.state["conv_first.bias"] = self.state.pop("conv_first.1.bias")
|
||||||
|
self.start_unshuffle = round(math.sqrt(self.state["conv_first.weight"].shape[1] // 3))
|
||||||
|
|
||||||
num_in_ch = self.state["conv_first.weight"].shape[1]
|
num_in_ch = self.state["conv_first.weight"].shape[1]
|
||||||
in_chans = num_in_ch
|
in_chans = num_in_ch
|
||||||
if "conv_last.weight" in state_keys:
|
if "conv_last.weight" in state_keys:
|
||||||
@ -968,10 +974,11 @@ class SwinIR(nn.Module):
|
|||||||
self.depths = depths
|
self.depths = depths
|
||||||
self.window_size = window_size
|
self.window_size = window_size
|
||||||
self.mlp_ratio = mlp_ratio
|
self.mlp_ratio = mlp_ratio
|
||||||
self.scale = upscale
|
self.scale = upscale / self.start_unshuffle
|
||||||
self.upsampler = upsampler
|
self.upsampler = upsampler
|
||||||
self.img_size = img_size
|
self.img_size = img_size
|
||||||
self.img_range = img_range
|
self.img_range = img_range
|
||||||
|
self.resi_connection = resi_connection
|
||||||
|
|
||||||
self.supports_fp16 = False # Too much weirdness to support this at the moment
|
self.supports_fp16 = False # Too much weirdness to support this at the moment
|
||||||
self.supports_bfp16 = True
|
self.supports_bfp16 = True
|
||||||
@ -1100,6 +1107,9 @@ class SwinIR(nn.Module):
|
|||||||
self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||||
if self.upscale == 4:
|
if self.upscale == 4:
|
||||||
self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||||
|
elif self.upscale == 8:
|
||||||
|
self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||||
|
self.conv_up3 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||||
self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||||
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
||||||
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
||||||
@ -1156,6 +1166,9 @@ class SwinIR(nn.Module):
|
|||||||
self.mean = self.mean.type_as(x)
|
self.mean = self.mean.type_as(x)
|
||||||
x = (x - self.mean) * self.img_range
|
x = (x - self.mean) * self.img_range
|
||||||
|
|
||||||
|
if self.start_unshuffle > 1:
|
||||||
|
x = torch.nn.functional.pixel_unshuffle(x, self.start_unshuffle)
|
||||||
|
|
||||||
if self.upsampler == "pixelshuffle":
|
if self.upsampler == "pixelshuffle":
|
||||||
# for classical SR
|
# for classical SR
|
||||||
x = self.conv_first(x)
|
x = self.conv_first(x)
|
||||||
@ -1185,6 +1198,9 @@ class SwinIR(nn.Module):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
elif self.upscale == 8:
|
||||||
|
x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
||||||
|
x = self.lrelu(self.conv_up3(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
||||||
x = self.conv_last(self.lrelu(self.conv_hr(x)))
|
x = self.conv_last(self.lrelu(self.conv_hr(x)))
|
||||||
else:
|
else:
|
||||||
# for image denoising and JPEG compression artifact reduction
|
# for image denoising and JPEG compression artifact reduction
|
||||||
|
|||||||
@ -1,698 +0,0 @@
|
|||||||
"""Code used for this implementation of the MAT helper utils is modified from
|
|
||||||
lama-cleaner, copyright of Sanster: https://github.com/fenglinglwb/MAT"""
|
|
||||||
|
|
||||||
import collections
|
|
||||||
from itertools import repeat
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
from torch import conv2d, conv_transpose2d
|
|
||||||
|
|
||||||
|
|
||||||
def normalize_2nd_moment(x, dim=1, eps=1e-8):
|
|
||||||
return x * (x.square().mean(dim=dim, keepdim=True) + eps).rsqrt()
|
|
||||||
|
|
||||||
|
|
||||||
class EasyDict(dict):
|
|
||||||
"""Convenience class that behaves like a dict but allows access with the attribute syntax."""
|
|
||||||
|
|
||||||
def __getattr__(self, name: str) -> Any:
|
|
||||||
try:
|
|
||||||
return self[name]
|
|
||||||
except KeyError:
|
|
||||||
raise AttributeError(name)
|
|
||||||
|
|
||||||
def __setattr__(self, name: str, value: Any) -> None:
|
|
||||||
self[name] = value
|
|
||||||
|
|
||||||
def __delattr__(self, name: str) -> None:
|
|
||||||
del self[name]
|
|
||||||
|
|
||||||
|
|
||||||
activation_funcs = {
|
|
||||||
"linear": EasyDict(
|
|
||||||
func=lambda x, **_: x,
|
|
||||||
def_alpha=0,
|
|
||||||
def_gain=1,
|
|
||||||
cuda_idx=1,
|
|
||||||
ref="",
|
|
||||||
has_2nd_grad=False,
|
|
||||||
),
|
|
||||||
"relu": EasyDict(
|
|
||||||
func=lambda x, **_: torch.nn.functional.relu(x),
|
|
||||||
def_alpha=0,
|
|
||||||
def_gain=np.sqrt(2),
|
|
||||||
cuda_idx=2,
|
|
||||||
ref="y",
|
|
||||||
has_2nd_grad=False,
|
|
||||||
),
|
|
||||||
"lrelu": EasyDict(
|
|
||||||
func=lambda x, alpha, **_: torch.nn.functional.leaky_relu(x, alpha),
|
|
||||||
def_alpha=0.2,
|
|
||||||
def_gain=np.sqrt(2),
|
|
||||||
cuda_idx=3,
|
|
||||||
ref="y",
|
|
||||||
has_2nd_grad=False,
|
|
||||||
),
|
|
||||||
"tanh": EasyDict(
|
|
||||||
func=lambda x, **_: torch.tanh(x),
|
|
||||||
def_alpha=0,
|
|
||||||
def_gain=1,
|
|
||||||
cuda_idx=4,
|
|
||||||
ref="y",
|
|
||||||
has_2nd_grad=True,
|
|
||||||
),
|
|
||||||
"sigmoid": EasyDict(
|
|
||||||
func=lambda x, **_: torch.sigmoid(x),
|
|
||||||
def_alpha=0,
|
|
||||||
def_gain=1,
|
|
||||||
cuda_idx=5,
|
|
||||||
ref="y",
|
|
||||||
has_2nd_grad=True,
|
|
||||||
),
|
|
||||||
"elu": EasyDict(
|
|
||||||
func=lambda x, **_: torch.nn.functional.elu(x),
|
|
||||||
def_alpha=0,
|
|
||||||
def_gain=1,
|
|
||||||
cuda_idx=6,
|
|
||||||
ref="y",
|
|
||||||
has_2nd_grad=True,
|
|
||||||
),
|
|
||||||
"selu": EasyDict(
|
|
||||||
func=lambda x, **_: torch.nn.functional.selu(x),
|
|
||||||
def_alpha=0,
|
|
||||||
def_gain=1,
|
|
||||||
cuda_idx=7,
|
|
||||||
ref="y",
|
|
||||||
has_2nd_grad=True,
|
|
||||||
),
|
|
||||||
"softplus": EasyDict(
|
|
||||||
func=lambda x, **_: torch.nn.functional.softplus(x),
|
|
||||||
def_alpha=0,
|
|
||||||
def_gain=1,
|
|
||||||
cuda_idx=8,
|
|
||||||
ref="y",
|
|
||||||
has_2nd_grad=True,
|
|
||||||
),
|
|
||||||
"swish": EasyDict(
|
|
||||||
func=lambda x, **_: torch.sigmoid(x) * x,
|
|
||||||
def_alpha=0,
|
|
||||||
def_gain=np.sqrt(2),
|
|
||||||
cuda_idx=9,
|
|
||||||
ref="x",
|
|
||||||
has_2nd_grad=True,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _bias_act_ref(x, b=None, dim=1, act="linear", alpha=None, gain=None, clamp=None):
|
|
||||||
"""Slow reference implementation of `bias_act()` using standard TensorFlow ops."""
|
|
||||||
assert isinstance(x, torch.Tensor)
|
|
||||||
assert clamp is None or clamp >= 0
|
|
||||||
spec = activation_funcs[act]
|
|
||||||
alpha = float(alpha if alpha is not None else spec.def_alpha)
|
|
||||||
gain = float(gain if gain is not None else spec.def_gain)
|
|
||||||
clamp = float(clamp if clamp is not None else -1)
|
|
||||||
|
|
||||||
# Add bias.
|
|
||||||
if b is not None:
|
|
||||||
assert isinstance(b, torch.Tensor) and b.ndim == 1
|
|
||||||
assert 0 <= dim < x.ndim
|
|
||||||
assert b.shape[0] == x.shape[dim]
|
|
||||||
x = x + b.reshape([-1 if i == dim else 1 for i in range(x.ndim)]).to(x.device)
|
|
||||||
|
|
||||||
# Evaluate activation function.
|
|
||||||
alpha = float(alpha)
|
|
||||||
x = spec.func(x, alpha=alpha)
|
|
||||||
|
|
||||||
# Scale by gain.
|
|
||||||
gain = float(gain)
|
|
||||||
if gain != 1:
|
|
||||||
x = x * gain
|
|
||||||
|
|
||||||
# Clamp.
|
|
||||||
if clamp >= 0:
|
|
||||||
x = x.clamp(-clamp, clamp) # pylint: disable=invalid-unary-operand-type
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
def bias_act(
|
|
||||||
x, b=None, dim=1, act="linear", alpha=None, gain=None, clamp=None, impl="ref"
|
|
||||||
):
|
|
||||||
r"""Fused bias and activation function.
|
|
||||||
Adds bias `b` to activation tensor `x`, evaluates activation function `act`,
|
|
||||||
and scales the result by `gain`. Each of the steps is optional. In most cases,
|
|
||||||
the fused op is considerably more efficient than performing the same calculation
|
|
||||||
using standard PyTorch ops. It supports first and second order gradients,
|
|
||||||
but not third order gradients.
|
|
||||||
Args:
|
|
||||||
x: Input activation tensor. Can be of any shape.
|
|
||||||
b: Bias vector, or `None` to disable. Must be a 1D tensor of the same type
|
|
||||||
as `x`. The shape must be known, and it must match the dimension of `x`
|
|
||||||
corresponding to `dim`.
|
|
||||||
dim: The dimension in `x` corresponding to the elements of `b`.
|
|
||||||
The value of `dim` is ignored if `b` is not specified.
|
|
||||||
act: Name of the activation function to evaluate, or `"linear"` to disable.
|
|
||||||
Can be e.g. `"relu"`, `"lrelu"`, `"tanh"`, `"sigmoid"`, `"swish"`, etc.
|
|
||||||
See `activation_funcs` for a full list. `None` is not allowed.
|
|
||||||
alpha: Shape parameter for the activation function, or `None` to use the default.
|
|
||||||
gain: Scaling factor for the output tensor, or `None` to use default.
|
|
||||||
See `activation_funcs` for the default scaling of each activation function.
|
|
||||||
If unsure, consider specifying 1.
|
|
||||||
clamp: Clamp the output values to `[-clamp, +clamp]`, or `None` to disable
|
|
||||||
the clamping (default).
|
|
||||||
impl: Name of the implementation to use. Can be `"ref"` or `"cuda"` (default).
|
|
||||||
Returns:
|
|
||||||
Tensor of the same shape and datatype as `x`.
|
|
||||||
"""
|
|
||||||
assert isinstance(x, torch.Tensor)
|
|
||||||
assert impl in ["ref", "cuda"]
|
|
||||||
return _bias_act_ref(
|
|
||||||
x=x, b=b, dim=dim, act=act, alpha=alpha, gain=gain, clamp=clamp
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def setup_filter(
|
|
||||||
f,
|
|
||||||
device=torch.device("cpu"),
|
|
||||||
normalize=True,
|
|
||||||
flip_filter=False,
|
|
||||||
gain=1,
|
|
||||||
separable=None,
|
|
||||||
):
|
|
||||||
r"""Convenience function to setup 2D FIR filter for `upfirdn2d()`.
|
|
||||||
Args:
|
|
||||||
f: Torch tensor, numpy array, or python list of the shape
|
|
||||||
`[filter_height, filter_width]` (non-separable),
|
|
||||||
`[filter_taps]` (separable),
|
|
||||||
`[]` (impulse), or
|
|
||||||
`None` (identity).
|
|
||||||
device: Result device (default: cpu).
|
|
||||||
normalize: Normalize the filter so that it retains the magnitude
|
|
||||||
for constant input signal (DC)? (default: True).
|
|
||||||
flip_filter: Flip the filter? (default: False).
|
|
||||||
gain: Overall scaling factor for signal magnitude (default: 1).
|
|
||||||
separable: Return a separable filter? (default: select automatically).
|
|
||||||
Returns:
|
|
||||||
Float32 tensor of the shape
|
|
||||||
`[filter_height, filter_width]` (non-separable) or
|
|
||||||
`[filter_taps]` (separable).
|
|
||||||
"""
|
|
||||||
# Validate.
|
|
||||||
if f is None:
|
|
||||||
f = 1
|
|
||||||
f = torch.as_tensor(f, dtype=torch.float32)
|
|
||||||
assert f.ndim in [0, 1, 2]
|
|
||||||
assert f.numel() > 0
|
|
||||||
if f.ndim == 0:
|
|
||||||
f = f[np.newaxis]
|
|
||||||
|
|
||||||
# Separable?
|
|
||||||
if separable is None:
|
|
||||||
separable = f.ndim == 1 and f.numel() >= 8
|
|
||||||
if f.ndim == 1 and not separable:
|
|
||||||
f = f.ger(f)
|
|
||||||
assert f.ndim == (1 if separable else 2)
|
|
||||||
|
|
||||||
# Apply normalize, flip, gain, and device.
|
|
||||||
if normalize:
|
|
||||||
f /= f.sum()
|
|
||||||
if flip_filter:
|
|
||||||
f = f.flip(list(range(f.ndim)))
|
|
||||||
f = f * (gain ** (f.ndim / 2))
|
|
||||||
f = f.to(device=device)
|
|
||||||
return f
|
|
||||||
|
|
||||||
|
|
||||||
def _get_filter_size(f):
|
|
||||||
if f is None:
|
|
||||||
return 1, 1
|
|
||||||
|
|
||||||
assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
|
|
||||||
fw = f.shape[-1]
|
|
||||||
fh = f.shape[0]
|
|
||||||
|
|
||||||
fw = int(fw)
|
|
||||||
fh = int(fh)
|
|
||||||
assert fw >= 1 and fh >= 1
|
|
||||||
return fw, fh
|
|
||||||
|
|
||||||
|
|
||||||
def _get_weight_shape(w):
|
|
||||||
shape = [int(sz) for sz in w.shape]
|
|
||||||
return shape
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_scaling(scaling):
|
|
||||||
if isinstance(scaling, int):
|
|
||||||
scaling = [scaling, scaling]
|
|
||||||
assert isinstance(scaling, (list, tuple))
|
|
||||||
assert all(isinstance(x, int) for x in scaling)
|
|
||||||
sx, sy = scaling
|
|
||||||
assert sx >= 1 and sy >= 1
|
|
||||||
return sx, sy
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_padding(padding):
|
|
||||||
if isinstance(padding, int):
|
|
||||||
padding = [padding, padding]
|
|
||||||
assert isinstance(padding, (list, tuple))
|
|
||||||
assert all(isinstance(x, int) for x in padding)
|
|
||||||
if len(padding) == 2:
|
|
||||||
padx, pady = padding
|
|
||||||
padding = [padx, padx, pady, pady]
|
|
||||||
padx0, padx1, pady0, pady1 = padding
|
|
||||||
return padx0, padx1, pady0, pady1
|
|
||||||
|
|
||||||
|
|
||||||
def _ntuple(n):
|
|
||||||
def parse(x):
|
|
||||||
if isinstance(x, collections.abc.Iterable):
|
|
||||||
return x
|
|
||||||
return tuple(repeat(x, n))
|
|
||||||
|
|
||||||
return parse
|
|
||||||
|
|
||||||
|
|
||||||
to_2tuple = _ntuple(2)
|
|
||||||
|
|
||||||
|
|
||||||
def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1):
|
|
||||||
"""Slow reference implementation of `upfirdn2d()` using standard PyTorch ops."""
|
|
||||||
# Validate arguments.
|
|
||||||
assert isinstance(x, torch.Tensor) and x.ndim == 4
|
|
||||||
if f is None:
|
|
||||||
f = torch.ones([1, 1], dtype=torch.float32, device=x.device)
|
|
||||||
assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
|
|
||||||
assert f.dtype == torch.float32 and not f.requires_grad
|
|
||||||
batch_size, num_channels, in_height, in_width = x.shape
|
|
||||||
# upx, upy = _parse_scaling(up)
|
|
||||||
# downx, downy = _parse_scaling(down)
|
|
||||||
|
|
||||||
upx, upy = up, up
|
|
||||||
downx, downy = down, down
|
|
||||||
|
|
||||||
# padx0, padx1, pady0, pady1 = _parse_padding(padding)
|
|
||||||
padx0, padx1, pady0, pady1 = padding[0], padding[1], padding[2], padding[3]
|
|
||||||
|
|
||||||
# Upsample by inserting zeros.
|
|
||||||
x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1])
|
|
||||||
x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1])
|
|
||||||
x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx])
|
|
||||||
|
|
||||||
# Pad or crop.
|
|
||||||
x = torch.nn.functional.pad(
|
|
||||||
x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)]
|
|
||||||
)
|
|
||||||
x = x[
|
|
||||||
:,
|
|
||||||
:,
|
|
||||||
max(-pady0, 0) : x.shape[2] - max(-pady1, 0),
|
|
||||||
max(-padx0, 0) : x.shape[3] - max(-padx1, 0),
|
|
||||||
]
|
|
||||||
|
|
||||||
# Setup filter.
|
|
||||||
f = f * (gain ** (f.ndim / 2))
|
|
||||||
f = f.to(x.dtype)
|
|
||||||
if not flip_filter:
|
|
||||||
f = f.flip(list(range(f.ndim)))
|
|
||||||
|
|
||||||
# Convolve with the filter.
|
|
||||||
f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim)
|
|
||||||
if f.ndim == 4:
|
|
||||||
x = conv2d(input=x, weight=f, groups=num_channels)
|
|
||||||
else:
|
|
||||||
x = conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels)
|
|
||||||
x = conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels)
|
|
||||||
|
|
||||||
# Downsample by throwing away pixels.
|
|
||||||
x = x[:, :, ::downy, ::downx]
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl="cuda"):
|
|
||||||
r"""Pad, upsample, filter, and downsample a batch of 2D images.
|
|
||||||
Performs the following sequence of operations for each channel:
|
|
||||||
1. Upsample the image by inserting N-1 zeros after each pixel (`up`).
|
|
||||||
2. Pad the image with the specified number of zeros on each side (`padding`).
|
|
||||||
Negative padding corresponds to cropping the image.
|
|
||||||
3. Convolve the image with the specified 2D FIR filter (`f`), shrinking it
|
|
||||||
so that the footprint of all output pixels lies within the input image.
|
|
||||||
4. Downsample the image by keeping every Nth pixel (`down`).
|
|
||||||
This sequence of operations bears close resemblance to scipy.signal.upfirdn().
|
|
||||||
The fused op is considerably more efficient than performing the same calculation
|
|
||||||
using standard PyTorch ops. It supports gradients of arbitrary order.
|
|
||||||
Args:
|
|
||||||
x: Float32/float64/float16 input tensor of the shape
|
|
||||||
`[batch_size, num_channels, in_height, in_width]`.
|
|
||||||
f: Float32 FIR filter of the shape
|
|
||||||
`[filter_height, filter_width]` (non-separable),
|
|
||||||
`[filter_taps]` (separable), or
|
|
||||||
`None` (identity).
|
|
||||||
up: Integer upsampling factor. Can be a single int or a list/tuple
|
|
||||||
`[x, y]` (default: 1).
|
|
||||||
down: Integer downsampling factor. Can be a single int or a list/tuple
|
|
||||||
`[x, y]` (default: 1).
|
|
||||||
padding: Padding with respect to the upsampled image. Can be a single number
|
|
||||||
or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
|
|
||||||
(default: 0).
|
|
||||||
flip_filter: False = convolution, True = correlation (default: False).
|
|
||||||
gain: Overall scaling factor for signal magnitude (default: 1).
|
|
||||||
impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).
|
|
||||||
Returns:
|
|
||||||
Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
|
|
||||||
"""
|
|
||||||
# assert isinstance(x, torch.Tensor)
|
|
||||||
# assert impl in ['ref', 'cuda']
|
|
||||||
return _upfirdn2d_ref(
|
|
||||||
x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def upsample2d(x, f, up=2, padding=0, flip_filter=False, gain=1, impl="cuda"):
|
|
||||||
r"""Upsample a batch of 2D images using the given 2D FIR filter.
|
|
||||||
By default, the result is padded so that its shape is a multiple of the input.
|
|
||||||
User-specified padding is applied on top of that, with negative values
|
|
||||||
indicating cropping. Pixels outside the image are assumed to be zero.
|
|
||||||
Args:
|
|
||||||
x: Float32/float64/float16 input tensor of the shape
|
|
||||||
`[batch_size, num_channels, in_height, in_width]`.
|
|
||||||
f: Float32 FIR filter of the shape
|
|
||||||
`[filter_height, filter_width]` (non-separable),
|
|
||||||
`[filter_taps]` (separable), or
|
|
||||||
`None` (identity).
|
|
||||||
up: Integer upsampling factor. Can be a single int or a list/tuple
|
|
||||||
`[x, y]` (default: 1).
|
|
||||||
padding: Padding with respect to the output. Can be a single number or a
|
|
||||||
list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
|
|
||||||
(default: 0).
|
|
||||||
flip_filter: False = convolution, True = correlation (default: False).
|
|
||||||
gain: Overall scaling factor for signal magnitude (default: 1).
|
|
||||||
impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).
|
|
||||||
Returns:
|
|
||||||
Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
|
|
||||||
"""
|
|
||||||
upx, upy = _parse_scaling(up)
|
|
||||||
# upx, upy = up, up
|
|
||||||
padx0, padx1, pady0, pady1 = _parse_padding(padding)
|
|
||||||
# padx0, padx1, pady0, pady1 = padding, padding, padding, padding
|
|
||||||
fw, fh = _get_filter_size(f)
|
|
||||||
p = [
|
|
||||||
padx0 + (fw + upx - 1) // 2,
|
|
||||||
padx1 + (fw - upx) // 2,
|
|
||||||
pady0 + (fh + upy - 1) // 2,
|
|
||||||
pady1 + (fh - upy) // 2,
|
|
||||||
]
|
|
||||||
return upfirdn2d(
|
|
||||||
x,
|
|
||||||
f,
|
|
||||||
up=up,
|
|
||||||
padding=p,
|
|
||||||
flip_filter=flip_filter,
|
|
||||||
gain=gain * upx * upy,
|
|
||||||
impl=impl,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class FullyConnectedLayer(torch.nn.Module):
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
in_features, # Number of input features.
|
|
||||||
out_features, # Number of output features.
|
|
||||||
bias=True, # Apply additive bias before the activation function?
|
|
||||||
activation="linear", # Activation function: 'relu', 'lrelu', etc.
|
|
||||||
lr_multiplier=1, # Learning rate multiplier.
|
|
||||||
bias_init=0, # Initial value for the additive bias.
|
|
||||||
):
|
|
||||||
super().__init__()
|
|
||||||
self.weight = torch.nn.Parameter(
|
|
||||||
torch.randn([out_features, in_features]) / lr_multiplier
|
|
||||||
)
|
|
||||||
self.bias = (
|
|
||||||
torch.nn.Parameter(torch.full([out_features], np.float32(bias_init)))
|
|
||||||
if bias
|
|
||||||
else None
|
|
||||||
)
|
|
||||||
self.activation = activation
|
|
||||||
|
|
||||||
self.weight_gain = lr_multiplier / np.sqrt(in_features)
|
|
||||||
self.bias_gain = lr_multiplier
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
w = self.weight * self.weight_gain
|
|
||||||
b = self.bias
|
|
||||||
if b is not None and self.bias_gain != 1:
|
|
||||||
b = b * self.bias_gain
|
|
||||||
|
|
||||||
if self.activation == "linear" and b is not None:
|
|
||||||
# out = torch.addmm(b.unsqueeze(0), x, w.t())
|
|
||||||
x = x.matmul(w.t().to(x.device))
|
|
||||||
out = x + b.reshape(
|
|
||||||
[-1 if i == x.ndim - 1 else 1 for i in range(x.ndim)]
|
|
||||||
).to(x.device)
|
|
||||||
else:
|
|
||||||
x = x.matmul(w.t().to(x.device))
|
|
||||||
out = bias_act(x, b, act=self.activation, dim=x.ndim - 1).to(x.device)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _conv2d_wrapper(
|
|
||||||
x, w, stride=1, padding=0, groups=1, transpose=False, flip_weight=True
|
|
||||||
):
|
|
||||||
"""Wrapper for the underlying `conv2d()` and `conv_transpose2d()` implementations."""
|
|
||||||
out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w)
|
|
||||||
|
|
||||||
# Flip weight if requested.
|
|
||||||
if (
|
|
||||||
not flip_weight
|
|
||||||
): # conv2d() actually performs correlation (flip_weight=True) not convolution (flip_weight=False).
|
|
||||||
w = w.flip([2, 3])
|
|
||||||
|
|
||||||
# Workaround performance pitfall in cuDNN 8.0.5, triggered when using
|
|
||||||
# 1x1 kernel + memory_format=channels_last + less than 64 channels.
|
|
||||||
if (
|
|
||||||
kw == 1
|
|
||||||
and kh == 1
|
|
||||||
and stride == 1
|
|
||||||
and padding in [0, [0, 0], (0, 0)]
|
|
||||||
and not transpose
|
|
||||||
):
|
|
||||||
if x.stride()[1] == 1 and min(out_channels, in_channels_per_group) < 64:
|
|
||||||
if out_channels <= 4 and groups == 1:
|
|
||||||
in_shape = x.shape
|
|
||||||
x = w.squeeze(3).squeeze(2) @ x.reshape(
|
|
||||||
[in_shape[0], in_channels_per_group, -1]
|
|
||||||
)
|
|
||||||
x = x.reshape([in_shape[0], out_channels, in_shape[2], in_shape[3]])
|
|
||||||
else:
|
|
||||||
x = x.to(memory_format=torch.contiguous_format)
|
|
||||||
w = w.to(memory_format=torch.contiguous_format)
|
|
||||||
x = conv2d(x, w, groups=groups)
|
|
||||||
return x.to(memory_format=torch.channels_last)
|
|
||||||
|
|
||||||
# Otherwise => execute using conv2d_gradfix.
|
|
||||||
op = conv_transpose2d if transpose else conv2d
|
|
||||||
return op(x, w, stride=stride, padding=padding, groups=groups)
|
|
||||||
|
|
||||||
|
|
||||||
def conv2d_resample(
|
|
||||||
x, w, f=None, up=1, down=1, padding=0, groups=1, flip_weight=True, flip_filter=False
|
|
||||||
):
|
|
||||||
r"""2D convolution with optional up/downsampling.
|
|
||||||
Padding is performed only once at the beginning, not between the operations.
|
|
||||||
Args:
|
|
||||||
x: Input tensor of shape
|
|
||||||
`[batch_size, in_channels, in_height, in_width]`.
|
|
||||||
w: Weight tensor of shape
|
|
||||||
`[out_channels, in_channels//groups, kernel_height, kernel_width]`.
|
|
||||||
f: Low-pass filter for up/downsampling. Must be prepared beforehand by
|
|
||||||
calling setup_filter(). None = identity (default).
|
|
||||||
up: Integer upsampling factor (default: 1).
|
|
||||||
down: Integer downsampling factor (default: 1).
|
|
||||||
padding: Padding with respect to the upsampled image. Can be a single number
|
|
||||||
or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
|
|
||||||
(default: 0).
|
|
||||||
groups: Split input channels into N groups (default: 1).
|
|
||||||
flip_weight: False = convolution, True = correlation (default: True).
|
|
||||||
flip_filter: False = convolution, True = correlation (default: False).
|
|
||||||
Returns:
|
|
||||||
Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
|
|
||||||
"""
|
|
||||||
# Validate arguments.
|
|
||||||
assert isinstance(x, torch.Tensor) and (x.ndim == 4)
|
|
||||||
assert isinstance(w, torch.Tensor) and (w.ndim == 4) and (w.dtype == x.dtype)
|
|
||||||
assert f is None or (
|
|
||||||
isinstance(f, torch.Tensor) and f.ndim in [1, 2] and f.dtype == torch.float32
|
|
||||||
)
|
|
||||||
assert isinstance(up, int) and (up >= 1)
|
|
||||||
assert isinstance(down, int) and (down >= 1)
|
|
||||||
# assert isinstance(groups, int) and (groups >= 1), f"!!!!!! groups: {groups} isinstance(groups, int) {isinstance(groups, int)} {type(groups)}"
|
|
||||||
out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w)
|
|
||||||
fw, fh = _get_filter_size(f)
|
|
||||||
# px0, px1, py0, py1 = _parse_padding(padding)
|
|
||||||
px0, px1, py0, py1 = padding, padding, padding, padding
|
|
||||||
|
|
||||||
# Adjust padding to account for up/downsampling.
|
|
||||||
if up > 1:
|
|
||||||
px0 += (fw + up - 1) // 2
|
|
||||||
px1 += (fw - up) // 2
|
|
||||||
py0 += (fh + up - 1) // 2
|
|
||||||
py1 += (fh - up) // 2
|
|
||||||
if down > 1:
|
|
||||||
px0 += (fw - down + 1) // 2
|
|
||||||
px1 += (fw - down) // 2
|
|
||||||
py0 += (fh - down + 1) // 2
|
|
||||||
py1 += (fh - down) // 2
|
|
||||||
|
|
||||||
# Fast path: 1x1 convolution with downsampling only => downsample first, then convolve.
|
|
||||||
if kw == 1 and kh == 1 and (down > 1 and up == 1):
|
|
||||||
x = upfirdn2d(
|
|
||||||
x=x, f=f, down=down, padding=[px0, px1, py0, py1], flip_filter=flip_filter
|
|
||||||
)
|
|
||||||
x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight)
|
|
||||||
return x
|
|
||||||
|
|
||||||
# Fast path: 1x1 convolution with upsampling only => convolve first, then upsample.
|
|
||||||
if kw == 1 and kh == 1 and (up > 1 and down == 1):
|
|
||||||
x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight)
|
|
||||||
x = upfirdn2d(
|
|
||||||
x=x,
|
|
||||||
f=f,
|
|
||||||
up=up,
|
|
||||||
padding=[px0, px1, py0, py1],
|
|
||||||
gain=up**2,
|
|
||||||
flip_filter=flip_filter,
|
|
||||||
)
|
|
||||||
return x
|
|
||||||
|
|
||||||
# Fast path: downsampling only => use strided convolution.
|
|
||||||
if down > 1 and up == 1:
|
|
||||||
x = upfirdn2d(x=x, f=f, padding=[px0, px1, py0, py1], flip_filter=flip_filter)
|
|
||||||
x = _conv2d_wrapper(
|
|
||||||
x=x, w=w, stride=down, groups=groups, flip_weight=flip_weight
|
|
||||||
)
|
|
||||||
return x
|
|
||||||
|
|
||||||
# Fast path: upsampling with optional downsampling => use transpose strided convolution.
|
|
||||||
if up > 1:
|
|
||||||
if groups == 1:
|
|
||||||
w = w.transpose(0, 1)
|
|
||||||
else:
|
|
||||||
w = w.reshape(groups, out_channels // groups, in_channels_per_group, kh, kw)
|
|
||||||
w = w.transpose(1, 2)
|
|
||||||
w = w.reshape(
|
|
||||||
groups * in_channels_per_group, out_channels // groups, kh, kw
|
|
||||||
)
|
|
||||||
px0 -= kw - 1
|
|
||||||
px1 -= kw - up
|
|
||||||
py0 -= kh - 1
|
|
||||||
py1 -= kh - up
|
|
||||||
pxt = max(min(-px0, -px1), 0)
|
|
||||||
pyt = max(min(-py0, -py1), 0)
|
|
||||||
x = _conv2d_wrapper(
|
|
||||||
x=x,
|
|
||||||
w=w,
|
|
||||||
stride=up,
|
|
||||||
padding=[pyt, pxt],
|
|
||||||
groups=groups,
|
|
||||||
transpose=True,
|
|
||||||
flip_weight=(not flip_weight),
|
|
||||||
)
|
|
||||||
x = upfirdn2d(
|
|
||||||
x=x,
|
|
||||||
f=f,
|
|
||||||
padding=[px0 + pxt, px1 + pxt, py0 + pyt, py1 + pyt],
|
|
||||||
gain=up**2,
|
|
||||||
flip_filter=flip_filter,
|
|
||||||
)
|
|
||||||
if down > 1:
|
|
||||||
x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter)
|
|
||||||
return x
|
|
||||||
|
|
||||||
# Fast path: no up/downsampling, padding supported by the underlying implementation => use plain conv2d.
|
|
||||||
if up == 1 and down == 1:
|
|
||||||
if px0 == px1 and py0 == py1 and px0 >= 0 and py0 >= 0:
|
|
||||||
return _conv2d_wrapper(
|
|
||||||
x=x, w=w, padding=[py0, px0], groups=groups, flip_weight=flip_weight
|
|
||||||
)
|
|
||||||
|
|
||||||
# Fallback: Generic reference implementation.
|
|
||||||
x = upfirdn2d(
|
|
||||||
x=x,
|
|
||||||
f=(f if up > 1 else None),
|
|
||||||
up=up,
|
|
||||||
padding=[px0, px1, py0, py1],
|
|
||||||
gain=up**2,
|
|
||||||
flip_filter=flip_filter,
|
|
||||||
)
|
|
||||||
x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight)
|
|
||||||
if down > 1:
|
|
||||||
x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter)
|
|
||||||
return x
|
|
||||||
|
|
||||||
|
|
||||||
class Conv2dLayer(torch.nn.Module):
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
in_channels, # Number of input channels.
|
|
||||||
out_channels, # Number of output channels.
|
|
||||||
kernel_size, # Width and height of the convolution kernel.
|
|
||||||
bias=True, # Apply additive bias before the activation function?
|
|
||||||
activation="linear", # Activation function: 'relu', 'lrelu', etc.
|
|
||||||
up=1, # Integer upsampling factor.
|
|
||||||
down=1, # Integer downsampling factor.
|
|
||||||
resample_filter=[
|
|
||||||
1,
|
|
||||||
3,
|
|
||||||
3,
|
|
||||||
1,
|
|
||||||
], # Low-pass filter to apply when resampling activations.
|
|
||||||
conv_clamp=None, # Clamp the output to +-X, None = disable clamping.
|
|
||||||
channels_last=False, # Expect the input to have memory_format=channels_last?
|
|
||||||
trainable=True, # Update the weights of this layer during training?
|
|
||||||
):
|
|
||||||
super().__init__()
|
|
||||||
self.activation = activation
|
|
||||||
self.up = up
|
|
||||||
self.down = down
|
|
||||||
self.register_buffer("resample_filter", setup_filter(resample_filter))
|
|
||||||
self.conv_clamp = conv_clamp
|
|
||||||
self.padding = kernel_size // 2
|
|
||||||
self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2))
|
|
||||||
self.act_gain = activation_funcs[activation].def_gain
|
|
||||||
|
|
||||||
memory_format = (
|
|
||||||
torch.channels_last if channels_last else torch.contiguous_format
|
|
||||||
)
|
|
||||||
weight = torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to(
|
|
||||||
memory_format=memory_format
|
|
||||||
)
|
|
||||||
bias = torch.zeros([out_channels]) if bias else None
|
|
||||||
if trainable:
|
|
||||||
self.weight = torch.nn.Parameter(weight)
|
|
||||||
self.bias = torch.nn.Parameter(bias) if bias is not None else None
|
|
||||||
else:
|
|
||||||
self.register_buffer("weight", weight)
|
|
||||||
if bias is not None:
|
|
||||||
self.register_buffer("bias", bias)
|
|
||||||
else:
|
|
||||||
self.bias = None
|
|
||||||
|
|
||||||
def forward(self, x, gain=1):
|
|
||||||
w = self.weight * self.weight_gain
|
|
||||||
x = conv2d_resample(
|
|
||||||
x=x,
|
|
||||||
w=w,
|
|
||||||
f=self.resample_filter,
|
|
||||||
up=self.up,
|
|
||||||
down=self.down,
|
|
||||||
padding=self.padding,
|
|
||||||
)
|
|
||||||
|
|
||||||
act_gain = self.act_gain * gain
|
|
||||||
act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None
|
|
||||||
out = bias_act(
|
|
||||||
x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp
|
|
||||||
)
|
|
||||||
return out
|
|
||||||
@ -1,13 +1,14 @@
|
|||||||
import logging as logger
|
import logging as logger
|
||||||
|
|
||||||
|
from .architecture.DAT import DAT
|
||||||
from .architecture.face.codeformer import CodeFormer
|
from .architecture.face.codeformer import CodeFormer
|
||||||
from .architecture.face.gfpganv1_clean_arch import GFPGANv1Clean
|
from .architecture.face.gfpganv1_clean_arch import GFPGANv1Clean
|
||||||
from .architecture.face.restoreformer_arch import RestoreFormer
|
from .architecture.face.restoreformer_arch import RestoreFormer
|
||||||
from .architecture.HAT import HAT
|
from .architecture.HAT import HAT
|
||||||
from .architecture.LaMa import LaMa
|
from .architecture.LaMa import LaMa
|
||||||
from .architecture.MAT import MAT
|
|
||||||
from .architecture.OmniSR.OmniSR import OmniSR
|
from .architecture.OmniSR.OmniSR import OmniSR
|
||||||
from .architecture.RRDB import RRDBNet as ESRGAN
|
from .architecture.RRDB import RRDBNet as ESRGAN
|
||||||
|
from .architecture.SCUNet import SCUNet
|
||||||
from .architecture.SPSR import SPSRNet as SPSR
|
from .architecture.SPSR import SPSRNet as SPSR
|
||||||
from .architecture.SRVGG import SRVGGNetCompact as RealESRGANv2
|
from .architecture.SRVGG import SRVGGNetCompact as RealESRGANv2
|
||||||
from .architecture.SwiftSRGAN import Generator as SwiftSRGAN
|
from .architecture.SwiftSRGAN import Generator as SwiftSRGAN
|
||||||
@ -33,7 +34,6 @@ def load_state_dict(state_dict) -> PyTorchModel:
|
|||||||
state_dict = state_dict["params"]
|
state_dict = state_dict["params"]
|
||||||
|
|
||||||
state_dict_keys = list(state_dict.keys())
|
state_dict_keys = list(state_dict.keys())
|
||||||
|
|
||||||
# SRVGGNet Real-ESRGAN (v2)
|
# SRVGGNet Real-ESRGAN (v2)
|
||||||
if "body.0.weight" in state_dict_keys and "body.1.weight" in state_dict_keys:
|
if "body.0.weight" in state_dict_keys and "body.1.weight" in state_dict_keys:
|
||||||
model = RealESRGANv2(state_dict)
|
model = RealESRGANv2(state_dict)
|
||||||
@ -46,12 +46,14 @@ def load_state_dict(state_dict) -> PyTorchModel:
|
|||||||
and "initial.cnn.depthwise.weight" in state_dict["model"].keys()
|
and "initial.cnn.depthwise.weight" in state_dict["model"].keys()
|
||||||
):
|
):
|
||||||
model = SwiftSRGAN(state_dict)
|
model = SwiftSRGAN(state_dict)
|
||||||
# HAT -- be sure it is above swinir
|
# SwinIR, Swin2SR, HAT
|
||||||
elif "layers.0.residual_group.blocks.0.conv_block.cab.0.weight" in state_dict_keys:
|
|
||||||
model = HAT(state_dict)
|
|
||||||
# SwinIR
|
|
||||||
elif "layers.0.residual_group.blocks.0.norm1.weight" in state_dict_keys:
|
elif "layers.0.residual_group.blocks.0.norm1.weight" in state_dict_keys:
|
||||||
if "patch_embed.proj.weight" in state_dict_keys:
|
if (
|
||||||
|
"layers.0.residual_group.blocks.0.conv_block.cab.0.weight"
|
||||||
|
in state_dict_keys
|
||||||
|
):
|
||||||
|
model = HAT(state_dict)
|
||||||
|
elif "patch_embed.proj.weight" in state_dict_keys:
|
||||||
model = Swin2SR(state_dict)
|
model = Swin2SR(state_dict)
|
||||||
else:
|
else:
|
||||||
model = SwinIR(state_dict)
|
model = SwinIR(state_dict)
|
||||||
@ -78,12 +80,15 @@ def load_state_dict(state_dict) -> PyTorchModel:
|
|||||||
or "generator.model.1.bn_l.running_mean" in state_dict_keys
|
or "generator.model.1.bn_l.running_mean" in state_dict_keys
|
||||||
):
|
):
|
||||||
model = LaMa(state_dict)
|
model = LaMa(state_dict)
|
||||||
# MAT
|
|
||||||
elif "synthesis.first_stage.conv_first.conv.resample_filter" in state_dict_keys:
|
|
||||||
model = MAT(state_dict)
|
|
||||||
# Omni-SR
|
# Omni-SR
|
||||||
elif "residual_layer.0.residual_layer.0.layer.0.fn.0.weight" in state_dict_keys:
|
elif "residual_layer.0.residual_layer.0.layer.0.fn.0.weight" in state_dict_keys:
|
||||||
model = OmniSR(state_dict)
|
model = OmniSR(state_dict)
|
||||||
|
# SCUNet
|
||||||
|
elif "m_head.0.weight" in state_dict_keys and "m_tail.0.weight" in state_dict_keys:
|
||||||
|
model = SCUNet(state_dict)
|
||||||
|
# DAT
|
||||||
|
elif "layers.0.blocks.2.attn.attn_mask_0" in state_dict_keys:
|
||||||
|
model = DAT(state_dict)
|
||||||
# Regular ESRGAN, "new-arch" ESRGAN, Real-ESRGAN v1
|
# Regular ESRGAN, "new-arch" ESRGAN, Real-ESRGAN v1
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@ -1,20 +1,32 @@
|
|||||||
from typing import Union
|
from typing import Union
|
||||||
|
|
||||||
|
from .architecture.DAT import DAT
|
||||||
from .architecture.face.codeformer import CodeFormer
|
from .architecture.face.codeformer import CodeFormer
|
||||||
from .architecture.face.gfpganv1_clean_arch import GFPGANv1Clean
|
from .architecture.face.gfpganv1_clean_arch import GFPGANv1Clean
|
||||||
from .architecture.face.restoreformer_arch import RestoreFormer
|
from .architecture.face.restoreformer_arch import RestoreFormer
|
||||||
from .architecture.HAT import HAT
|
from .architecture.HAT import HAT
|
||||||
from .architecture.LaMa import LaMa
|
from .architecture.LaMa import LaMa
|
||||||
from .architecture.MAT import MAT
|
|
||||||
from .architecture.OmniSR.OmniSR import OmniSR
|
from .architecture.OmniSR.OmniSR import OmniSR
|
||||||
from .architecture.RRDB import RRDBNet as ESRGAN
|
from .architecture.RRDB import RRDBNet as ESRGAN
|
||||||
|
from .architecture.SCUNet import SCUNet
|
||||||
from .architecture.SPSR import SPSRNet as SPSR
|
from .architecture.SPSR import SPSRNet as SPSR
|
||||||
from .architecture.SRVGG import SRVGGNetCompact as RealESRGANv2
|
from .architecture.SRVGG import SRVGGNetCompact as RealESRGANv2
|
||||||
from .architecture.SwiftSRGAN import Generator as SwiftSRGAN
|
from .architecture.SwiftSRGAN import Generator as SwiftSRGAN
|
||||||
from .architecture.Swin2SR import Swin2SR
|
from .architecture.Swin2SR import Swin2SR
|
||||||
from .architecture.SwinIR import SwinIR
|
from .architecture.SwinIR import SwinIR
|
||||||
|
|
||||||
PyTorchSRModels = (RealESRGANv2, SPSR, SwiftSRGAN, ESRGAN, SwinIR, Swin2SR, HAT, OmniSR)
|
PyTorchSRModels = (
|
||||||
|
RealESRGANv2,
|
||||||
|
SPSR,
|
||||||
|
SwiftSRGAN,
|
||||||
|
ESRGAN,
|
||||||
|
SwinIR,
|
||||||
|
Swin2SR,
|
||||||
|
HAT,
|
||||||
|
OmniSR,
|
||||||
|
SCUNet,
|
||||||
|
DAT,
|
||||||
|
)
|
||||||
PyTorchSRModel = Union[
|
PyTorchSRModel = Union[
|
||||||
RealESRGANv2,
|
RealESRGANv2,
|
||||||
SPSR,
|
SPSR,
|
||||||
@ -24,6 +36,8 @@ PyTorchSRModel = Union[
|
|||||||
Swin2SR,
|
Swin2SR,
|
||||||
HAT,
|
HAT,
|
||||||
OmniSR,
|
OmniSR,
|
||||||
|
SCUNet,
|
||||||
|
DAT,
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@ -39,8 +53,8 @@ def is_pytorch_face_model(model: object):
|
|||||||
return isinstance(model, PyTorchFaceModels)
|
return isinstance(model, PyTorchFaceModels)
|
||||||
|
|
||||||
|
|
||||||
PyTorchInpaintModels = (LaMa, MAT)
|
PyTorchInpaintModels = (LaMa,)
|
||||||
PyTorchInpaintModel = Union[LaMa, MAT]
|
PyTorchInpaintModel = Union[LaMa]
|
||||||
|
|
||||||
|
|
||||||
def is_pytorch_inpaint_model(model: object):
|
def is_pytorch_inpaint_model(model: object):
|
||||||
|
|||||||
299
comfy_extras/nodes_canny.py
Normal file
299
comfy_extras/nodes_canny.py
Normal file
@ -0,0 +1,299 @@
|
|||||||
|
#From https://github.com/kornia/kornia
|
||||||
|
import math
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.nn.functional as F
|
||||||
|
import comfy.model_management
|
||||||
|
|
||||||
|
def get_canny_nms_kernel(device=None, dtype=None):
|
||||||
|
"""Utility function that returns 3x3 kernels for the Canny Non-maximal suppression."""
|
||||||
|
return torch.tensor(
|
||||||
|
[
|
||||||
|
[[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]]],
|
||||||
|
[[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]],
|
||||||
|
[[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0]]],
|
||||||
|
[[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]]],
|
||||||
|
[[[0.0, 0.0, 0.0], [-1.0, 1.0, 0.0], [0.0, 0.0, 0.0]]],
|
||||||
|
[[[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]],
|
||||||
|
[[[0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]],
|
||||||
|
[[[0.0, 0.0, -1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]],
|
||||||
|
],
|
||||||
|
device=device,
|
||||||
|
dtype=dtype,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_hysteresis_kernel(device=None, dtype=None):
|
||||||
|
"""Utility function that returns the 3x3 kernels for the Canny hysteresis."""
|
||||||
|
return torch.tensor(
|
||||||
|
[
|
||||||
|
[[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]],
|
||||||
|
[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]],
|
||||||
|
[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]],
|
||||||
|
[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]],
|
||||||
|
[[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
|
||||||
|
[[[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
|
||||||
|
[[[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
|
||||||
|
[[[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
|
||||||
|
],
|
||||||
|
device=device,
|
||||||
|
dtype=dtype,
|
||||||
|
)
|
||||||
|
|
||||||
|
def gaussian_blur_2d(img, kernel_size, sigma):
|
||||||
|
ksize_half = (kernel_size - 1) * 0.5
|
||||||
|
|
||||||
|
x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size)
|
||||||
|
|
||||||
|
pdf = torch.exp(-0.5 * (x / sigma).pow(2))
|
||||||
|
|
||||||
|
x_kernel = pdf / pdf.sum()
|
||||||
|
x_kernel = x_kernel.to(device=img.device, dtype=img.dtype)
|
||||||
|
|
||||||
|
kernel2d = torch.mm(x_kernel[:, None], x_kernel[None, :])
|
||||||
|
kernel2d = kernel2d.expand(img.shape[-3], 1, kernel2d.shape[0], kernel2d.shape[1])
|
||||||
|
|
||||||
|
padding = [kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2]
|
||||||
|
|
||||||
|
img = torch.nn.functional.pad(img, padding, mode="reflect")
|
||||||
|
img = torch.nn.functional.conv2d(img, kernel2d, groups=img.shape[-3])
|
||||||
|
|
||||||
|
return img
|
||||||
|
|
||||||
|
def get_sobel_kernel2d(device=None, dtype=None):
|
||||||
|
kernel_x = torch.tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=device, dtype=dtype)
|
||||||
|
kernel_y = kernel_x.transpose(0, 1)
|
||||||
|
return torch.stack([kernel_x, kernel_y])
|
||||||
|
|
||||||
|
def spatial_gradient(input, normalized: bool = True):
|
||||||
|
r"""Compute the first order image derivative in both x and y using a Sobel operator.
|
||||||
|
.. image:: _static/img/spatial_gradient.png
|
||||||
|
Args:
|
||||||
|
input: input image tensor with shape :math:`(B, C, H, W)`.
|
||||||
|
mode: derivatives modality, can be: `sobel` or `diff`.
|
||||||
|
order: the order of the derivatives.
|
||||||
|
normalized: whether the output is normalized.
|
||||||
|
Return:
|
||||||
|
the derivatives of the input feature map. with shape :math:`(B, C, 2, H, W)`.
|
||||||
|
.. note::
|
||||||
|
See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/
|
||||||
|
filtering_edges.html>`__.
|
||||||
|
Examples:
|
||||||
|
>>> input = torch.rand(1, 3, 4, 4)
|
||||||
|
>>> output = spatial_gradient(input) # 1x3x2x4x4
|
||||||
|
>>> output.shape
|
||||||
|
torch.Size([1, 3, 2, 4, 4])
|
||||||
|
"""
|
||||||
|
# KORNIA_CHECK_IS_TENSOR(input)
|
||||||
|
# KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
|
||||||
|
|
||||||
|
# allocate kernel
|
||||||
|
kernel = get_sobel_kernel2d(device=input.device, dtype=input.dtype)
|
||||||
|
if normalized:
|
||||||
|
kernel = normalize_kernel2d(kernel)
|
||||||
|
|
||||||
|
# prepare kernel
|
||||||
|
b, c, h, w = input.shape
|
||||||
|
tmp_kernel = kernel[:, None, ...]
|
||||||
|
|
||||||
|
# Pad with "replicate for spatial dims, but with zeros for channel
|
||||||
|
spatial_pad = [kernel.size(1) // 2, kernel.size(1) // 2, kernel.size(2) // 2, kernel.size(2) // 2]
|
||||||
|
out_channels: int = 2
|
||||||
|
padded_inp = torch.nn.functional.pad(input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')
|
||||||
|
out = F.conv2d(padded_inp, tmp_kernel, groups=1, padding=0, stride=1)
|
||||||
|
return out.reshape(b, c, out_channels, h, w)
|
||||||
|
|
||||||
|
def rgb_to_grayscale(image, rgb_weights = None):
|
||||||
|
r"""Convert a RGB image to grayscale version of image.
|
||||||
|
|
||||||
|
.. image:: _static/img/rgb_to_grayscale.png
|
||||||
|
|
||||||
|
The image data is assumed to be in the range of (0, 1).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
image: RGB image to be converted to grayscale with shape :math:`(*,3,H,W)`.
|
||||||
|
rgb_weights: Weights that will be applied on each channel (RGB).
|
||||||
|
The sum of the weights should add up to one.
|
||||||
|
Returns:
|
||||||
|
grayscale version of the image with shape :math:`(*,1,H,W)`.
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/
|
||||||
|
color_conversions.html>`__.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
>>> input = torch.rand(2, 3, 4, 5)
|
||||||
|
>>> gray = rgb_to_grayscale(input) # 2x1x4x5
|
||||||
|
"""
|
||||||
|
|
||||||
|
if len(image.shape) < 3 or image.shape[-3] != 3:
|
||||||
|
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
|
||||||
|
|
||||||
|
if rgb_weights is None:
|
||||||
|
# 8 bit images
|
||||||
|
if image.dtype == torch.uint8:
|
||||||
|
rgb_weights = torch.tensor([76, 150, 29], device=image.device, dtype=torch.uint8)
|
||||||
|
# floating point images
|
||||||
|
elif image.dtype in (torch.float16, torch.float32, torch.float64):
|
||||||
|
rgb_weights = torch.tensor([0.299, 0.587, 0.114], device=image.device, dtype=image.dtype)
|
||||||
|
else:
|
||||||
|
raise TypeError(f"Unknown data type: {image.dtype}")
|
||||||
|
else:
|
||||||
|
# is tensor that we make sure is in the same device/dtype
|
||||||
|
rgb_weights = rgb_weights.to(image)
|
||||||
|
|
||||||
|
# unpack the color image channels with RGB order
|
||||||
|
r: Tensor = image[..., 0:1, :, :]
|
||||||
|
g: Tensor = image[..., 1:2, :, :]
|
||||||
|
b: Tensor = image[..., 2:3, :, :]
|
||||||
|
|
||||||
|
w_r, w_g, w_b = rgb_weights.unbind()
|
||||||
|
return w_r * r + w_g * g + w_b * b
|
||||||
|
|
||||||
|
def canny(
|
||||||
|
input,
|
||||||
|
low_threshold = 0.1,
|
||||||
|
high_threshold = 0.2,
|
||||||
|
kernel_size = 5,
|
||||||
|
sigma = 1,
|
||||||
|
hysteresis = True,
|
||||||
|
eps = 1e-6,
|
||||||
|
):
|
||||||
|
r"""Find edges of the input image and filters them using the Canny algorithm.
|
||||||
|
.. image:: _static/img/canny.png
|
||||||
|
Args:
|
||||||
|
input: input image tensor with shape :math:`(B,C,H,W)`.
|
||||||
|
low_threshold: lower threshold for the hysteresis procedure.
|
||||||
|
high_threshold: upper threshold for the hysteresis procedure.
|
||||||
|
kernel_size: the size of the kernel for the gaussian blur.
|
||||||
|
sigma: the standard deviation of the kernel for the gaussian blur.
|
||||||
|
hysteresis: if True, applies the hysteresis edge tracking.
|
||||||
|
Otherwise, the edges are divided between weak (0.5) and strong (1) edges.
|
||||||
|
eps: regularization number to avoid NaN during backprop.
|
||||||
|
Returns:
|
||||||
|
- the canny edge magnitudes map, shape of :math:`(B,1,H,W)`.
|
||||||
|
- the canny edge detection filtered by thresholds and hysteresis, shape of :math:`(B,1,H,W)`.
|
||||||
|
.. note::
|
||||||
|
See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/
|
||||||
|
canny.html>`__.
|
||||||
|
Example:
|
||||||
|
>>> input = torch.rand(5, 3, 4, 4)
|
||||||
|
>>> magnitude, edges = canny(input) # 5x3x4x4
|
||||||
|
>>> magnitude.shape
|
||||||
|
torch.Size([5, 1, 4, 4])
|
||||||
|
>>> edges.shape
|
||||||
|
torch.Size([5, 1, 4, 4])
|
||||||
|
"""
|
||||||
|
# KORNIA_CHECK_IS_TENSOR(input)
|
||||||
|
# KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
|
||||||
|
# KORNIA_CHECK(
|
||||||
|
# low_threshold <= high_threshold,
|
||||||
|
# "Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: "
|
||||||
|
# f"{low_threshold}>{high_threshold}",
|
||||||
|
# )
|
||||||
|
# KORNIA_CHECK(0 < low_threshold < 1, f'Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}')
|
||||||
|
# KORNIA_CHECK(0 < high_threshold < 1, f'Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}')
|
||||||
|
|
||||||
|
device = input.device
|
||||||
|
dtype = input.dtype
|
||||||
|
|
||||||
|
# To Grayscale
|
||||||
|
if input.shape[1] == 3:
|
||||||
|
input = rgb_to_grayscale(input)
|
||||||
|
|
||||||
|
# Gaussian filter
|
||||||
|
blurred: Tensor = gaussian_blur_2d(input, kernel_size, sigma)
|
||||||
|
|
||||||
|
# Compute the gradients
|
||||||
|
gradients: Tensor = spatial_gradient(blurred, normalized=False)
|
||||||
|
|
||||||
|
# Unpack the edges
|
||||||
|
gx: Tensor = gradients[:, :, 0]
|
||||||
|
gy: Tensor = gradients[:, :, 1]
|
||||||
|
|
||||||
|
# Compute gradient magnitude and angle
|
||||||
|
magnitude: Tensor = torch.sqrt(gx * gx + gy * gy + eps)
|
||||||
|
angle: Tensor = torch.atan2(gy, gx)
|
||||||
|
|
||||||
|
# Radians to Degrees
|
||||||
|
angle = 180.0 * angle / math.pi
|
||||||
|
|
||||||
|
# Round angle to the nearest 45 degree
|
||||||
|
angle = torch.round(angle / 45) * 45
|
||||||
|
|
||||||
|
# Non-maximal suppression
|
||||||
|
nms_kernels: Tensor = get_canny_nms_kernel(device, dtype)
|
||||||
|
nms_magnitude: Tensor = F.conv2d(magnitude, nms_kernels, padding=nms_kernels.shape[-1] // 2)
|
||||||
|
|
||||||
|
# Get the indices for both directions
|
||||||
|
positive_idx: Tensor = (angle / 45) % 8
|
||||||
|
positive_idx = positive_idx.long()
|
||||||
|
|
||||||
|
negative_idx: Tensor = ((angle / 45) + 4) % 8
|
||||||
|
negative_idx = negative_idx.long()
|
||||||
|
|
||||||
|
# Apply the non-maximum suppression to the different directions
|
||||||
|
channel_select_filtered_positive: Tensor = torch.gather(nms_magnitude, 1, positive_idx)
|
||||||
|
channel_select_filtered_negative: Tensor = torch.gather(nms_magnitude, 1, negative_idx)
|
||||||
|
|
||||||
|
channel_select_filtered: Tensor = torch.stack(
|
||||||
|
[channel_select_filtered_positive, channel_select_filtered_negative], 1
|
||||||
|
)
|
||||||
|
|
||||||
|
is_max: Tensor = channel_select_filtered.min(dim=1)[0] > 0.0
|
||||||
|
|
||||||
|
magnitude = magnitude * is_max
|
||||||
|
|
||||||
|
# Threshold
|
||||||
|
edges: Tensor = F.threshold(magnitude, low_threshold, 0.0)
|
||||||
|
|
||||||
|
low: Tensor = magnitude > low_threshold
|
||||||
|
high: Tensor = magnitude > high_threshold
|
||||||
|
|
||||||
|
edges = low * 0.5 + high * 0.5
|
||||||
|
edges = edges.to(dtype)
|
||||||
|
|
||||||
|
# Hysteresis
|
||||||
|
if hysteresis:
|
||||||
|
edges_old: Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)
|
||||||
|
hysteresis_kernels: Tensor = get_hysteresis_kernel(device, dtype)
|
||||||
|
|
||||||
|
while ((edges_old - edges).abs() != 0).any():
|
||||||
|
weak: Tensor = (edges == 0.5).float()
|
||||||
|
strong: Tensor = (edges == 1).float()
|
||||||
|
|
||||||
|
hysteresis_magnitude: Tensor = F.conv2d(
|
||||||
|
edges, hysteresis_kernels, padding=hysteresis_kernels.shape[-1] // 2
|
||||||
|
)
|
||||||
|
hysteresis_magnitude = (hysteresis_magnitude == 1).any(1, keepdim=True).to(dtype)
|
||||||
|
hysteresis_magnitude = hysteresis_magnitude * weak + strong
|
||||||
|
|
||||||
|
edges_old = edges.clone()
|
||||||
|
edges = hysteresis_magnitude + (hysteresis_magnitude == 0) * weak * 0.5
|
||||||
|
|
||||||
|
edges = hysteresis_magnitude
|
||||||
|
|
||||||
|
return magnitude, edges
|
||||||
|
|
||||||
|
|
||||||
|
class Canny:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {"image": ("IMAGE",),
|
||||||
|
"low_threshold": ("FLOAT", {"default": 0.4, "min": 0.01, "max": 0.99, "step": 0.01}),
|
||||||
|
"high_threshold": ("FLOAT", {"default": 0.8, "min": 0.01, "max": 0.99, "step": 0.01})
|
||||||
|
}}
|
||||||
|
|
||||||
|
RETURN_TYPES = ("IMAGE",)
|
||||||
|
FUNCTION = "detect_edge"
|
||||||
|
|
||||||
|
CATEGORY = "image/preprocessors"
|
||||||
|
|
||||||
|
def detect_edge(self, image, low_threshold, high_threshold):
|
||||||
|
output = canny(image.to(comfy.model_management.get_torch_device()).movedim(-1, 1), low_threshold, high_threshold)
|
||||||
|
img_out = output[1].cpu().repeat(1, 3, 1, 1).movedim(1, -1)
|
||||||
|
return (img_out,)
|
||||||
|
|
||||||
|
NODE_CLASS_MAPPINGS = {
|
||||||
|
"Canny": Canny,
|
||||||
|
}
|
||||||
56
comfy_extras/nodes_clip_sdxl.py
Normal file
56
comfy_extras/nodes_clip_sdxl.py
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
import torch
|
||||||
|
from nodes import MAX_RESOLUTION
|
||||||
|
|
||||||
|
class CLIPTextEncodeSDXLRefiner:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {
|
||||||
|
"ascore": ("FLOAT", {"default": 6.0, "min": 0.0, "max": 1000.0, "step": 0.01}),
|
||||||
|
"width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
|
"height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
|
"text": ("STRING", {"multiline": True}), "clip": ("CLIP", ),
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("CONDITIONING",)
|
||||||
|
FUNCTION = "encode"
|
||||||
|
|
||||||
|
CATEGORY = "advanced/conditioning"
|
||||||
|
|
||||||
|
def encode(self, clip, ascore, width, height, text):
|
||||||
|
tokens = clip.tokenize(text)
|
||||||
|
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
|
||||||
|
return ([[cond, {"pooled_output": pooled, "aesthetic_score": ascore, "width": width,"height": height}]], )
|
||||||
|
|
||||||
|
class CLIPTextEncodeSDXL:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {
|
||||||
|
"width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
|
"height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
|
"crop_w": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
|
"crop_h": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
|
"target_width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
|
"target_height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||||
|
"text_g": ("STRING", {"multiline": True, "default": "CLIP_G"}), "clip": ("CLIP", ),
|
||||||
|
"text_l": ("STRING", {"multiline": True, "default": "CLIP_L"}), "clip": ("CLIP", ),
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("CONDITIONING",)
|
||||||
|
FUNCTION = "encode"
|
||||||
|
|
||||||
|
CATEGORY = "advanced/conditioning"
|
||||||
|
|
||||||
|
def encode(self, clip, width, height, crop_w, crop_h, target_width, target_height, text_g, text_l):
|
||||||
|
tokens = clip.tokenize(text_g)
|
||||||
|
tokens["l"] = clip.tokenize(text_l)["l"]
|
||||||
|
if len(tokens["l"]) != len(tokens["g"]):
|
||||||
|
empty = clip.tokenize("")
|
||||||
|
while len(tokens["l"]) < len(tokens["g"]):
|
||||||
|
tokens["l"] += empty["l"]
|
||||||
|
while len(tokens["l"]) > len(tokens["g"]):
|
||||||
|
tokens["g"] += empty["g"]
|
||||||
|
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
|
||||||
|
return ([[cond, {"pooled_output": pooled, "width": width, "height": height, "crop_w": crop_w, "crop_h": crop_h, "target_width": target_width, "target_height": target_height}]], )
|
||||||
|
|
||||||
|
NODE_CLASS_MAPPINGS = {
|
||||||
|
"CLIPTextEncodeSDXLRefiner": CLIPTextEncodeSDXLRefiner,
|
||||||
|
"CLIPTextEncodeSDXL": CLIPTextEncodeSDXL,
|
||||||
|
}
|
||||||
@ -1,7 +1,40 @@
|
|||||||
|
import numpy as np
|
||||||
|
from scipy.ndimage import grey_dilation
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
from nodes import MAX_RESOLUTION
|
from nodes import MAX_RESOLUTION
|
||||||
|
|
||||||
|
def composite(destination, source, x, y, mask = None, multiplier = 8, resize_source = False):
|
||||||
|
if resize_source:
|
||||||
|
source = torch.nn.functional.interpolate(source, size=(destination.shape[2], destination.shape[3]), mode="bilinear")
|
||||||
|
|
||||||
|
x = max(-source.shape[3] * multiplier, min(x, destination.shape[3] * multiplier))
|
||||||
|
y = max(-source.shape[2] * multiplier, min(y, destination.shape[2] * multiplier))
|
||||||
|
|
||||||
|
left, top = (x // multiplier, y // multiplier)
|
||||||
|
right, bottom = (left + source.shape[3], top + source.shape[2],)
|
||||||
|
|
||||||
|
if mask is None:
|
||||||
|
mask = torch.ones_like(source)
|
||||||
|
else:
|
||||||
|
mask = mask.clone()
|
||||||
|
mask = torch.nn.functional.interpolate(mask[None, None], size=(source.shape[2], source.shape[3]), mode="bilinear")
|
||||||
|
mask = mask.repeat((source.shape[0], source.shape[1], 1, 1))
|
||||||
|
|
||||||
|
# calculate the bounds of the source that will be overlapping the destination
|
||||||
|
# this prevents the source trying to overwrite latent pixels that are out of bounds
|
||||||
|
# of the destination
|
||||||
|
visible_width, visible_height = (destination.shape[3] - left + min(0, x), destination.shape[2] - top + min(0, y),)
|
||||||
|
|
||||||
|
mask = mask[:, :, :visible_height, :visible_width]
|
||||||
|
inverse_mask = torch.ones_like(mask) - mask
|
||||||
|
|
||||||
|
source_portion = mask * source[:, :, :visible_height, :visible_width]
|
||||||
|
destination_portion = inverse_mask * destination[:, :, top:bottom, left:right]
|
||||||
|
|
||||||
|
destination[:, :, top:bottom, left:right] = source_portion + destination_portion
|
||||||
|
return destination
|
||||||
|
|
||||||
class LatentCompositeMasked:
|
class LatentCompositeMasked:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
@ -11,6 +44,7 @@ class LatentCompositeMasked:
|
|||||||
"source": ("LATENT",),
|
"source": ("LATENT",),
|
||||||
"x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
"x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
||||||
"y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
"y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
||||||
|
"resize_source": ("BOOLEAN", {"default": False}),
|
||||||
},
|
},
|
||||||
"optional": {
|
"optional": {
|
||||||
"mask": ("MASK",),
|
"mask": ("MASK",),
|
||||||
@ -21,40 +55,36 @@ class LatentCompositeMasked:
|
|||||||
|
|
||||||
CATEGORY = "latent"
|
CATEGORY = "latent"
|
||||||
|
|
||||||
def composite(self, destination, source, x, y, mask = None):
|
def composite(self, destination, source, x, y, resize_source, mask = None):
|
||||||
output = destination.copy()
|
output = destination.copy()
|
||||||
destination = destination["samples"].clone()
|
destination = destination["samples"].clone()
|
||||||
source = source["samples"]
|
source = source["samples"]
|
||||||
|
output["samples"] = composite(destination, source, x, y, mask, 8, resize_source)
|
||||||
|
return (output,)
|
||||||
|
|
||||||
x = max(-source.shape[3] * 8, min(x, destination.shape[3] * 8))
|
class ImageCompositeMasked:
|
||||||
y = max(-source.shape[2] * 8, min(y, destination.shape[2] * 8))
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {
|
||||||
|
"required": {
|
||||||
|
"destination": ("IMAGE",),
|
||||||
|
"source": ("IMAGE",),
|
||||||
|
"x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
|
||||||
|
"y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
|
||||||
|
"resize_source": ("BOOLEAN", {"default": False}),
|
||||||
|
},
|
||||||
|
"optional": {
|
||||||
|
"mask": ("MASK",),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RETURN_TYPES = ("IMAGE",)
|
||||||
|
FUNCTION = "composite"
|
||||||
|
|
||||||
left, top = (x // 8, y // 8)
|
CATEGORY = "image"
|
||||||
right, bottom = (left + source.shape[3], top + source.shape[2],)
|
|
||||||
|
|
||||||
|
|
||||||
if mask is None:
|
|
||||||
mask = torch.ones_like(source)
|
|
||||||
else:
|
|
||||||
mask = mask.clone()
|
|
||||||
mask = torch.nn.functional.interpolate(mask[None, None], size=(source.shape[2], source.shape[3]), mode="bilinear")
|
|
||||||
mask = mask.repeat((source.shape[0], source.shape[1], 1, 1))
|
|
||||||
|
|
||||||
# calculate the bounds of the source that will be overlapping the destination
|
|
||||||
# this prevents the source trying to overwrite latent pixels that are out of bounds
|
|
||||||
# of the destination
|
|
||||||
visible_width, visible_height = (destination.shape[3] - left + min(0, x), destination.shape[2] - top + min(0, y),)
|
|
||||||
|
|
||||||
mask = mask[:, :, :visible_height, :visible_width]
|
|
||||||
inverse_mask = torch.ones_like(mask) - mask
|
|
||||||
|
|
||||||
source_portion = mask * source[:, :, :visible_height, :visible_width]
|
|
||||||
destination_portion = inverse_mask * destination[:, :, top:bottom, left:right]
|
|
||||||
|
|
||||||
destination[:, :, top:bottom, left:right] = source_portion + destination_portion
|
|
||||||
|
|
||||||
output["samples"] = destination
|
|
||||||
|
|
||||||
|
def composite(self, destination, source, x, y, resize_source, mask = None):
|
||||||
|
destination = destination.clone().movedim(-1, 1)
|
||||||
|
output = composite(destination, source.movedim(-1, 1), x, y, mask, 1, resize_source).movedim(1, -1)
|
||||||
return (output,)
|
return (output,)
|
||||||
|
|
||||||
class MaskToImage:
|
class MaskToImage:
|
||||||
@ -95,6 +125,27 @@ class ImageToMask:
|
|||||||
mask = image[0, :, :, channels.index(channel)]
|
mask = image[0, :, :, channels.index(channel)]
|
||||||
return (mask,)
|
return (mask,)
|
||||||
|
|
||||||
|
class ImageColorToMask:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {
|
||||||
|
"required": {
|
||||||
|
"image": ("IMAGE",),
|
||||||
|
"color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CATEGORY = "mask"
|
||||||
|
|
||||||
|
RETURN_TYPES = ("MASK",)
|
||||||
|
FUNCTION = "image_to_mask"
|
||||||
|
|
||||||
|
def image_to_mask(self, image, color):
|
||||||
|
temp = (torch.clamp(image[0], 0, 1.0) * 255.0).round().to(torch.int)
|
||||||
|
temp = torch.bitwise_left_shift(temp[:,:,0], 16) + torch.bitwise_left_shift(temp[:,:,1], 8) + temp[:,:,2]
|
||||||
|
mask = torch.where(temp == color, 255, 0).float()
|
||||||
|
return (mask,)
|
||||||
|
|
||||||
class SolidMask:
|
class SolidMask:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(cls):
|
def INPUT_TYPES(cls):
|
||||||
@ -249,17 +300,49 @@ class FeatherMask:
|
|||||||
|
|
||||||
return (output,)
|
return (output,)
|
||||||
|
|
||||||
|
class GrowMask:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(cls):
|
||||||
|
return {
|
||||||
|
"required": {
|
||||||
|
"mask": ("MASK",),
|
||||||
|
"expand": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
|
||||||
|
"tapered_corners": ("BOOLEAN", {"default": True}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
CATEGORY = "mask"
|
||||||
|
|
||||||
|
RETURN_TYPES = ("MASK",)
|
||||||
|
|
||||||
|
FUNCTION = "expand_mask"
|
||||||
|
|
||||||
|
def expand_mask(self, mask, expand, tapered_corners):
|
||||||
|
c = 0 if tapered_corners else 1
|
||||||
|
kernel = np.array([[c, 1, c],
|
||||||
|
[1, 1, 1],
|
||||||
|
[c, 1, c]])
|
||||||
|
output = mask.numpy().copy()
|
||||||
|
while expand > 0:
|
||||||
|
output = grey_dilation(output, footprint=kernel)
|
||||||
|
expand -= 1
|
||||||
|
output = torch.from_numpy(output)
|
||||||
|
return (output,)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
NODE_CLASS_MAPPINGS = {
|
NODE_CLASS_MAPPINGS = {
|
||||||
"LatentCompositeMasked": LatentCompositeMasked,
|
"LatentCompositeMasked": LatentCompositeMasked,
|
||||||
|
"ImageCompositeMasked": ImageCompositeMasked,
|
||||||
"MaskToImage": MaskToImage,
|
"MaskToImage": MaskToImage,
|
||||||
"ImageToMask": ImageToMask,
|
"ImageToMask": ImageToMask,
|
||||||
|
"ImageColorToMask": ImageColorToMask,
|
||||||
"SolidMask": SolidMask,
|
"SolidMask": SolidMask,
|
||||||
"InvertMask": InvertMask,
|
"InvertMask": InvertMask,
|
||||||
"CropMask": CropMask,
|
"CropMask": CropMask,
|
||||||
"MaskComposite": MaskComposite,
|
"MaskComposite": MaskComposite,
|
||||||
"FeatherMask": FeatherMask,
|
"FeatherMask": FeatherMask,
|
||||||
|
"GrowMask": GrowMask,
|
||||||
}
|
}
|
||||||
|
|
||||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||||
|
|||||||
@ -1,9 +1,13 @@
|
|||||||
import comfy.sd
|
import comfy.sd
|
||||||
import comfy.utils
|
import comfy.utils
|
||||||
|
import comfy.model_base
|
||||||
|
|
||||||
import folder_paths
|
import folder_paths
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
from comfy.cli_args import args
|
||||||
|
|
||||||
class ModelMergeSimple:
|
class ModelMergeSimple:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
@ -14,13 +18,34 @@ class ModelMergeSimple:
|
|||||||
RETURN_TYPES = ("MODEL",)
|
RETURN_TYPES = ("MODEL",)
|
||||||
FUNCTION = "merge"
|
FUNCTION = "merge"
|
||||||
|
|
||||||
CATEGORY = "_for_testing/model_merging"
|
CATEGORY = "advanced/model_merging"
|
||||||
|
|
||||||
def merge(self, model1, model2, ratio):
|
def merge(self, model1, model2, ratio):
|
||||||
m = model1.clone()
|
m = model1.clone()
|
||||||
sd = model2.model_state_dict("diffusion_model.")
|
kp = model2.get_key_patches("diffusion_model.")
|
||||||
for k in sd:
|
for k in kp:
|
||||||
m.add_patches({k: (sd[k], )}, 1.0 - ratio, ratio)
|
m.add_patches({k: kp[k]}, 1.0 - ratio, ratio)
|
||||||
|
return (m, )
|
||||||
|
|
||||||
|
class CLIPMergeSimple:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": { "clip1": ("CLIP",),
|
||||||
|
"clip2": ("CLIP",),
|
||||||
|
"ratio": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("CLIP",)
|
||||||
|
FUNCTION = "merge"
|
||||||
|
|
||||||
|
CATEGORY = "advanced/model_merging"
|
||||||
|
|
||||||
|
def merge(self, clip1, clip2, ratio):
|
||||||
|
m = clip1.clone()
|
||||||
|
kp = clip2.get_key_patches()
|
||||||
|
for k in kp:
|
||||||
|
if k.endswith(".position_ids") or k.endswith(".logit_scale"):
|
||||||
|
continue
|
||||||
|
m.add_patches({k: kp[k]}, 1.0 - ratio, ratio)
|
||||||
return (m, )
|
return (m, )
|
||||||
|
|
||||||
class ModelMergeBlocks:
|
class ModelMergeBlocks:
|
||||||
@ -35,22 +60,24 @@ class ModelMergeBlocks:
|
|||||||
RETURN_TYPES = ("MODEL",)
|
RETURN_TYPES = ("MODEL",)
|
||||||
FUNCTION = "merge"
|
FUNCTION = "merge"
|
||||||
|
|
||||||
CATEGORY = "_for_testing/model_merging"
|
CATEGORY = "advanced/model_merging"
|
||||||
|
|
||||||
def merge(self, model1, model2, **kwargs):
|
def merge(self, model1, model2, **kwargs):
|
||||||
m = model1.clone()
|
m = model1.clone()
|
||||||
sd = model2.model_state_dict("diffusion_model.")
|
kp = model2.get_key_patches("diffusion_model.")
|
||||||
default_ratio = next(iter(kwargs.values()))
|
default_ratio = next(iter(kwargs.values()))
|
||||||
|
|
||||||
for k in sd:
|
for k in kp:
|
||||||
ratio = default_ratio
|
ratio = default_ratio
|
||||||
k_unet = k[len("diffusion_model."):]
|
k_unet = k[len("diffusion_model."):]
|
||||||
|
|
||||||
|
last_arg_size = 0
|
||||||
for arg in kwargs:
|
for arg in kwargs:
|
||||||
if k_unet.startswith(arg):
|
if k_unet.startswith(arg) and last_arg_size < len(arg):
|
||||||
ratio = kwargs[arg]
|
ratio = kwargs[arg]
|
||||||
|
last_arg_size = len(arg)
|
||||||
|
|
||||||
m.add_patches({k: (sd[k], )}, 1.0 - ratio, ratio)
|
m.add_patches({k: kp[k]}, 1.0 - ratio, ratio)
|
||||||
return (m, )
|
return (m, )
|
||||||
|
|
||||||
class CheckpointSave:
|
class CheckpointSave:
|
||||||
@ -68,7 +95,7 @@ class CheckpointSave:
|
|||||||
FUNCTION = "save"
|
FUNCTION = "save"
|
||||||
OUTPUT_NODE = True
|
OUTPUT_NODE = True
|
||||||
|
|
||||||
CATEGORY = "_for_testing/model_merging"
|
CATEGORY = "advanced/model_merging"
|
||||||
|
|
||||||
def save(self, model, clip, vae, filename_prefix, prompt=None, extra_pnginfo=None):
|
def save(self, model, clip, vae, filename_prefix, prompt=None, extra_pnginfo=None):
|
||||||
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
|
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
|
||||||
@ -76,10 +103,36 @@ class CheckpointSave:
|
|||||||
if prompt is not None:
|
if prompt is not None:
|
||||||
prompt_info = json.dumps(prompt)
|
prompt_info = json.dumps(prompt)
|
||||||
|
|
||||||
metadata = {"prompt": prompt_info}
|
metadata = {}
|
||||||
if extra_pnginfo is not None:
|
|
||||||
for x in extra_pnginfo:
|
enable_modelspec = True
|
||||||
metadata[x] = json.dumps(extra_pnginfo[x])
|
if isinstance(model.model, comfy.model_base.SDXL):
|
||||||
|
metadata["modelspec.architecture"] = "stable-diffusion-xl-v1-base"
|
||||||
|
elif isinstance(model.model, comfy.model_base.SDXLRefiner):
|
||||||
|
metadata["modelspec.architecture"] = "stable-diffusion-xl-v1-refiner"
|
||||||
|
else:
|
||||||
|
enable_modelspec = False
|
||||||
|
|
||||||
|
if enable_modelspec:
|
||||||
|
metadata["modelspec.sai_model_spec"] = "1.0.0"
|
||||||
|
metadata["modelspec.implementation"] = "sgm"
|
||||||
|
metadata["modelspec.title"] = "{} {}".format(filename, counter)
|
||||||
|
|
||||||
|
#TODO:
|
||||||
|
# "stable-diffusion-v1", "stable-diffusion-v1-inpainting", "stable-diffusion-v2-512",
|
||||||
|
# "stable-diffusion-v2-768-v", "stable-diffusion-v2-unclip-l", "stable-diffusion-v2-unclip-h",
|
||||||
|
# "v2-inpainting"
|
||||||
|
|
||||||
|
if model.model.model_type == comfy.model_base.ModelType.EPS:
|
||||||
|
metadata["modelspec.predict_key"] = "epsilon"
|
||||||
|
elif model.model.model_type == comfy.model_base.ModelType.V_PREDICTION:
|
||||||
|
metadata["modelspec.predict_key"] = "v"
|
||||||
|
|
||||||
|
if not args.disable_metadata:
|
||||||
|
metadata["prompt"] = prompt_info
|
||||||
|
if extra_pnginfo is not None:
|
||||||
|
for x in extra_pnginfo:
|
||||||
|
metadata[x] = json.dumps(extra_pnginfo[x])
|
||||||
|
|
||||||
output_checkpoint = f"{filename}_{counter:05}_.safetensors"
|
output_checkpoint = f"{filename}_{counter:05}_.safetensors"
|
||||||
output_checkpoint = os.path.join(full_output_folder, output_checkpoint)
|
output_checkpoint = os.path.join(full_output_folder, output_checkpoint)
|
||||||
@ -92,4 +145,5 @@ NODE_CLASS_MAPPINGS = {
|
|||||||
"ModelMergeSimple": ModelMergeSimple,
|
"ModelMergeSimple": ModelMergeSimple,
|
||||||
"ModelMergeBlocks": ModelMergeBlocks,
|
"ModelMergeBlocks": ModelMergeBlocks,
|
||||||
"CheckpointSave": CheckpointSave,
|
"CheckpointSave": CheckpointSave,
|
||||||
|
"CLIPMergeSimple": CLIPMergeSimple,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,6 +2,7 @@ import numpy as np
|
|||||||
import torch
|
import torch
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
import math
|
||||||
|
|
||||||
import comfy.utils
|
import comfy.utils
|
||||||
|
|
||||||
@ -59,8 +60,8 @@ class Blend:
|
|||||||
def g(self, x):
|
def g(self, x):
|
||||||
return torch.where(x <= 0.25, ((16 * x - 12) * x + 4) * x, torch.sqrt(x))
|
return torch.where(x <= 0.25, ((16 * x - 12) * x + 4) * x, torch.sqrt(x))
|
||||||
|
|
||||||
def gaussian_kernel(kernel_size: int, sigma: float):
|
def gaussian_kernel(kernel_size: int, sigma: float, device=None):
|
||||||
x, y = torch.meshgrid(torch.linspace(-1, 1, kernel_size), torch.linspace(-1, 1, kernel_size), indexing="ij")
|
x, y = torch.meshgrid(torch.linspace(-1, 1, kernel_size, device=device), torch.linspace(-1, 1, kernel_size, device=device), indexing="ij")
|
||||||
d = torch.sqrt(x * x + y * y)
|
d = torch.sqrt(x * x + y * y)
|
||||||
g = torch.exp(-(d * d) / (2.0 * sigma * sigma))
|
g = torch.exp(-(d * d) / (2.0 * sigma * sigma))
|
||||||
return g / g.sum()
|
return g / g.sum()
|
||||||
@ -101,7 +102,7 @@ class Blur:
|
|||||||
batch_size, height, width, channels = image.shape
|
batch_size, height, width, channels = image.shape
|
||||||
|
|
||||||
kernel_size = blur_radius * 2 + 1
|
kernel_size = blur_radius * 2 + 1
|
||||||
kernel = gaussian_kernel(kernel_size, sigma).repeat(channels, 1, 1).unsqueeze(1)
|
kernel = gaussian_kernel(kernel_size, sigma, device=image.device).repeat(channels, 1, 1).unsqueeze(1)
|
||||||
|
|
||||||
image = image.permute(0, 3, 1, 2) # Torch wants (B, C, H, W) we use (B, H, W, C)
|
image = image.permute(0, 3, 1, 2) # Torch wants (B, C, H, W) we use (B, H, W, C)
|
||||||
padded_image = F.pad(image, (blur_radius,blur_radius,blur_radius,blur_radius), 'reflect')
|
padded_image = F.pad(image, (blur_radius,blur_radius,blur_radius,blur_radius), 'reflect')
|
||||||
@ -209,9 +210,36 @@ class Sharpen:
|
|||||||
|
|
||||||
return (result,)
|
return (result,)
|
||||||
|
|
||||||
|
class ImageScaleToTotalPixels:
|
||||||
|
upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic"]
|
||||||
|
crop_methods = ["disabled", "center"]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
|
||||||
|
"megapixels": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 16.0, "step": 0.01}),
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("IMAGE",)
|
||||||
|
FUNCTION = "upscale"
|
||||||
|
|
||||||
|
CATEGORY = "image/upscaling"
|
||||||
|
|
||||||
|
def upscale(self, image, upscale_method, megapixels):
|
||||||
|
samples = image.movedim(-1,1)
|
||||||
|
total = int(megapixels * 1024 * 1024)
|
||||||
|
|
||||||
|
scale_by = math.sqrt(total / (samples.shape[3] * samples.shape[2]))
|
||||||
|
width = round(samples.shape[3] * scale_by)
|
||||||
|
height = round(samples.shape[2] * scale_by)
|
||||||
|
|
||||||
|
s = comfy.utils.common_upscale(samples, width, height, upscale_method, "disabled")
|
||||||
|
s = s.movedim(1,-1)
|
||||||
|
return (s,)
|
||||||
|
|
||||||
NODE_CLASS_MAPPINGS = {
|
NODE_CLASS_MAPPINGS = {
|
||||||
"ImageBlend": Blend,
|
"ImageBlend": Blend,
|
||||||
"ImageBlur": Blur,
|
"ImageBlur": Blur,
|
||||||
"ImageQuantize": Quantize,
|
"ImageQuantize": Quantize,
|
||||||
"ImageSharpen": Sharpen,
|
"ImageSharpen": Sharpen,
|
||||||
|
"ImageScaleToTotalPixels": ImageScaleToTotalPixels,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,6 +18,8 @@ class UpscaleModelLoader:
|
|||||||
def load_model(self, model_name):
|
def load_model(self, model_name):
|
||||||
model_path = folder_paths.get_full_path("upscale_models", model_name)
|
model_path = folder_paths.get_full_path("upscale_models", model_name)
|
||||||
sd = comfy.utils.load_torch_file(model_path, safe_load=True)
|
sd = comfy.utils.load_torch_file(model_path, safe_load=True)
|
||||||
|
if "module.layers.0.residual_group.blocks.0.norm1.weight" in sd:
|
||||||
|
sd = comfy.utils.state_dict_prefix_replace(sd, {"module.":""})
|
||||||
out = model_loading.load_state_dict(sd).eval()
|
out = model_loading.load_state_dict(sd).eval()
|
||||||
return (out, )
|
return (out, )
|
||||||
|
|
||||||
@ -37,12 +39,23 @@ class ImageUpscaleWithModel:
|
|||||||
device = model_management.get_torch_device()
|
device = model_management.get_torch_device()
|
||||||
upscale_model.to(device)
|
upscale_model.to(device)
|
||||||
in_img = image.movedim(-1,-3).to(device)
|
in_img = image.movedim(-1,-3).to(device)
|
||||||
|
free_memory = model_management.get_free_memory(device)
|
||||||
|
|
||||||
|
tile = 512
|
||||||
|
overlap = 32
|
||||||
|
|
||||||
|
oom = True
|
||||||
|
while oom:
|
||||||
|
try:
|
||||||
|
steps = in_img.shape[0] * comfy.utils.get_tiled_scale_steps(in_img.shape[3], in_img.shape[2], tile_x=tile, tile_y=tile, overlap=overlap)
|
||||||
|
pbar = comfy.utils.ProgressBar(steps)
|
||||||
|
s = comfy.utils.tiled_scale(in_img, lambda a: upscale_model(a), tile_x=tile, tile_y=tile, overlap=overlap, upscale_amount=upscale_model.scale, pbar=pbar)
|
||||||
|
oom = False
|
||||||
|
except model_management.OOM_EXCEPTION as e:
|
||||||
|
tile //= 2
|
||||||
|
if tile < 128:
|
||||||
|
raise e
|
||||||
|
|
||||||
tile = 128 + 64
|
|
||||||
overlap = 8
|
|
||||||
steps = in_img.shape[0] * comfy.utils.get_tiled_scale_steps(in_img.shape[3], in_img.shape[2], tile_x=tile, tile_y=tile, overlap=overlap)
|
|
||||||
pbar = comfy.utils.ProgressBar(steps)
|
|
||||||
s = comfy.utils.tiled_scale(in_img, lambda a: upscale_model(a), tile_x=tile, tile_y=tile, overlap=overlap, upscale_amount=upscale_model.scale, pbar=pbar)
|
|
||||||
upscale_model.cpu()
|
upscale_model.cpu()
|
||||||
s = torch.clamp(s.movedim(-3,-1), min=0, max=1.0)
|
s = torch.clamp(s.movedim(-3,-1), min=0, max=1.0)
|
||||||
return (s,)
|
return (s,)
|
||||||
|
|||||||
84
cuda_malloc.py
Normal file
84
cuda_malloc.py
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
import os
|
||||||
|
import importlib.util
|
||||||
|
from comfy.cli_args import args
|
||||||
|
|
||||||
|
#Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import.
|
||||||
|
def get_gpu_names():
|
||||||
|
if os.name == 'nt':
|
||||||
|
import ctypes
|
||||||
|
|
||||||
|
# Define necessary C structures and types
|
||||||
|
class DISPLAY_DEVICEA(ctypes.Structure):
|
||||||
|
_fields_ = [
|
||||||
|
('cb', ctypes.c_ulong),
|
||||||
|
('DeviceName', ctypes.c_char * 32),
|
||||||
|
('DeviceString', ctypes.c_char * 128),
|
||||||
|
('StateFlags', ctypes.c_ulong),
|
||||||
|
('DeviceID', ctypes.c_char * 128),
|
||||||
|
('DeviceKey', ctypes.c_char * 128)
|
||||||
|
]
|
||||||
|
|
||||||
|
# Load user32.dll
|
||||||
|
user32 = ctypes.windll.user32
|
||||||
|
|
||||||
|
# Call EnumDisplayDevicesA
|
||||||
|
def enum_display_devices():
|
||||||
|
device_info = DISPLAY_DEVICEA()
|
||||||
|
device_info.cb = ctypes.sizeof(device_info)
|
||||||
|
device_index = 0
|
||||||
|
gpu_names = set()
|
||||||
|
|
||||||
|
while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0):
|
||||||
|
device_index += 1
|
||||||
|
gpu_names.add(device_info.DeviceString.decode('utf-8'))
|
||||||
|
return gpu_names
|
||||||
|
return enum_display_devices()
|
||||||
|
else:
|
||||||
|
return set()
|
||||||
|
|
||||||
|
blacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeForce GTX 950", "GeForce 945M",
|
||||||
|
"GeForce 940M", "GeForce 930M", "GeForce 920M", "GeForce 910M", "GeForce GTX 750", "GeForce GTX 745", "Quadro K620",
|
||||||
|
"Quadro K1200", "Quadro K2200", "Quadro M500", "Quadro M520", "Quadro M600", "Quadro M620", "Quadro M1000",
|
||||||
|
"Quadro M1200", "Quadro M2000", "Quadro M2200", "Quadro M3000", "Quadro M4000", "Quadro M5000", "Quadro M5500", "Quadro M6000",
|
||||||
|
"GeForce MX110", "GeForce MX130", "GeForce 830M", "GeForce 840M", "GeForce GTX 850M", "GeForce GTX 860M",
|
||||||
|
"GeForce GTX 1650", "GeForce GTX 1630"
|
||||||
|
}
|
||||||
|
|
||||||
|
def cuda_malloc_supported():
|
||||||
|
try:
|
||||||
|
names = get_gpu_names()
|
||||||
|
except:
|
||||||
|
names = set()
|
||||||
|
for x in names:
|
||||||
|
if "NVIDIA" in x:
|
||||||
|
for b in blacklist:
|
||||||
|
if b in x:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
if not args.cuda_malloc:
|
||||||
|
try:
|
||||||
|
version = ""
|
||||||
|
torch_spec = importlib.util.find_spec("torch")
|
||||||
|
for folder in torch_spec.submodule_search_locations:
|
||||||
|
ver_file = os.path.join(folder, "version.py")
|
||||||
|
if os.path.isfile(ver_file):
|
||||||
|
spec = importlib.util.spec_from_file_location("torch_version_import", ver_file)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
version = module.__version__
|
||||||
|
if int(version[0]) >= 2: #enable by default for torch version 2.0 and up
|
||||||
|
args.cuda_malloc = cuda_malloc_supported()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
if args.cuda_malloc and not args.disable_cuda_malloc:
|
||||||
|
env_var = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', None)
|
||||||
|
if env_var is None:
|
||||||
|
env_var = "backend:cudaMallocAsync"
|
||||||
|
else:
|
||||||
|
env_var += ",backend:cudaMallocAsync"
|
||||||
|
|
||||||
|
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = env_var
|
||||||
@ -51,9 +51,10 @@ class Example:
|
|||||||
"default": 0,
|
"default": 0,
|
||||||
"min": 0, #Minimum value
|
"min": 0, #Minimum value
|
||||||
"max": 4096, #Maximum value
|
"max": 4096, #Maximum value
|
||||||
"step": 64 #Slider's step
|
"step": 64, #Slider's step
|
||||||
|
"display": "number" # Cosmetic only: display as "number" or "slider"
|
||||||
}),
|
}),
|
||||||
"float_field": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
"float_field": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01, "display": "number"}),
|
||||||
"print_to_screen": (["enable", "disable"],),
|
"print_to_screen": (["enable", "disable"],),
|
||||||
"string_field": ("STRING", {
|
"string_field": ("STRING", {
|
||||||
"multiline": False, #True if you want the field to look like the one on the ClipTextEncode node
|
"multiline": False, #True if you want the field to look like the one on the ClipTextEncode node
|
||||||
|
|||||||
44
execution.py
44
execution.py
@ -6,7 +6,6 @@ import threading
|
|||||||
import heapq
|
import heapq
|
||||||
import traceback
|
import traceback
|
||||||
import gc
|
import gc
|
||||||
import time
|
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
import nodes
|
import nodes
|
||||||
@ -22,7 +21,8 @@ def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_da
|
|||||||
input_unique_id = input_data[0]
|
input_unique_id = input_data[0]
|
||||||
output_index = input_data[1]
|
output_index = input_data[1]
|
||||||
if input_unique_id not in outputs:
|
if input_unique_id not in outputs:
|
||||||
return None
|
input_data_all[x] = (None,)
|
||||||
|
continue
|
||||||
obj = outputs[input_unique_id][output_index]
|
obj = outputs[input_unique_id][output_index]
|
||||||
input_data_all[x] = obj
|
input_data_all[x] = obj
|
||||||
else:
|
else:
|
||||||
@ -43,11 +43,14 @@ def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_da
|
|||||||
|
|
||||||
def map_node_over_list(obj, input_data_all, func, allow_interrupt=False):
|
def map_node_over_list(obj, input_data_all, func, allow_interrupt=False):
|
||||||
# check if node wants the lists
|
# check if node wants the lists
|
||||||
intput_is_list = False
|
input_is_list = False
|
||||||
if hasattr(obj, "INPUT_IS_LIST"):
|
if hasattr(obj, "INPUT_IS_LIST"):
|
||||||
intput_is_list = obj.INPUT_IS_LIST
|
input_is_list = obj.INPUT_IS_LIST
|
||||||
|
|
||||||
max_len_input = max([len(x) for x in input_data_all.values()])
|
if len(input_data_all) == 0:
|
||||||
|
max_len_input = 0
|
||||||
|
else:
|
||||||
|
max_len_input = max([len(x) for x in input_data_all.values()])
|
||||||
|
|
||||||
# get a slice of inputs, repeat last input when list isn't long enough
|
# get a slice of inputs, repeat last input when list isn't long enough
|
||||||
def slice_dict(d, i):
|
def slice_dict(d, i):
|
||||||
@ -57,10 +60,14 @@ def map_node_over_list(obj, input_data_all, func, allow_interrupt=False):
|
|||||||
return d_new
|
return d_new
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
if intput_is_list:
|
if input_is_list:
|
||||||
if allow_interrupt:
|
if allow_interrupt:
|
||||||
nodes.before_node_execution()
|
nodes.before_node_execution()
|
||||||
results.append(getattr(obj, func)(**input_data_all))
|
results.append(getattr(obj, func)(**input_data_all))
|
||||||
|
elif max_len_input == 0:
|
||||||
|
if allow_interrupt:
|
||||||
|
nodes.before_node_execution()
|
||||||
|
results.append(getattr(obj, func)())
|
||||||
else:
|
else:
|
||||||
for i in range(max_len_input):
|
for i in range(max_len_input):
|
||||||
if allow_interrupt:
|
if allow_interrupt:
|
||||||
@ -110,7 +117,7 @@ def format_value(x):
|
|||||||
else:
|
else:
|
||||||
return str(x)
|
return str(x)
|
||||||
|
|
||||||
def recursive_execute(server, prompt, outputs, current_item, extra_data, executed, prompt_id, outputs_ui):
|
def recursive_execute(server, prompt, outputs, current_item, extra_data, executed, prompt_id, outputs_ui, object_storage):
|
||||||
unique_id = current_item
|
unique_id = current_item
|
||||||
inputs = prompt[unique_id]['inputs']
|
inputs = prompt[unique_id]['inputs']
|
||||||
class_type = prompt[unique_id]['class_type']
|
class_type = prompt[unique_id]['class_type']
|
||||||
@ -125,7 +132,7 @@ def recursive_execute(server, prompt, outputs, current_item, extra_data, execute
|
|||||||
input_unique_id = input_data[0]
|
input_unique_id = input_data[0]
|
||||||
output_index = input_data[1]
|
output_index = input_data[1]
|
||||||
if input_unique_id not in outputs:
|
if input_unique_id not in outputs:
|
||||||
result = recursive_execute(server, prompt, outputs, input_unique_id, extra_data, executed, prompt_id, outputs_ui)
|
result = recursive_execute(server, prompt, outputs, input_unique_id, extra_data, executed, prompt_id, outputs_ui, object_storage)
|
||||||
if result[0] is not True:
|
if result[0] is not True:
|
||||||
# Another node failed further upstream
|
# Another node failed further upstream
|
||||||
return result
|
return result
|
||||||
@ -136,7 +143,11 @@ def recursive_execute(server, prompt, outputs, current_item, extra_data, execute
|
|||||||
if server.client_id is not None:
|
if server.client_id is not None:
|
||||||
server.last_node_id = unique_id
|
server.last_node_id = unique_id
|
||||||
server.send_sync("executing", { "node": unique_id, "prompt_id": prompt_id }, server.client_id)
|
server.send_sync("executing", { "node": unique_id, "prompt_id": prompt_id }, server.client_id)
|
||||||
obj = class_def()
|
|
||||||
|
obj = object_storage.get((unique_id, class_type), None)
|
||||||
|
if obj is None:
|
||||||
|
obj = class_def()
|
||||||
|
object_storage[(unique_id, class_type)] = obj
|
||||||
|
|
||||||
output_data, output_ui = get_output_data(obj, input_data_all)
|
output_data, output_ui = get_output_data(obj, input_data_all)
|
||||||
outputs[unique_id] = output_data
|
outputs[unique_id] = output_data
|
||||||
@ -256,6 +267,7 @@ def recursive_output_delete_if_changed(prompt, old_prompt, outputs, current_item
|
|||||||
class PromptExecutor:
|
class PromptExecutor:
|
||||||
def __init__(self, server):
|
def __init__(self, server):
|
||||||
self.outputs = {}
|
self.outputs = {}
|
||||||
|
self.object_storage = {}
|
||||||
self.outputs_ui = {}
|
self.outputs_ui = {}
|
||||||
self.old_prompt = {}
|
self.old_prompt = {}
|
||||||
self.server = server
|
self.server = server
|
||||||
@ -322,6 +334,17 @@ class PromptExecutor:
|
|||||||
for o in to_delete:
|
for o in to_delete:
|
||||||
d = self.outputs.pop(o)
|
d = self.outputs.pop(o)
|
||||||
del d
|
del d
|
||||||
|
to_delete = []
|
||||||
|
for o in self.object_storage:
|
||||||
|
if o[0] not in prompt:
|
||||||
|
to_delete += [o]
|
||||||
|
else:
|
||||||
|
p = prompt[o[0]]
|
||||||
|
if o[1] != p['class_type']:
|
||||||
|
to_delete += [o]
|
||||||
|
for o in to_delete:
|
||||||
|
d = self.object_storage.pop(o)
|
||||||
|
del d
|
||||||
|
|
||||||
for x in prompt:
|
for x in prompt:
|
||||||
recursive_output_delete_if_changed(prompt, self.old_prompt, self.outputs, x)
|
recursive_output_delete_if_changed(prompt, self.old_prompt, self.outputs, x)
|
||||||
@ -332,6 +355,7 @@ class PromptExecutor:
|
|||||||
d = self.outputs_ui.pop(x)
|
d = self.outputs_ui.pop(x)
|
||||||
del d
|
del d
|
||||||
|
|
||||||
|
comfy.model_management.cleanup_models()
|
||||||
if self.server.client_id is not None:
|
if self.server.client_id is not None:
|
||||||
self.server.send_sync("execution_cached", { "nodes": list(current_outputs) , "prompt_id": prompt_id}, self.server.client_id)
|
self.server.send_sync("execution_cached", { "nodes": list(current_outputs) , "prompt_id": prompt_id}, self.server.client_id)
|
||||||
executed = set()
|
executed = set()
|
||||||
@ -349,7 +373,7 @@ class PromptExecutor:
|
|||||||
# This call shouldn't raise anything if there's an error deep in
|
# This call shouldn't raise anything if there's an error deep in
|
||||||
# the actual SD code, instead it will report the node where the
|
# the actual SD code, instead it will report the node where the
|
||||||
# error was raised
|
# error was raised
|
||||||
success, error, ex = recursive_execute(self.server, prompt, self.outputs, output_node_id, extra_data, executed, prompt_id, self.outputs_ui)
|
success, error, ex = recursive_execute(self.server, prompt, self.outputs, output_node_id, extra_data, executed, prompt_id, self.outputs_ui, self.object_storage)
|
||||||
if success is not True:
|
if success is not True:
|
||||||
self.handle_execution_error(prompt_id, prompt, current_outputs, executed, error, ex)
|
self.handle_execution_error(prompt_id, prompt, current_outputs, executed, error, ex)
|
||||||
break
|
break
|
||||||
|
|||||||
@ -13,6 +13,7 @@ a111:
|
|||||||
models/LyCORIS
|
models/LyCORIS
|
||||||
upscale_models: |
|
upscale_models: |
|
||||||
models/ESRGAN
|
models/ESRGAN
|
||||||
|
models/RealESRGAN
|
||||||
models/SwinIR
|
models/SwinIR
|
||||||
embeddings: embeddings
|
embeddings: embeddings
|
||||||
hypernetworks: models/hypernetworks
|
hypernetworks: models/hypernetworks
|
||||||
|
|||||||
@ -1,19 +1,19 @@
|
|||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
|
||||||
supported_ckpt_extensions = set(['.ckpt', '.pth', '.safetensors'])
|
|
||||||
supported_pt_extensions = set(['.ckpt', '.pt', '.bin', '.pth', '.safetensors'])
|
supported_pt_extensions = set(['.ckpt', '.pt', '.bin', '.pth', '.safetensors'])
|
||||||
|
|
||||||
folder_names_and_paths = {}
|
folder_names_and_paths = {}
|
||||||
|
|
||||||
base_path = os.path.dirname(os.path.realpath(__file__))
|
base_path = os.path.dirname(os.path.realpath(__file__))
|
||||||
models_dir = os.path.join(base_path, "models")
|
models_dir = os.path.join(base_path, "models")
|
||||||
folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_ckpt_extensions)
|
folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_pt_extensions)
|
||||||
folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"])
|
folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"])
|
||||||
|
|
||||||
folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
|
folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
|
||||||
folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
|
folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
|
||||||
folder_names_and_paths["clip"] = ([os.path.join(models_dir, "clip")], supported_pt_extensions)
|
folder_names_and_paths["clip"] = ([os.path.join(models_dir, "clip")], supported_pt_extensions)
|
||||||
|
folder_names_and_paths["unet"] = ([os.path.join(models_dir, "unet")], supported_pt_extensions)
|
||||||
folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
|
folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
|
||||||
folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
|
folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
|
||||||
folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
|
folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
|
||||||
@ -42,6 +42,10 @@ def set_output_directory(output_dir):
|
|||||||
global output_directory
|
global output_directory
|
||||||
output_directory = output_dir
|
output_directory = output_dir
|
||||||
|
|
||||||
|
def set_temp_directory(temp_dir):
|
||||||
|
global temp_directory
|
||||||
|
temp_directory = temp_dir
|
||||||
|
|
||||||
def get_output_directory():
|
def get_output_directory():
|
||||||
global output_directory
|
global output_directory
|
||||||
return output_directory
|
return output_directory
|
||||||
@ -110,21 +114,28 @@ def add_model_folder_path(folder_name, full_folder_path):
|
|||||||
global folder_names_and_paths
|
global folder_names_and_paths
|
||||||
if folder_name in folder_names_and_paths:
|
if folder_name in folder_names_and_paths:
|
||||||
folder_names_and_paths[folder_name][0].append(full_folder_path)
|
folder_names_and_paths[folder_name][0].append(full_folder_path)
|
||||||
|
else:
|
||||||
|
folder_names_and_paths[folder_name] = ([full_folder_path], set())
|
||||||
|
|
||||||
def get_folder_paths(folder_name):
|
def get_folder_paths(folder_name):
|
||||||
return folder_names_and_paths[folder_name][0][:]
|
return folder_names_and_paths[folder_name][0][:]
|
||||||
|
|
||||||
def recursive_search(directory):
|
def recursive_search(directory, excluded_dir_names=None):
|
||||||
if not os.path.isdir(directory):
|
if not os.path.isdir(directory):
|
||||||
return [], {}
|
return [], {}
|
||||||
|
|
||||||
|
if excluded_dir_names is None:
|
||||||
|
excluded_dir_names = []
|
||||||
|
|
||||||
result = []
|
result = []
|
||||||
dirs = {directory: os.path.getmtime(directory)}
|
dirs = {directory: os.path.getmtime(directory)}
|
||||||
for root, subdir, file in os.walk(directory, followlinks=True):
|
for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
|
||||||
for filepath in file:
|
subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
|
||||||
#we os.path,join directory with a blank string to generate a path separator at the end.
|
for file_name in filenames:
|
||||||
result.append(os.path.join(root, filepath).replace(os.path.join(directory,''),''))
|
relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
|
||||||
for d in subdir:
|
result.append(relative_path)
|
||||||
path = os.path.join(root, d)
|
for d in subdirs:
|
||||||
|
path = os.path.join(dirpath, d)
|
||||||
dirs[path] = os.path.getmtime(path)
|
dirs[path] = os.path.getmtime(path)
|
||||||
return result, dirs
|
return result, dirs
|
||||||
|
|
||||||
@ -152,7 +163,7 @@ def get_filename_list_(folder_name):
|
|||||||
folders = folder_names_and_paths[folder_name]
|
folders = folder_names_and_paths[folder_name]
|
||||||
output_folders = {}
|
output_folders = {}
|
||||||
for x in folders[0]:
|
for x in folders[0]:
|
||||||
files, folders_all = recursive_search(x)
|
files, folders_all = recursive_search(x, excluded_dir_names=[".git"])
|
||||||
output_list.update(filter_files_extensions(files, folders[1]))
|
output_list.update(filter_files_extensions(files, folders[1]))
|
||||||
output_folders = {**output_folders, **folders_all}
|
output_folders = {**output_folders, **folders_all}
|
||||||
|
|
||||||
|
|||||||
@ -1,9 +1,7 @@
|
|||||||
import torch
|
import torch
|
||||||
from PIL import Image, ImageOps
|
from PIL import Image
|
||||||
from io import BytesIO
|
|
||||||
import struct
|
import struct
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from comfy.cli_args import args, LatentPreviewMethod
|
from comfy.cli_args import args, LatentPreviewMethod
|
||||||
from comfy.taesd.taesd import TAESD
|
from comfy.taesd.taesd import TAESD
|
||||||
import folder_paths
|
import folder_paths
|
||||||
@ -16,20 +14,7 @@ class LatentPreviewer:
|
|||||||
|
|
||||||
def decode_latent_to_preview_image(self, preview_format, x0):
|
def decode_latent_to_preview_image(self, preview_format, x0):
|
||||||
preview_image = self.decode_latent_to_preview(x0)
|
preview_image = self.decode_latent_to_preview(x0)
|
||||||
preview_image = ImageOps.contain(preview_image, (MAX_PREVIEW_RESOLUTION, MAX_PREVIEW_RESOLUTION), Image.ANTIALIAS)
|
return ("JPEG", preview_image, MAX_PREVIEW_RESOLUTION)
|
||||||
|
|
||||||
preview_type = 1
|
|
||||||
if preview_format == "JPEG":
|
|
||||||
preview_type = 1
|
|
||||||
elif preview_format == "PNG":
|
|
||||||
preview_type = 2
|
|
||||||
|
|
||||||
bytesIO = BytesIO()
|
|
||||||
header = struct.pack(">I", preview_type)
|
|
||||||
bytesIO.write(header)
|
|
||||||
preview_image.save(bytesIO, format=preview_format, quality=95)
|
|
||||||
preview_bytes = bytesIO.getvalue()
|
|
||||||
return preview_bytes
|
|
||||||
|
|
||||||
class TAESDPreviewerImpl(LatentPreviewer):
|
class TAESDPreviewerImpl(LatentPreviewer):
|
||||||
def __init__(self, taesd):
|
def __init__(self, taesd):
|
||||||
|
|||||||
85
main.py
85
main.py
@ -1,37 +1,88 @@
|
|||||||
|
import os
|
||||||
|
import importlib.util
|
||||||
|
import folder_paths
|
||||||
|
import time
|
||||||
|
|
||||||
|
def execute_prestartup_script():
|
||||||
|
def execute_script(script_path):
|
||||||
|
module_name = os.path.splitext(script_path)[0]
|
||||||
|
try:
|
||||||
|
spec = importlib.util.spec_from_file_location(module_name, script_path)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Failed to execute startup-script: {script_path} / {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
node_paths = folder_paths.get_folder_paths("custom_nodes")
|
||||||
|
for custom_node_path in node_paths:
|
||||||
|
possible_modules = os.listdir(custom_node_path)
|
||||||
|
node_prestartup_times = []
|
||||||
|
|
||||||
|
for possible_module in possible_modules:
|
||||||
|
module_path = os.path.join(custom_node_path, possible_module)
|
||||||
|
if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
|
||||||
|
continue
|
||||||
|
|
||||||
|
script_path = os.path.join(module_path, "prestartup_script.py")
|
||||||
|
if os.path.exists(script_path):
|
||||||
|
time_before = time.perf_counter()
|
||||||
|
success = execute_script(script_path)
|
||||||
|
node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
|
||||||
|
if len(node_prestartup_times) > 0:
|
||||||
|
print("\nPrestartup times for custom nodes:")
|
||||||
|
for n in sorted(node_prestartup_times):
|
||||||
|
if n[2]:
|
||||||
|
import_message = ""
|
||||||
|
else:
|
||||||
|
import_message = " (PRESTARTUP FAILED)"
|
||||||
|
print("{:6.1f} seconds{}:".format(n[0], import_message), n[1])
|
||||||
|
print()
|
||||||
|
|
||||||
|
execute_prestartup_script()
|
||||||
|
|
||||||
|
|
||||||
|
# Main code
|
||||||
import asyncio
|
import asyncio
|
||||||
import itertools
|
import itertools
|
||||||
import os
|
|
||||||
import shutil
|
import shutil
|
||||||
import threading
|
import threading
|
||||||
import gc
|
import gc
|
||||||
import time
|
|
||||||
|
|
||||||
from comfy.cli_args import args
|
from comfy.cli_args import args
|
||||||
import comfy.utils
|
|
||||||
|
|
||||||
if os.name == "nt":
|
if os.name == "nt":
|
||||||
import logging
|
import logging
|
||||||
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
|
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
if args.dont_upcast_attention:
|
|
||||||
print("disabling upcasting of attention")
|
|
||||||
os.environ['ATTN_PRECISION'] = "fp16"
|
|
||||||
|
|
||||||
if args.cuda_device is not None:
|
if args.cuda_device is not None:
|
||||||
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
|
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
|
||||||
print("Set cuda device to:", args.cuda_device)
|
print("Set cuda device to:", args.cuda_device)
|
||||||
|
|
||||||
|
import cuda_malloc
|
||||||
|
|
||||||
|
import comfy.utils
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
import execution
|
import execution
|
||||||
import folder_paths
|
|
||||||
import server
|
import server
|
||||||
from server import BinaryEventTypes
|
from server import BinaryEventTypes
|
||||||
from nodes import init_custom_nodes
|
from nodes import init_custom_nodes
|
||||||
import comfy.model_management
|
import comfy.model_management
|
||||||
|
|
||||||
|
def cuda_malloc_warning():
|
||||||
|
device = comfy.model_management.get_torch_device()
|
||||||
|
device_name = comfy.model_management.get_torch_device_name(device)
|
||||||
|
cuda_malloc_warning = False
|
||||||
|
if "cudaMallocAsync" in device_name:
|
||||||
|
for b in cuda_malloc.blacklist:
|
||||||
|
if b in device_name:
|
||||||
|
cuda_malloc_warning = True
|
||||||
|
if cuda_malloc_warning:
|
||||||
|
print("\nWARNING: this card most likely does not support cuda-malloc, if you get \"CUDA error\" please run ComfyUI with: --disable-cuda-malloc\n")
|
||||||
|
|
||||||
def prompt_worker(q, server):
|
def prompt_worker(q, server):
|
||||||
e = execution.PromptExecutor(server)
|
e = execution.PromptExecutor(server)
|
||||||
while True:
|
while True:
|
||||||
@ -52,15 +103,16 @@ async def run(server, address='', port=8188, verbose=True, call_on_start=None):
|
|||||||
|
|
||||||
|
|
||||||
def hijack_progress(server):
|
def hijack_progress(server):
|
||||||
def hook(value, total, preview_image_bytes):
|
def hook(value, total, preview_image):
|
||||||
|
comfy.model_management.throw_exception_if_processing_interrupted()
|
||||||
server.send_sync("progress", {"value": value, "max": total}, server.client_id)
|
server.send_sync("progress", {"value": value, "max": total}, server.client_id)
|
||||||
if preview_image_bytes is not None:
|
if preview_image is not None:
|
||||||
server.send_sync(BinaryEventTypes.PREVIEW_IMAGE, preview_image_bytes, server.client_id)
|
server.send_sync(BinaryEventTypes.UNENCODED_PREVIEW_IMAGE, preview_image, server.client_id)
|
||||||
comfy.utils.set_progress_bar_global_hook(hook)
|
comfy.utils.set_progress_bar_global_hook(hook)
|
||||||
|
|
||||||
|
|
||||||
def cleanup_temp():
|
def cleanup_temp():
|
||||||
temp_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp")
|
temp_dir = folder_paths.get_temp_directory()
|
||||||
if os.path.exists(temp_dir):
|
if os.path.exists(temp_dir):
|
||||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
@ -87,6 +139,10 @@ def load_extra_path_config(yaml_path):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
if args.temp_directory:
|
||||||
|
temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
|
||||||
|
print(f"Setting temp directory to: {temp_dir}")
|
||||||
|
folder_paths.set_temp_directory(temp_dir)
|
||||||
cleanup_temp()
|
cleanup_temp()
|
||||||
|
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
@ -103,6 +159,9 @@ if __name__ == "__main__":
|
|||||||
load_extra_path_config(config_path)
|
load_extra_path_config(config_path)
|
||||||
|
|
||||||
init_custom_nodes()
|
init_custom_nodes()
|
||||||
|
|
||||||
|
cuda_malloc_warning()
|
||||||
|
|
||||||
server.add_routes()
|
server.add_routes()
|
||||||
hijack_progress(server)
|
hijack_progress(server)
|
||||||
|
|
||||||
@ -120,6 +179,8 @@ if __name__ == "__main__":
|
|||||||
if args.auto_launch:
|
if args.auto_launch:
|
||||||
def startup_server(address, port):
|
def startup_server(address, port):
|
||||||
import webbrowser
|
import webbrowser
|
||||||
|
if os.name == 'nt' and address == '0.0.0.0':
|
||||||
|
address = '127.0.0.1'
|
||||||
webbrowser.open(f"http://{address}:{port}")
|
webbrowser.open(f"http://{address}:{port}")
|
||||||
call_on_start = startup_server
|
call_on_start = startup_server
|
||||||
|
|
||||||
|
|||||||
0
models/unet/put_unet_files_here
Normal file
0
models/unet/put_unet_files_here
Normal file
373
nodes.py
373
nodes.py
@ -7,6 +7,7 @@ import hashlib
|
|||||||
import traceback
|
import traceback
|
||||||
import math
|
import math
|
||||||
import time
|
import time
|
||||||
|
import random
|
||||||
|
|
||||||
from PIL import Image, ImageOps
|
from PIL import Image, ImageOps
|
||||||
from PIL.PngImagePlugin import PngInfo
|
from PIL.PngImagePlugin import PngInfo
|
||||||
@ -21,10 +22,13 @@ import comfy.samplers
|
|||||||
import comfy.sample
|
import comfy.sample
|
||||||
import comfy.sd
|
import comfy.sd
|
||||||
import comfy.utils
|
import comfy.utils
|
||||||
|
import comfy.controlnet
|
||||||
|
|
||||||
import comfy.clip_vision
|
import comfy.clip_vision
|
||||||
|
|
||||||
import comfy.model_management
|
import comfy.model_management
|
||||||
|
from comfy.cli_args import args
|
||||||
|
|
||||||
import importlib
|
import importlib
|
||||||
|
|
||||||
import folder_paths
|
import folder_paths
|
||||||
@ -82,16 +86,52 @@ class ConditioningAverage :
|
|||||||
print("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
|
print("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
|
||||||
|
|
||||||
cond_from = conditioning_from[0][0]
|
cond_from = conditioning_from[0][0]
|
||||||
|
pooled_output_from = conditioning_from[0][1].get("pooled_output", None)
|
||||||
|
|
||||||
for i in range(len(conditioning_to)):
|
for i in range(len(conditioning_to)):
|
||||||
t1 = conditioning_to[i][0]
|
t1 = conditioning_to[i][0]
|
||||||
|
pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from)
|
||||||
t0 = cond_from[:,:t1.shape[1]]
|
t0 = cond_from[:,:t1.shape[1]]
|
||||||
if t0.shape[1] < t1.shape[1]:
|
if t0.shape[1] < t1.shape[1]:
|
||||||
t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1)
|
t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1)
|
||||||
|
|
||||||
tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength))
|
tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength))
|
||||||
|
t_to = conditioning_to[i][1].copy()
|
||||||
|
if pooled_output_from is not None and pooled_output_to is not None:
|
||||||
|
t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength))
|
||||||
|
elif pooled_output_from is not None:
|
||||||
|
t_to["pooled_output"] = pooled_output_from
|
||||||
|
|
||||||
|
n = [tw, t_to]
|
||||||
|
out.append(n)
|
||||||
|
return (out, )
|
||||||
|
|
||||||
|
class ConditioningConcat:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {
|
||||||
|
"conditioning_to": ("CONDITIONING",),
|
||||||
|
"conditioning_from": ("CONDITIONING",),
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("CONDITIONING",)
|
||||||
|
FUNCTION = "concat"
|
||||||
|
|
||||||
|
CATEGORY = "conditioning"
|
||||||
|
|
||||||
|
def concat(self, conditioning_to, conditioning_from):
|
||||||
|
out = []
|
||||||
|
|
||||||
|
if len(conditioning_from) > 1:
|
||||||
|
print("Warning: ConditioningConcat conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
|
||||||
|
|
||||||
|
cond_from = conditioning_from[0][0]
|
||||||
|
|
||||||
|
for i in range(len(conditioning_to)):
|
||||||
|
t1 = conditioning_to[i][0]
|
||||||
|
tw = torch.cat((t1, cond_from),1)
|
||||||
n = [tw, conditioning_to[i][1].copy()]
|
n = [tw, conditioning_to[i][1].copy()]
|
||||||
out.append(n)
|
out.append(n)
|
||||||
|
|
||||||
return (out, )
|
return (out, )
|
||||||
|
|
||||||
class ConditioningSetArea:
|
class ConditioningSetArea:
|
||||||
@ -119,6 +159,31 @@ class ConditioningSetArea:
|
|||||||
c.append(n)
|
c.append(n)
|
||||||
return (c, )
|
return (c, )
|
||||||
|
|
||||||
|
class ConditioningSetAreaPercentage:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {"conditioning": ("CONDITIONING", ),
|
||||||
|
"width": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
|
||||||
|
"height": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
|
||||||
|
"x": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
|
||||||
|
"y": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
|
||||||
|
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("CONDITIONING",)
|
||||||
|
FUNCTION = "append"
|
||||||
|
|
||||||
|
CATEGORY = "conditioning"
|
||||||
|
|
||||||
|
def append(self, conditioning, width, height, x, y, strength):
|
||||||
|
c = []
|
||||||
|
for t in conditioning:
|
||||||
|
n = [t[0], t[1].copy()]
|
||||||
|
n[1]['area'] = ("percentage", height, width, y, x)
|
||||||
|
n[1]['strength'] = strength
|
||||||
|
n[1]['set_area_to_bounds'] = False
|
||||||
|
c.append(n)
|
||||||
|
return (c, )
|
||||||
|
|
||||||
class ConditioningSetMask:
|
class ConditioningSetMask:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
@ -148,6 +213,47 @@ class ConditioningSetMask:
|
|||||||
c.append(n)
|
c.append(n)
|
||||||
return (c, )
|
return (c, )
|
||||||
|
|
||||||
|
class ConditioningZeroOut:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {"conditioning": ("CONDITIONING", )}}
|
||||||
|
RETURN_TYPES = ("CONDITIONING",)
|
||||||
|
FUNCTION = "zero_out"
|
||||||
|
|
||||||
|
CATEGORY = "advanced/conditioning"
|
||||||
|
|
||||||
|
def zero_out(self, conditioning):
|
||||||
|
c = []
|
||||||
|
for t in conditioning:
|
||||||
|
d = t[1].copy()
|
||||||
|
if "pooled_output" in d:
|
||||||
|
d["pooled_output"] = torch.zeros_like(d["pooled_output"])
|
||||||
|
n = [torch.zeros_like(t[0]), d]
|
||||||
|
c.append(n)
|
||||||
|
return (c, )
|
||||||
|
|
||||||
|
class ConditioningSetTimestepRange:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {"conditioning": ("CONDITIONING", ),
|
||||||
|
"start": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||||
|
"end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("CONDITIONING",)
|
||||||
|
FUNCTION = "set_range"
|
||||||
|
|
||||||
|
CATEGORY = "advanced/conditioning"
|
||||||
|
|
||||||
|
def set_range(self, conditioning, start, end):
|
||||||
|
c = []
|
||||||
|
for t in conditioning:
|
||||||
|
d = t[1].copy()
|
||||||
|
d['start_percent'] = 1.0 - start
|
||||||
|
d['end_percent'] = 1.0 - end
|
||||||
|
n = [t[0], d]
|
||||||
|
c.append(n)
|
||||||
|
return (c, )
|
||||||
|
|
||||||
class VAEDecode:
|
class VAEDecode:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
@ -163,14 +269,16 @@ class VAEDecode:
|
|||||||
class VAEDecodeTiled:
|
class VAEDecodeTiled:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
return {"required": { "samples": ("LATENT", ), "vae": ("VAE", )}}
|
return {"required": {"samples": ("LATENT", ), "vae": ("VAE", ),
|
||||||
|
"tile_size": ("INT", {"default": 512, "min": 320, "max": 4096, "step": 64})
|
||||||
|
}}
|
||||||
RETURN_TYPES = ("IMAGE",)
|
RETURN_TYPES = ("IMAGE",)
|
||||||
FUNCTION = "decode"
|
FUNCTION = "decode"
|
||||||
|
|
||||||
CATEGORY = "_for_testing"
|
CATEGORY = "_for_testing"
|
||||||
|
|
||||||
def decode(self, vae, samples):
|
def decode(self, vae, samples, tile_size):
|
||||||
return (vae.decode_tiled(samples["samples"]), )
|
return (vae.decode_tiled(samples["samples"], tile_x=tile_size // 8, tile_y=tile_size // 8, ), )
|
||||||
|
|
||||||
class VAEEncode:
|
class VAEEncode:
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -199,15 +307,17 @@ class VAEEncode:
|
|||||||
class VAEEncodeTiled:
|
class VAEEncodeTiled:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", )}}
|
return {"required": {"pixels": ("IMAGE", ), "vae": ("VAE", ),
|
||||||
|
"tile_size": ("INT", {"default": 512, "min": 320, "max": 4096, "step": 64})
|
||||||
|
}}
|
||||||
RETURN_TYPES = ("LATENT",)
|
RETURN_TYPES = ("LATENT",)
|
||||||
FUNCTION = "encode"
|
FUNCTION = "encode"
|
||||||
|
|
||||||
CATEGORY = "_for_testing"
|
CATEGORY = "_for_testing"
|
||||||
|
|
||||||
def encode(self, vae, pixels):
|
def encode(self, vae, pixels, tile_size):
|
||||||
pixels = VAEEncode.vae_encode_crop_pixels(pixels)
|
pixels = VAEEncode.vae_encode_crop_pixels(pixels)
|
||||||
t = vae.encode_tiled(pixels[:,:,:,:3])
|
t = vae.encode_tiled(pixels[:,:,:,:3], tile_x=tile_size, tile_y=tile_size, )
|
||||||
return ({"samples":t}, )
|
return ({"samples":t}, )
|
||||||
|
|
||||||
class VAEEncodeForInpaint:
|
class VAEEncodeForInpaint:
|
||||||
@ -274,12 +384,22 @@ class SaveLatent:
|
|||||||
if prompt is not None:
|
if prompt is not None:
|
||||||
prompt_info = json.dumps(prompt)
|
prompt_info = json.dumps(prompt)
|
||||||
|
|
||||||
metadata = {"prompt": prompt_info}
|
metadata = None
|
||||||
if extra_pnginfo is not None:
|
if not args.disable_metadata:
|
||||||
for x in extra_pnginfo:
|
metadata = {"prompt": prompt_info}
|
||||||
metadata[x] = json.dumps(extra_pnginfo[x])
|
if extra_pnginfo is not None:
|
||||||
|
for x in extra_pnginfo:
|
||||||
|
metadata[x] = json.dumps(extra_pnginfo[x])
|
||||||
|
|
||||||
file = f"{filename}_{counter:05}_.latent"
|
file = f"{filename}_{counter:05}_.latent"
|
||||||
|
|
||||||
|
results = list()
|
||||||
|
results.append({
|
||||||
|
"filename": file,
|
||||||
|
"subfolder": subfolder,
|
||||||
|
"type": "output"
|
||||||
|
})
|
||||||
|
|
||||||
file = os.path.join(full_output_folder, file)
|
file = os.path.join(full_output_folder, file)
|
||||||
|
|
||||||
output = {}
|
output = {}
|
||||||
@ -287,7 +407,7 @@ class SaveLatent:
|
|||||||
output["latent_format_version_0"] = torch.tensor([])
|
output["latent_format_version_0"] = torch.tensor([])
|
||||||
|
|
||||||
comfy.utils.save_torch_file(output, file, metadata=metadata)
|
comfy.utils.save_torch_file(output, file, metadata=metadata)
|
||||||
return {}
|
return { "ui": { "latents": results } }
|
||||||
|
|
||||||
|
|
||||||
class LoadLatent:
|
class LoadLatent:
|
||||||
@ -354,7 +474,7 @@ class CheckpointLoaderSimple:
|
|||||||
def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
|
def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
|
||||||
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
|
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
|
||||||
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
||||||
return out
|
return out[:3]
|
||||||
|
|
||||||
class DiffusersLoader:
|
class DiffusersLoader:
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -370,7 +490,7 @@ class DiffusersLoader:
|
|||||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
|
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
|
||||||
FUNCTION = "load_checkpoint"
|
FUNCTION = "load_checkpoint"
|
||||||
|
|
||||||
CATEGORY = "advanced/loaders"
|
CATEGORY = "advanced/loaders/deprecated"
|
||||||
|
|
||||||
def load_checkpoint(self, model_path, output_vae=True, output_clip=True):
|
def load_checkpoint(self, model_path, output_vae=True, output_clip=True):
|
||||||
for search_path in folder_paths.get_folder_paths("diffusers"):
|
for search_path in folder_paths.get_folder_paths("diffusers"):
|
||||||
@ -380,7 +500,7 @@ class DiffusersLoader:
|
|||||||
model_path = path
|
model_path = path
|
||||||
break
|
break
|
||||||
|
|
||||||
return comfy.diffusers_load.load_diffusers(model_path, fp16=comfy.model_management.should_use_fp16(), output_vae=output_vae, output_clip=output_clip, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
return comfy.diffusers_load.load_diffusers(model_path, output_vae=output_vae, output_clip=output_clip, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
||||||
|
|
||||||
|
|
||||||
class unCLIPCheckpointLoader:
|
class unCLIPCheckpointLoader:
|
||||||
@ -415,6 +535,9 @@ class CLIPSetLastLayer:
|
|||||||
return (clip,)
|
return (clip,)
|
||||||
|
|
||||||
class LoraLoader:
|
class LoraLoader:
|
||||||
|
def __init__(self):
|
||||||
|
self.loaded_lora = None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
return {"required": { "model": ("MODEL",),
|
return {"required": { "model": ("MODEL",),
|
||||||
@ -433,7 +556,20 @@ class LoraLoader:
|
|||||||
return (model, clip)
|
return (model, clip)
|
||||||
|
|
||||||
lora_path = folder_paths.get_full_path("loras", lora_name)
|
lora_path = folder_paths.get_full_path("loras", lora_name)
|
||||||
model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora_path, strength_model, strength_clip)
|
lora = None
|
||||||
|
if self.loaded_lora is not None:
|
||||||
|
if self.loaded_lora[0] == lora_path:
|
||||||
|
lora = self.loaded_lora[1]
|
||||||
|
else:
|
||||||
|
temp = self.loaded_lora
|
||||||
|
self.loaded_lora = None
|
||||||
|
del temp
|
||||||
|
|
||||||
|
if lora is None:
|
||||||
|
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
|
||||||
|
self.loaded_lora = (lora_path, lora)
|
||||||
|
|
||||||
|
model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip)
|
||||||
return (model_lora, clip_lora)
|
return (model_lora, clip_lora)
|
||||||
|
|
||||||
class VAELoader:
|
class VAELoader:
|
||||||
@ -463,7 +599,7 @@ class ControlNetLoader:
|
|||||||
|
|
||||||
def load_controlnet(self, control_net_name):
|
def load_controlnet(self, control_net_name):
|
||||||
controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
|
controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
|
||||||
controlnet = comfy.sd.load_controlnet(controlnet_path)
|
controlnet = comfy.controlnet.load_controlnet(controlnet_path)
|
||||||
return (controlnet,)
|
return (controlnet,)
|
||||||
|
|
||||||
class DiffControlNetLoader:
|
class DiffControlNetLoader:
|
||||||
@ -479,7 +615,7 @@ class DiffControlNetLoader:
|
|||||||
|
|
||||||
def load_controlnet(self, model, control_net_name):
|
def load_controlnet(self, model, control_net_name):
|
||||||
controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
|
controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
|
||||||
controlnet = comfy.sd.load_controlnet(controlnet_path, model)
|
controlnet = comfy.controlnet.load_controlnet(controlnet_path, model)
|
||||||
return (controlnet,)
|
return (controlnet,)
|
||||||
|
|
||||||
|
|
||||||
@ -508,9 +644,73 @@ class ControlNetApply:
|
|||||||
if 'control' in t[1]:
|
if 'control' in t[1]:
|
||||||
c_net.set_previous_controlnet(t[1]['control'])
|
c_net.set_previous_controlnet(t[1]['control'])
|
||||||
n[1]['control'] = c_net
|
n[1]['control'] = c_net
|
||||||
|
n[1]['control_apply_to_uncond'] = True
|
||||||
c.append(n)
|
c.append(n)
|
||||||
return (c, )
|
return (c, )
|
||||||
|
|
||||||
|
|
||||||
|
class ControlNetApplyAdvanced:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {"positive": ("CONDITIONING", ),
|
||||||
|
"negative": ("CONDITIONING", ),
|
||||||
|
"control_net": ("CONTROL_NET", ),
|
||||||
|
"image": ("IMAGE", ),
|
||||||
|
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
||||||
|
"start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||||
|
"end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
|
||||||
|
}}
|
||||||
|
|
||||||
|
RETURN_TYPES = ("CONDITIONING","CONDITIONING")
|
||||||
|
RETURN_NAMES = ("positive", "negative")
|
||||||
|
FUNCTION = "apply_controlnet"
|
||||||
|
|
||||||
|
CATEGORY = "conditioning"
|
||||||
|
|
||||||
|
def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent):
|
||||||
|
if strength == 0:
|
||||||
|
return (positive, negative)
|
||||||
|
|
||||||
|
control_hint = image.movedim(-1,1)
|
||||||
|
cnets = {}
|
||||||
|
|
||||||
|
out = []
|
||||||
|
for conditioning in [positive, negative]:
|
||||||
|
c = []
|
||||||
|
for t in conditioning:
|
||||||
|
d = t[1].copy()
|
||||||
|
|
||||||
|
prev_cnet = d.get('control', None)
|
||||||
|
if prev_cnet in cnets:
|
||||||
|
c_net = cnets[prev_cnet]
|
||||||
|
else:
|
||||||
|
c_net = control_net.copy().set_cond_hint(control_hint, strength, (1.0 - start_percent, 1.0 - end_percent))
|
||||||
|
c_net.set_previous_controlnet(prev_cnet)
|
||||||
|
cnets[prev_cnet] = c_net
|
||||||
|
|
||||||
|
d['control'] = c_net
|
||||||
|
d['control_apply_to_uncond'] = False
|
||||||
|
n = [t[0], d]
|
||||||
|
c.append(n)
|
||||||
|
out.append(c)
|
||||||
|
return (out[0], out[1])
|
||||||
|
|
||||||
|
|
||||||
|
class UNETLoader:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": { "unet_name": (folder_paths.get_filename_list("unet"), ),
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("MODEL",)
|
||||||
|
FUNCTION = "load_unet"
|
||||||
|
|
||||||
|
CATEGORY = "advanced/loaders"
|
||||||
|
|
||||||
|
def load_unet(self, unet_name):
|
||||||
|
unet_path = folder_paths.get_full_path("unet", unet_name)
|
||||||
|
model = comfy.sd.load_unet(unet_path)
|
||||||
|
return (model,)
|
||||||
|
|
||||||
class CLIPLoader:
|
class CLIPLoader:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
@ -601,7 +801,7 @@ class StyleModelApply:
|
|||||||
CATEGORY = "conditioning/style_model"
|
CATEGORY = "conditioning/style_model"
|
||||||
|
|
||||||
def apply_stylemodel(self, clip_vision_output, style_model, conditioning):
|
def apply_stylemodel(self, clip_vision_output, style_model, conditioning):
|
||||||
cond = style_model.get_cond(clip_vision_output)
|
cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
|
||||||
c = []
|
c = []
|
||||||
for t in conditioning:
|
for t in conditioning:
|
||||||
n = [torch.cat((t[0], cond), dim=1), t[1].copy()]
|
n = [torch.cat((t[0], cond), dim=1), t[1].copy()]
|
||||||
@ -885,6 +1085,47 @@ class LatentComposite:
|
|||||||
samples_out["samples"] = s
|
samples_out["samples"] = s
|
||||||
return (samples_out,)
|
return (samples_out,)
|
||||||
|
|
||||||
|
class LatentBlend:
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": {
|
||||||
|
"samples1": ("LATENT",),
|
||||||
|
"samples2": ("LATENT",),
|
||||||
|
"blend_factor": ("FLOAT", {
|
||||||
|
"default": 0.5,
|
||||||
|
"min": 0,
|
||||||
|
"max": 1,
|
||||||
|
"step": 0.01
|
||||||
|
}),
|
||||||
|
}}
|
||||||
|
|
||||||
|
RETURN_TYPES = ("LATENT",)
|
||||||
|
FUNCTION = "blend"
|
||||||
|
|
||||||
|
CATEGORY = "_for_testing"
|
||||||
|
|
||||||
|
def blend(self, samples1, samples2, blend_factor:float, blend_mode: str="normal"):
|
||||||
|
|
||||||
|
samples_out = samples1.copy()
|
||||||
|
samples1 = samples1["samples"]
|
||||||
|
samples2 = samples2["samples"]
|
||||||
|
|
||||||
|
if samples1.shape != samples2.shape:
|
||||||
|
samples2.permute(0, 3, 1, 2)
|
||||||
|
samples2 = comfy.utils.common_upscale(samples2, samples1.shape[3], samples1.shape[2], 'bicubic', crop='center')
|
||||||
|
samples2.permute(0, 2, 3, 1)
|
||||||
|
|
||||||
|
samples_blended = self.blend_mode(samples1, samples2, blend_mode)
|
||||||
|
samples_blended = samples1 * blend_factor + samples_blended * (1 - blend_factor)
|
||||||
|
samples_out["samples"] = samples_blended
|
||||||
|
return (samples_out,)
|
||||||
|
|
||||||
|
def blend_mode(self, img1, img2, mode):
|
||||||
|
if mode == "normal":
|
||||||
|
return img2
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported blend mode: {mode}")
|
||||||
|
|
||||||
class LatentCrop:
|
class LatentCrop:
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
@ -1032,6 +1273,7 @@ class SaveImage:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.output_dir = folder_paths.get_output_directory()
|
self.output_dir = folder_paths.get_output_directory()
|
||||||
self.type = "output"
|
self.type = "output"
|
||||||
|
self.prefix_append = ""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
@ -1049,17 +1291,20 @@ class SaveImage:
|
|||||||
CATEGORY = "image"
|
CATEGORY = "image"
|
||||||
|
|
||||||
def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
|
def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
|
||||||
|
filename_prefix += self.prefix_append
|
||||||
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
|
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
|
||||||
results = list()
|
results = list()
|
||||||
for image in images:
|
for image in images:
|
||||||
i = 255. * image.cpu().numpy()
|
i = 255. * image.cpu().numpy()
|
||||||
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
|
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
|
||||||
metadata = PngInfo()
|
metadata = None
|
||||||
if prompt is not None:
|
if not args.disable_metadata:
|
||||||
metadata.add_text("prompt", json.dumps(prompt))
|
metadata = PngInfo()
|
||||||
if extra_pnginfo is not None:
|
if prompt is not None:
|
||||||
for x in extra_pnginfo:
|
metadata.add_text("prompt", json.dumps(prompt))
|
||||||
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
|
if extra_pnginfo is not None:
|
||||||
|
for x in extra_pnginfo:
|
||||||
|
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
|
||||||
|
|
||||||
file = f"{filename}_{counter:05}_.png"
|
file = f"{filename}_{counter:05}_.png"
|
||||||
img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=4)
|
img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=4)
|
||||||
@ -1076,6 +1321,7 @@ class PreviewImage(SaveImage):
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.output_dir = folder_paths.get_temp_directory()
|
self.output_dir = folder_paths.get_temp_directory()
|
||||||
self.type = "temp"
|
self.type = "temp"
|
||||||
|
self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def INPUT_TYPES(s):
|
def INPUT_TYPES(s):
|
||||||
@ -1090,7 +1336,7 @@ class LoadImage:
|
|||||||
input_dir = folder_paths.get_input_directory()
|
input_dir = folder_paths.get_input_directory()
|
||||||
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
|
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
|
||||||
return {"required":
|
return {"required":
|
||||||
{"image": (sorted(files), )},
|
{"image": (sorted(files), {"image_upload": True})},
|
||||||
}
|
}
|
||||||
|
|
||||||
CATEGORY = "image"
|
CATEGORY = "image"
|
||||||
@ -1133,7 +1379,7 @@ class LoadImageMask:
|
|||||||
input_dir = folder_paths.get_input_directory()
|
input_dir = folder_paths.get_input_directory()
|
||||||
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
|
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
|
||||||
return {"required":
|
return {"required":
|
||||||
{"image": (sorted(files), ),
|
{"image": (sorted(files), {"image_upload": True}),
|
||||||
"channel": (s._color_channels, ), }
|
"channel": (s._color_channels, ), }
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1232,6 +1478,44 @@ class ImageInvert:
|
|||||||
s = 1.0 - image
|
s = 1.0 - image
|
||||||
return (s,)
|
return (s,)
|
||||||
|
|
||||||
|
class ImageBatch:
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": { "image1": ("IMAGE",), "image2": ("IMAGE",)}}
|
||||||
|
|
||||||
|
RETURN_TYPES = ("IMAGE",)
|
||||||
|
FUNCTION = "batch"
|
||||||
|
|
||||||
|
CATEGORY = "image"
|
||||||
|
|
||||||
|
def batch(self, image1, image2):
|
||||||
|
if image1.shape[1:] != image2.shape[1:]:
|
||||||
|
image2 = comfy.utils.common_upscale(image2.movedim(-1,1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1,-1)
|
||||||
|
s = torch.cat((image1, image2), dim=0)
|
||||||
|
return (s,)
|
||||||
|
|
||||||
|
class EmptyImage:
|
||||||
|
def __init__(self, device="cpu"):
|
||||||
|
self.device = device
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def INPUT_TYPES(s):
|
||||||
|
return {"required": { "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
|
||||||
|
"height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
|
||||||
|
"batch_size": ("INT", {"default": 1, "min": 1, "max": 64}),
|
||||||
|
"color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}),
|
||||||
|
}}
|
||||||
|
RETURN_TYPES = ("IMAGE",)
|
||||||
|
FUNCTION = "generate"
|
||||||
|
|
||||||
|
CATEGORY = "image"
|
||||||
|
|
||||||
|
def generate(self, width, height, batch_size=1, color=0):
|
||||||
|
r = torch.full([batch_size, height, width, 1], ((color >> 16) & 0xFF) / 0xFF)
|
||||||
|
g = torch.full([batch_size, height, width, 1], ((color >> 8) & 0xFF) / 0xFF)
|
||||||
|
b = torch.full([batch_size, height, width, 1], ((color) & 0xFF) / 0xFF)
|
||||||
|
return (torch.cat((r, g, b), dim=-1), )
|
||||||
|
|
||||||
class ImagePadForOutpaint:
|
class ImagePadForOutpaint:
|
||||||
|
|
||||||
@ -1317,24 +1601,31 @@ NODE_CLASS_MAPPINGS = {
|
|||||||
"ImageScale": ImageScale,
|
"ImageScale": ImageScale,
|
||||||
"ImageScaleBy": ImageScaleBy,
|
"ImageScaleBy": ImageScaleBy,
|
||||||
"ImageInvert": ImageInvert,
|
"ImageInvert": ImageInvert,
|
||||||
|
"ImageBatch": ImageBatch,
|
||||||
"ImagePadForOutpaint": ImagePadForOutpaint,
|
"ImagePadForOutpaint": ImagePadForOutpaint,
|
||||||
|
"EmptyImage": EmptyImage,
|
||||||
"ConditioningAverage ": ConditioningAverage ,
|
"ConditioningAverage ": ConditioningAverage ,
|
||||||
"ConditioningCombine": ConditioningCombine,
|
"ConditioningCombine": ConditioningCombine,
|
||||||
|
"ConditioningConcat": ConditioningConcat,
|
||||||
"ConditioningSetArea": ConditioningSetArea,
|
"ConditioningSetArea": ConditioningSetArea,
|
||||||
|
"ConditioningSetAreaPercentage": ConditioningSetAreaPercentage,
|
||||||
"ConditioningSetMask": ConditioningSetMask,
|
"ConditioningSetMask": ConditioningSetMask,
|
||||||
"KSamplerAdvanced": KSamplerAdvanced,
|
"KSamplerAdvanced": KSamplerAdvanced,
|
||||||
"SetLatentNoiseMask": SetLatentNoiseMask,
|
"SetLatentNoiseMask": SetLatentNoiseMask,
|
||||||
"LatentComposite": LatentComposite,
|
"LatentComposite": LatentComposite,
|
||||||
|
"LatentBlend": LatentBlend,
|
||||||
"LatentRotate": LatentRotate,
|
"LatentRotate": LatentRotate,
|
||||||
"LatentFlip": LatentFlip,
|
"LatentFlip": LatentFlip,
|
||||||
"LatentCrop": LatentCrop,
|
"LatentCrop": LatentCrop,
|
||||||
"LoraLoader": LoraLoader,
|
"LoraLoader": LoraLoader,
|
||||||
"CLIPLoader": CLIPLoader,
|
"CLIPLoader": CLIPLoader,
|
||||||
|
"UNETLoader": UNETLoader,
|
||||||
"DualCLIPLoader": DualCLIPLoader,
|
"DualCLIPLoader": DualCLIPLoader,
|
||||||
"CLIPVisionEncode": CLIPVisionEncode,
|
"CLIPVisionEncode": CLIPVisionEncode,
|
||||||
"StyleModelApply": StyleModelApply,
|
"StyleModelApply": StyleModelApply,
|
||||||
"unCLIPConditioning": unCLIPConditioning,
|
"unCLIPConditioning": unCLIPConditioning,
|
||||||
"ControlNetApply": ControlNetApply,
|
"ControlNetApply": ControlNetApply,
|
||||||
|
"ControlNetApplyAdvanced": ControlNetApplyAdvanced,
|
||||||
"ControlNetLoader": ControlNetLoader,
|
"ControlNetLoader": ControlNetLoader,
|
||||||
"DiffControlNetLoader": DiffControlNetLoader,
|
"DiffControlNetLoader": DiffControlNetLoader,
|
||||||
"StyleModelLoader": StyleModelLoader,
|
"StyleModelLoader": StyleModelLoader,
|
||||||
@ -1350,6 +1641,9 @@ NODE_CLASS_MAPPINGS = {
|
|||||||
|
|
||||||
"LoadLatent": LoadLatent,
|
"LoadLatent": LoadLatent,
|
||||||
"SaveLatent": SaveLatent,
|
"SaveLatent": SaveLatent,
|
||||||
|
|
||||||
|
"ConditioningZeroOut": ConditioningZeroOut,
|
||||||
|
"ConditioningSetTimestepRange": ConditioningSetTimestepRange,
|
||||||
}
|
}
|
||||||
|
|
||||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||||
@ -1374,9 +1668,12 @@ NODE_DISPLAY_NAME_MAPPINGS = {
|
|||||||
"CLIPSetLastLayer": "CLIP Set Last Layer",
|
"CLIPSetLastLayer": "CLIP Set Last Layer",
|
||||||
"ConditioningCombine": "Conditioning (Combine)",
|
"ConditioningCombine": "Conditioning (Combine)",
|
||||||
"ConditioningAverage ": "Conditioning (Average)",
|
"ConditioningAverage ": "Conditioning (Average)",
|
||||||
|
"ConditioningConcat": "Conditioning (Concat)",
|
||||||
"ConditioningSetArea": "Conditioning (Set Area)",
|
"ConditioningSetArea": "Conditioning (Set Area)",
|
||||||
|
"ConditioningSetAreaPercentage": "Conditioning (Set Area with Percentage)",
|
||||||
"ConditioningSetMask": "Conditioning (Set Mask)",
|
"ConditioningSetMask": "Conditioning (Set Mask)",
|
||||||
"ControlNetApply": "Apply ControlNet",
|
"ControlNetApply": "Apply ControlNet",
|
||||||
|
"ControlNetApplyAdvanced": "Apply ControlNet (Advanced)",
|
||||||
# Latent
|
# Latent
|
||||||
"VAEEncodeForInpaint": "VAE Encode (for Inpainting)",
|
"VAEEncodeForInpaint": "VAE Encode (for Inpainting)",
|
||||||
"SetLatentNoiseMask": "Set Latent Noise Mask",
|
"SetLatentNoiseMask": "Set Latent Noise Mask",
|
||||||
@ -1389,6 +1686,7 @@ NODE_DISPLAY_NAME_MAPPINGS = {
|
|||||||
"LatentUpscale": "Upscale Latent",
|
"LatentUpscale": "Upscale Latent",
|
||||||
"LatentUpscaleBy": "Upscale Latent By",
|
"LatentUpscaleBy": "Upscale Latent By",
|
||||||
"LatentComposite": "Latent Composite",
|
"LatentComposite": "Latent Composite",
|
||||||
|
"LatentBlend": "Latent Blend",
|
||||||
"LatentFromBatch" : "Latent From Batch",
|
"LatentFromBatch" : "Latent From Batch",
|
||||||
"RepeatLatentBatch": "Repeat Latent Batch",
|
"RepeatLatentBatch": "Repeat Latent Batch",
|
||||||
# Image
|
# Image
|
||||||
@ -1401,12 +1699,15 @@ NODE_DISPLAY_NAME_MAPPINGS = {
|
|||||||
"ImageUpscaleWithModel": "Upscale Image (using Model)",
|
"ImageUpscaleWithModel": "Upscale Image (using Model)",
|
||||||
"ImageInvert": "Invert Image",
|
"ImageInvert": "Invert Image",
|
||||||
"ImagePadForOutpaint": "Pad Image for Outpainting",
|
"ImagePadForOutpaint": "Pad Image for Outpainting",
|
||||||
|
"ImageBatch": "Batch Images",
|
||||||
# _for_testing
|
# _for_testing
|
||||||
"VAEDecodeTiled": "VAE Decode (Tiled)",
|
"VAEDecodeTiled": "VAE Decode (Tiled)",
|
||||||
"VAEEncodeTiled": "VAE Encode (Tiled)",
|
"VAEEncodeTiled": "VAE Encode (Tiled)",
|
||||||
}
|
}
|
||||||
|
|
||||||
def load_custom_node(module_path):
|
EXTENSION_WEB_DIRS = {}
|
||||||
|
|
||||||
|
def load_custom_node(module_path, ignore=set()):
|
||||||
module_name = os.path.basename(module_path)
|
module_name = os.path.basename(module_path)
|
||||||
if os.path.isfile(module_path):
|
if os.path.isfile(module_path):
|
||||||
sp = os.path.splitext(module_path)
|
sp = os.path.splitext(module_path)
|
||||||
@ -1414,13 +1715,24 @@ def load_custom_node(module_path):
|
|||||||
try:
|
try:
|
||||||
if os.path.isfile(module_path):
|
if os.path.isfile(module_path):
|
||||||
module_spec = importlib.util.spec_from_file_location(module_name, module_path)
|
module_spec = importlib.util.spec_from_file_location(module_name, module_path)
|
||||||
|
module_dir = os.path.split(module_path)[0]
|
||||||
else:
|
else:
|
||||||
module_spec = importlib.util.spec_from_file_location(module_name, os.path.join(module_path, "__init__.py"))
|
module_spec = importlib.util.spec_from_file_location(module_name, os.path.join(module_path, "__init__.py"))
|
||||||
|
module_dir = module_path
|
||||||
|
|
||||||
module = importlib.util.module_from_spec(module_spec)
|
module = importlib.util.module_from_spec(module_spec)
|
||||||
sys.modules[module_name] = module
|
sys.modules[module_name] = module
|
||||||
module_spec.loader.exec_module(module)
|
module_spec.loader.exec_module(module)
|
||||||
|
|
||||||
|
if hasattr(module, "WEB_DIRECTORY") and getattr(module, "WEB_DIRECTORY") is not None:
|
||||||
|
web_dir = os.path.abspath(os.path.join(module_dir, getattr(module, "WEB_DIRECTORY")))
|
||||||
|
if os.path.isdir(web_dir):
|
||||||
|
EXTENSION_WEB_DIRS[module_name] = web_dir
|
||||||
|
|
||||||
if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None:
|
if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None:
|
||||||
NODE_CLASS_MAPPINGS.update(module.NODE_CLASS_MAPPINGS)
|
for name in module.NODE_CLASS_MAPPINGS:
|
||||||
|
if name not in ignore:
|
||||||
|
NODE_CLASS_MAPPINGS[name] = module.NODE_CLASS_MAPPINGS[name]
|
||||||
if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None:
|
if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None:
|
||||||
NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
|
NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
|
||||||
return True
|
return True
|
||||||
@ -1433,6 +1745,7 @@ def load_custom_node(module_path):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
def load_custom_nodes():
|
def load_custom_nodes():
|
||||||
|
base_node_names = set(NODE_CLASS_MAPPINGS.keys())
|
||||||
node_paths = folder_paths.get_folder_paths("custom_nodes")
|
node_paths = folder_paths.get_folder_paths("custom_nodes")
|
||||||
node_import_times = []
|
node_import_times = []
|
||||||
for custom_node_path in node_paths:
|
for custom_node_path in node_paths:
|
||||||
@ -1445,7 +1758,7 @@ def load_custom_nodes():
|
|||||||
if os.path.isfile(module_path) and os.path.splitext(module_path)[1] != ".py": continue
|
if os.path.isfile(module_path) and os.path.splitext(module_path)[1] != ".py": continue
|
||||||
if module_path.endswith(".disabled"): continue
|
if module_path.endswith(".disabled"): continue
|
||||||
time_before = time.perf_counter()
|
time_before = time.perf_counter()
|
||||||
success = load_custom_node(module_path)
|
success = load_custom_node(module_path, base_node_names)
|
||||||
node_import_times.append((time.perf_counter() - time_before, module_path, success))
|
node_import_times.append((time.perf_counter() - time_before, module_path, success))
|
||||||
|
|
||||||
if len(node_import_times) > 0:
|
if len(node_import_times) > 0:
|
||||||
@ -1466,4 +1779,6 @@ def init_custom_nodes():
|
|||||||
load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_rebatch.py"))
|
load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_rebatch.py"))
|
||||||
load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_model_merging.py"))
|
load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_model_merging.py"))
|
||||||
load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_tomesd.py"))
|
load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_tomesd.py"))
|
||||||
|
load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_clip_sdxl.py"))
|
||||||
|
load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_canny.py"))
|
||||||
load_custom_nodes()
|
load_custom_nodes()
|
||||||
|
|||||||
@ -69,6 +69,15 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# Checkpoints\n",
|
"# Checkpoints\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"### SDXL\n",
|
||||||
|
"### I recommend these workflow examples: https://comfyanonymous.github.io/ComfyUI_examples/sdxl/\n",
|
||||||
|
"\n",
|
||||||
|
"#!wget -c https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors -P ./models/checkpoints/\n",
|
||||||
|
"#!wget -c https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0/resolve/main/sd_xl_refiner_1.0.safetensors -P ./models/checkpoints/\n",
|
||||||
|
"\n",
|
||||||
|
"# SDXL ReVision\n",
|
||||||
|
"#!wget -c https://huggingface.co/comfyanonymous/clip_vision_g/resolve/main/clip_vision_g.safetensors -P ./models/clip_vision/\n",
|
||||||
|
"\n",
|
||||||
"# SD1.5\n",
|
"# SD1.5\n",
|
||||||
"!wget -c https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt -P ./models/checkpoints/\n",
|
"!wget -c https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt -P ./models/checkpoints/\n",
|
||||||
"\n",
|
"\n",
|
||||||
@ -83,7 +92,7 @@
|
|||||||
"#!wget -c https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/anything-v3-fp16-pruned.safetensors -P ./models/checkpoints/\n",
|
"#!wget -c https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/anything-v3-fp16-pruned.safetensors -P ./models/checkpoints/\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Waifu Diffusion 1.5 (anime style SD2.x 768-v)\n",
|
"# Waifu Diffusion 1.5 (anime style SD2.x 768-v)\n",
|
||||||
"#!wget -c https://huggingface.co/waifu-diffusion/wd-1-5-beta2/resolve/main/checkpoints/wd-1-5-beta2-fp16.safetensors -P ./models/checkpoints/\n",
|
"#!wget -c https://huggingface.co/waifu-diffusion/wd-1-5-beta3/resolve/main/wd-illusion-fp16.safetensors -P ./models/checkpoints/\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# unCLIP models\n",
|
"# unCLIP models\n",
|
||||||
@ -100,6 +109,7 @@
|
|||||||
"# Loras\n",
|
"# Loras\n",
|
||||||
"#!wget -c https://civitai.com/api/download/models/10350 -O ./models/loras/theovercomer8sContrastFix_sd21768.safetensors #theovercomer8sContrastFix SD2.x 768-v\n",
|
"#!wget -c https://civitai.com/api/download/models/10350 -O ./models/loras/theovercomer8sContrastFix_sd21768.safetensors #theovercomer8sContrastFix SD2.x 768-v\n",
|
||||||
"#!wget -c https://civitai.com/api/download/models/10638 -O ./models/loras/theovercomer8sContrastFix_sd15.safetensors #theovercomer8sContrastFix SD1.x\n",
|
"#!wget -c https://civitai.com/api/download/models/10638 -O ./models/loras/theovercomer8sContrastFix_sd15.safetensors #theovercomer8sContrastFix SD1.x\n",
|
||||||
|
"#!wget -c https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_offset_example-lora_1.0.safetensors -P ./models/loras/ #SDXL offset noise lora\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# T2I-Adapter\n",
|
"# T2I-Adapter\n",
|
||||||
@ -134,6 +144,11 @@
|
|||||||
"#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15s2_lineart_anime_fp16.safetensors -P ./models/controlnet/\n",
|
"#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15s2_lineart_anime_fp16.safetensors -P ./models/controlnet/\n",
|
||||||
"#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11u_sd15_tile_fp16.safetensors -P ./models/controlnet/\n",
|
"#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11u_sd15_tile_fp16.safetensors -P ./models/controlnet/\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"# ControlNet SDXL\n",
|
||||||
|
"#!wget -c https://huggingface.co/stabilityai/control-lora/resolve/main/control-LoRAs-rank256/control-lora-canny-rank256.safetensors -P ./models/controlnet/\n",
|
||||||
|
"#!wget -c https://huggingface.co/stabilityai/control-lora/resolve/main/control-LoRAs-rank256/control-lora-depth-rank256.safetensors -P ./models/controlnet/\n",
|
||||||
|
"#!wget -c https://huggingface.co/stabilityai/control-lora/resolve/main/control-LoRAs-rank256/control-lora-recolor-rank256.safetensors -P ./models/controlnet/\n",
|
||||||
|
"#!wget -c https://huggingface.co/stabilityai/control-lora/resolve/main/control-LoRAs-rank256/control-lora-sketch-rank256.safetensors -P ./models/controlnet/\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Controlnet Preprocessor nodes by Fannovel16\n",
|
"# Controlnet Preprocessor nodes by Fannovel16\n",
|
||||||
"#!cd custom_nodes && git clone https://github.com/Fannovel16/comfy_controlnet_preprocessors; cd comfy_controlnet_preprocessors && python install.py\n",
|
"#!cd custom_nodes && git clone https://github.com/Fannovel16/comfy_controlnet_preprocessors; cd comfy_controlnet_preprocessors && python install.py\n",
|
||||||
@ -151,13 +166,64 @@
|
|||||||
"\n"
|
"\n"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "kkkkkkkkkkkkkkk"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"### Run ComfyUI with cloudflared (Recommended Way)\n",
|
||||||
|
"\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"id": "jjjjjjjjjjjjjj"
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"!wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb\n",
|
||||||
|
"!dpkg -i cloudflared-linux-amd64.deb\n",
|
||||||
|
"\n",
|
||||||
|
"import subprocess\n",
|
||||||
|
"import threading\n",
|
||||||
|
"import time\n",
|
||||||
|
"import socket\n",
|
||||||
|
"import urllib.request\n",
|
||||||
|
"\n",
|
||||||
|
"def iframe_thread(port):\n",
|
||||||
|
" while True:\n",
|
||||||
|
" time.sleep(0.5)\n",
|
||||||
|
" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
|
||||||
|
" result = sock.connect_ex(('127.0.0.1', port))\n",
|
||||||
|
" if result == 0:\n",
|
||||||
|
" break\n",
|
||||||
|
" sock.close()\n",
|
||||||
|
" print(\"\\nComfyUI finished loading, trying to launch cloudflared (if it gets stuck here cloudflared is having issues)\\n\")\n",
|
||||||
|
"\n",
|
||||||
|
" p = subprocess.Popen([\"cloudflared\", \"tunnel\", \"--url\", \"http://127.0.0.1:{}\".format(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n",
|
||||||
|
" for line in p.stderr:\n",
|
||||||
|
" l = line.decode()\n",
|
||||||
|
" if \"trycloudflare.com \" in l:\n",
|
||||||
|
" print(\"This is the URL to access ComfyUI:\", l[l.find(\"http\"):], end='')\n",
|
||||||
|
" #print(l, end='')\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"threading.Thread(target=iframe_thread, daemon=True, args=(8188,)).start()\n",
|
||||||
|
"\n",
|
||||||
|
"!python main.py --dont-print-server"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"id": "kkkkkkkkkkkkkk"
|
"id": "kkkkkkkkkkkkkk"
|
||||||
},
|
},
|
||||||
"source": [
|
"source": [
|
||||||
"### Run ComfyUI with localtunnel (Recommended Way)\n",
|
"### Run ComfyUI with localtunnel\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n"
|
"\n"
|
||||||
]
|
]
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
torch
|
torch
|
||||||
torchdiffeq
|
|
||||||
torchsde
|
torchsde
|
||||||
einops
|
einops
|
||||||
transformers>=4.25.1
|
transformers>=4.25.1
|
||||||
@ -10,3 +9,4 @@ pyyaml
|
|||||||
Pillow
|
Pillow
|
||||||
scipy
|
scipy
|
||||||
tqdm
|
tqdm
|
||||||
|
psutil
|
||||||
|
|||||||
@ -2,8 +2,12 @@ import json
|
|||||||
from urllib import request, parse
|
from urllib import request, parse
|
||||||
import random
|
import random
|
||||||
|
|
||||||
#this is the ComfyUI api prompt format. If you want it for a specific workflow you can copy it from the prompt section
|
#This is the ComfyUI api prompt format.
|
||||||
#of the image metadata of images generated with ComfyUI
|
|
||||||
|
#If you want it for a specific workflow you can "enable dev mode options"
|
||||||
|
#in the settings of the UI (gear beside the "Queue Size: ") this will enable
|
||||||
|
#a button on the UI to save workflows in api format.
|
||||||
|
|
||||||
#keep in mind ComfyUI is pre alpha software so this format will change a bit.
|
#keep in mind ComfyUI is pre alpha software so this format will change a bit.
|
||||||
|
|
||||||
#this is the one for the default workflow
|
#this is the one for the default workflow
|
||||||
|
|||||||
97
server.py
97
server.py
@ -1,14 +1,18 @@
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import traceback
|
||||||
|
|
||||||
import nodes
|
import nodes
|
||||||
import folder_paths
|
import folder_paths
|
||||||
import execution
|
import execution
|
||||||
import uuid
|
import uuid
|
||||||
|
import urllib
|
||||||
import json
|
import json
|
||||||
import glob
|
import glob
|
||||||
import struct
|
import struct
|
||||||
from PIL import Image
|
from PIL import Image, ImageOps
|
||||||
|
from PIL.PngImagePlugin import PngInfo
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@ -29,6 +33,7 @@ import comfy.model_management
|
|||||||
|
|
||||||
class BinaryEventTypes:
|
class BinaryEventTypes:
|
||||||
PREVIEW_IMAGE = 1
|
PREVIEW_IMAGE = 1
|
||||||
|
UNENCODED_PREVIEW_IMAGE = 2
|
||||||
|
|
||||||
async def send_socket_catch_exception(function, message):
|
async def send_socket_catch_exception(function, message):
|
||||||
try:
|
try:
|
||||||
@ -66,6 +71,8 @@ class PromptServer():
|
|||||||
|
|
||||||
mimetypes.init()
|
mimetypes.init()
|
||||||
mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
|
mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
|
||||||
|
|
||||||
|
self.supports = ["custom_nodes_from_web"]
|
||||||
self.prompt_queue = None
|
self.prompt_queue = None
|
||||||
self.loop = loop
|
self.loop = loop
|
||||||
self.messages = asyncio.Queue()
|
self.messages = asyncio.Queue()
|
||||||
@ -75,7 +82,7 @@ class PromptServer():
|
|||||||
if args.enable_cors_header:
|
if args.enable_cors_header:
|
||||||
middlewares.append(create_cors_middleware(args.enable_cors_header))
|
middlewares.append(create_cors_middleware(args.enable_cors_header))
|
||||||
|
|
||||||
self.app = web.Application(client_max_size=20971520, middlewares=middlewares)
|
self.app = web.Application(client_max_size=104857600, middlewares=middlewares)
|
||||||
self.sockets = dict()
|
self.sockets = dict()
|
||||||
self.web_root = os.path.join(os.path.dirname(
|
self.web_root = os.path.join(os.path.dirname(
|
||||||
os.path.realpath(__file__)), "web")
|
os.path.realpath(__file__)), "web")
|
||||||
@ -84,6 +91,8 @@ class PromptServer():
|
|||||||
self.last_node_id = None
|
self.last_node_id = None
|
||||||
self.client_id = None
|
self.client_id = None
|
||||||
|
|
||||||
|
self.on_prompt_handlers = []
|
||||||
|
|
||||||
@routes.get('/ws')
|
@routes.get('/ws')
|
||||||
async def websocket_handler(request):
|
async def websocket_handler(request):
|
||||||
ws = web.WebSocketResponse()
|
ws = web.WebSocketResponse()
|
||||||
@ -118,12 +127,21 @@ class PromptServer():
|
|||||||
@routes.get("/embeddings")
|
@routes.get("/embeddings")
|
||||||
def get_embeddings(self):
|
def get_embeddings(self):
|
||||||
embeddings = folder_paths.get_filename_list("embeddings")
|
embeddings = folder_paths.get_filename_list("embeddings")
|
||||||
return web.json_response(list(map(lambda a: os.path.splitext(a)[0].lower(), embeddings)))
|
return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings)))
|
||||||
|
|
||||||
@routes.get("/extensions")
|
@routes.get("/extensions")
|
||||||
async def get_extensions(request):
|
async def get_extensions(request):
|
||||||
files = glob.glob(os.path.join(self.web_root, 'extensions/**/*.js'), recursive=True)
|
files = glob.glob(os.path.join(
|
||||||
return web.json_response(list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files)))
|
self.web_root, 'extensions/**/*.js'), recursive=True)
|
||||||
|
|
||||||
|
extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files))
|
||||||
|
|
||||||
|
for name, dir in nodes.EXTENSION_WEB_DIRS.items():
|
||||||
|
files = glob.glob(os.path.join(dir, '**/*.js'), recursive=True)
|
||||||
|
extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote(
|
||||||
|
name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files)))
|
||||||
|
|
||||||
|
return web.json_response(extensions)
|
||||||
|
|
||||||
def get_dir_by_type(dir_type):
|
def get_dir_by_type(dir_type):
|
||||||
if dir_type is None:
|
if dir_type is None:
|
||||||
@ -152,15 +170,15 @@ class PromptServer():
|
|||||||
|
|
||||||
subfolder = post.get("subfolder", "")
|
subfolder = post.get("subfolder", "")
|
||||||
full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder))
|
full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder))
|
||||||
|
filepath = os.path.abspath(os.path.join(full_output_folder, filename))
|
||||||
|
|
||||||
if os.path.commonpath((upload_dir, os.path.abspath(full_output_folder))) != upload_dir:
|
if os.path.commonpath((upload_dir, filepath)) != upload_dir:
|
||||||
return web.Response(status=400)
|
return web.Response(status=400)
|
||||||
|
|
||||||
if not os.path.exists(full_output_folder):
|
if not os.path.exists(full_output_folder):
|
||||||
os.makedirs(full_output_folder)
|
os.makedirs(full_output_folder)
|
||||||
|
|
||||||
split = os.path.splitext(filename)
|
split = os.path.splitext(filename)
|
||||||
filepath = os.path.join(full_output_folder, filename)
|
|
||||||
|
|
||||||
if overwrite is not None and (overwrite == "true" or overwrite == "1"):
|
if overwrite is not None and (overwrite == "true" or overwrite == "1"):
|
||||||
pass
|
pass
|
||||||
@ -216,13 +234,17 @@ class PromptServer():
|
|||||||
|
|
||||||
if os.path.isfile(file):
|
if os.path.isfile(file):
|
||||||
with Image.open(file) as original_pil:
|
with Image.open(file) as original_pil:
|
||||||
|
metadata = PngInfo()
|
||||||
|
if hasattr(original_pil,'text'):
|
||||||
|
for key in original_pil.text:
|
||||||
|
metadata.add_text(key, original_pil.text[key])
|
||||||
original_pil = original_pil.convert('RGBA')
|
original_pil = original_pil.convert('RGBA')
|
||||||
mask_pil = Image.open(image.file).convert('RGBA')
|
mask_pil = Image.open(image.file).convert('RGBA')
|
||||||
|
|
||||||
# alpha copy
|
# alpha copy
|
||||||
new_alpha = mask_pil.getchannel('A')
|
new_alpha = mask_pil.getchannel('A')
|
||||||
original_pil.putalpha(new_alpha)
|
original_pil.putalpha(new_alpha)
|
||||||
original_pil.save(filepath, compress_level=4)
|
original_pil.save(filepath, compress_level=4, pnginfo=metadata)
|
||||||
|
|
||||||
return image_upload(post, image_save_function)
|
return image_upload(post, image_save_function)
|
||||||
|
|
||||||
@ -344,6 +366,11 @@ class PromptServer():
|
|||||||
vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
|
vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
|
||||||
vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
|
vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
|
||||||
system_stats = {
|
system_stats = {
|
||||||
|
"system": {
|
||||||
|
"os": os.name,
|
||||||
|
"python_version": sys.version,
|
||||||
|
"embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded"
|
||||||
|
},
|
||||||
"devices": [
|
"devices": [
|
||||||
{
|
{
|
||||||
"name": device_name,
|
"name": device_name,
|
||||||
@ -371,7 +398,7 @@ class PromptServer():
|
|||||||
info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
|
info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
|
||||||
info['name'] = node_class
|
info['name'] = node_class
|
||||||
info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
|
info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
|
||||||
info['description'] = ''
|
info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
|
||||||
info['category'] = 'sd'
|
info['category'] = 'sd'
|
||||||
if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
|
if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
|
||||||
info['output_node'] = True
|
info['output_node'] = True
|
||||||
@ -420,6 +447,7 @@ class PromptServer():
|
|||||||
resp_code = 200
|
resp_code = 200
|
||||||
out_string = ""
|
out_string = ""
|
||||||
json_data = await request.json()
|
json_data = await request.json()
|
||||||
|
json_data = self.trigger_on_prompt(json_data)
|
||||||
|
|
||||||
if "number" in json_data:
|
if "number" in json_data:
|
||||||
number = float(json_data['number'])
|
number = float(json_data['number'])
|
||||||
@ -444,7 +472,8 @@ class PromptServer():
|
|||||||
prompt_id = str(uuid.uuid4())
|
prompt_id = str(uuid.uuid4())
|
||||||
outputs_to_execute = valid[2]
|
outputs_to_execute = valid[2]
|
||||||
self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
|
self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
|
||||||
return web.json_response({"prompt_id": prompt_id, "number": number})
|
response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
|
||||||
|
return web.json_response(response)
|
||||||
else:
|
else:
|
||||||
print("invalid prompt:", valid[1])
|
print("invalid prompt:", valid[1])
|
||||||
return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
|
return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
|
||||||
@ -485,6 +514,12 @@ class PromptServer():
|
|||||||
|
|
||||||
def add_routes(self):
|
def add_routes(self):
|
||||||
self.app.add_routes(self.routes)
|
self.app.add_routes(self.routes)
|
||||||
|
|
||||||
|
for name, dir in nodes.EXTENSION_WEB_DIRS.items():
|
||||||
|
self.app.add_routes([
|
||||||
|
web.static('/extensions/' + urllib.parse.quote(name), dir, follow_symlinks=True),
|
||||||
|
])
|
||||||
|
|
||||||
self.app.add_routes([
|
self.app.add_routes([
|
||||||
web.static('/', self.web_root, follow_symlinks=True),
|
web.static('/', self.web_root, follow_symlinks=True),
|
||||||
])
|
])
|
||||||
@ -497,7 +532,9 @@ class PromptServer():
|
|||||||
return prompt_info
|
return prompt_info
|
||||||
|
|
||||||
async def send(self, event, data, sid=None):
|
async def send(self, event, data, sid=None):
|
||||||
if isinstance(data, (bytes, bytearray)):
|
if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
|
||||||
|
await self.send_image(data, sid=sid)
|
||||||
|
elif isinstance(data, (bytes, bytearray)):
|
||||||
await self.send_bytes(event, data, sid)
|
await self.send_bytes(event, data, sid)
|
||||||
else:
|
else:
|
||||||
await self.send_json(event, data, sid)
|
await self.send_json(event, data, sid)
|
||||||
@ -511,6 +548,30 @@ class PromptServer():
|
|||||||
message.extend(data)
|
message.extend(data)
|
||||||
return message
|
return message
|
||||||
|
|
||||||
|
async def send_image(self, image_data, sid=None):
|
||||||
|
image_type = image_data[0]
|
||||||
|
image = image_data[1]
|
||||||
|
max_size = image_data[2]
|
||||||
|
if max_size is not None:
|
||||||
|
if hasattr(Image, 'Resampling'):
|
||||||
|
resampling = Image.Resampling.BILINEAR
|
||||||
|
else:
|
||||||
|
resampling = Image.ANTIALIAS
|
||||||
|
|
||||||
|
image = ImageOps.contain(image, (max_size, max_size), resampling)
|
||||||
|
type_num = 1
|
||||||
|
if image_type == "JPEG":
|
||||||
|
type_num = 1
|
||||||
|
elif image_type == "PNG":
|
||||||
|
type_num = 2
|
||||||
|
|
||||||
|
bytesIO = BytesIO()
|
||||||
|
header = struct.pack(">I", type_num)
|
||||||
|
bytesIO.write(header)
|
||||||
|
image.save(bytesIO, format=image_type, quality=95, compress_level=4)
|
||||||
|
preview_bytes = bytesIO.getvalue()
|
||||||
|
await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid)
|
||||||
|
|
||||||
async def send_bytes(self, event, data, sid=None):
|
async def send_bytes(self, event, data, sid=None):
|
||||||
message = self.encode_bytes(event, data)
|
message = self.encode_bytes(event, data)
|
||||||
|
|
||||||
@ -542,7 +603,7 @@ class PromptServer():
|
|||||||
await self.send(*msg)
|
await self.send(*msg)
|
||||||
|
|
||||||
async def start(self, address, port, verbose=True, call_on_start=None):
|
async def start(self, address, port, verbose=True, call_on_start=None):
|
||||||
runner = web.AppRunner(self.app)
|
runner = web.AppRunner(self.app, access_log=None)
|
||||||
await runner.setup()
|
await runner.setup()
|
||||||
site = web.TCPSite(runner, address, port)
|
site = web.TCPSite(runner, address, port)
|
||||||
await site.start()
|
await site.start()
|
||||||
@ -555,3 +616,15 @@ class PromptServer():
|
|||||||
if call_on_start is not None:
|
if call_on_start is not None:
|
||||||
call_on_start(address, port)
|
call_on_start(address, port)
|
||||||
|
|
||||||
|
def add_on_prompt_handler(self, handler):
|
||||||
|
self.on_prompt_handlers.append(handler)
|
||||||
|
|
||||||
|
def trigger_on_prompt(self, json_data):
|
||||||
|
for handler in self.on_prompt_handlers:
|
||||||
|
try:
|
||||||
|
json_data = handler(json_data)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] An error occurred during the on_prompt_handler processing")
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
|
return json_data
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
import { ComfyDialog, $el } from "/scripts/ui.js";
|
import { ComfyDialog, $el } from "../../scripts/ui.js";
|
||||||
import { ComfyApp } from "/scripts/app.js";
|
import { ComfyApp } from "../../scripts/app.js";
|
||||||
|
|
||||||
export class ClipspaceDialog extends ComfyDialog {
|
export class ClipspaceDialog extends ComfyDialog {
|
||||||
static items = [];
|
static items = [];
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import {app} from "/scripts/app.js";
|
import {app} from "../../scripts/app.js";
|
||||||
import {$el} from "/scripts/ui.js";
|
import {$el} from "../../scripts/ui.js";
|
||||||
|
|
||||||
// Manage color palettes
|
// Manage color palettes
|
||||||
|
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import {app} from "/scripts/app.js";
|
import {app} from "../../scripts/app.js";
|
||||||
|
|
||||||
// Adds filtering to combo context menus
|
// Adds filtering to combo context menus
|
||||||
|
|
||||||
@ -27,10 +27,13 @@ const ext = {
|
|||||||
const clickedComboValue = currentNode.widgets
|
const clickedComboValue = currentNode.widgets
|
||||||
.filter(w => w.type === "combo" && w.options.values.length === values.length)
|
.filter(w => w.type === "combo" && w.options.values.length === values.length)
|
||||||
.find(w => w.options.values.every((v, i) => v === values[i]))
|
.find(w => w.options.values.every((v, i) => v === values[i]))
|
||||||
.value;
|
?.value;
|
||||||
|
|
||||||
let selectedIndex = values.findIndex(v => v === clickedComboValue);
|
let selectedIndex = clickedComboValue ? values.findIndex(v => v === clickedComboValue) : 0;
|
||||||
let selectedItem = displayedItems?.[selectedIndex];
|
if (selectedIndex < 0) {
|
||||||
|
selectedIndex = 0;
|
||||||
|
}
|
||||||
|
let selectedItem = displayedItems[selectedIndex];
|
||||||
updateSelected();
|
updateSelected();
|
||||||
|
|
||||||
// Apply highlighting to the selected item
|
// Apply highlighting to the selected item
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
|
|
||||||
// Allows you to edit the attention weight by holding ctrl (or cmd) and using the up/down arrow keys
|
// Allows you to edit the attention weight by holding ctrl (or cmd) and using the up/down arrow keys
|
||||||
|
|
||||||
|
|||||||
167
web/extensions/core/groupOptions.js
Normal file
167
web/extensions/core/groupOptions.js
Normal file
@ -0,0 +1,167 @@
|
|||||||
|
import {app} from "../../scripts/app.js";
|
||||||
|
|
||||||
|
function setNodeMode(node, mode) {
|
||||||
|
node.mode = mode;
|
||||||
|
node.graph.change();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.registerExtension({
|
||||||
|
name: "Comfy.GroupOptions",
|
||||||
|
setup() {
|
||||||
|
const orig = LGraphCanvas.prototype.getCanvasMenuOptions;
|
||||||
|
// graph_mouse
|
||||||
|
LGraphCanvas.prototype.getCanvasMenuOptions = function () {
|
||||||
|
const options = orig.apply(this, arguments);
|
||||||
|
const group = this.graph.getGroupOnPos(this.graph_mouse[0], this.graph_mouse[1]);
|
||||||
|
if (!group) {
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group nodes aren't recomputed until the group is moved, this ensures the nodes are up-to-date
|
||||||
|
group.recomputeInsideNodes();
|
||||||
|
const nodesInGroup = group._nodes;
|
||||||
|
|
||||||
|
// No nodes in group, return default options
|
||||||
|
if (nodesInGroup.length === 0) {
|
||||||
|
return options;
|
||||||
|
} else {
|
||||||
|
// Add a separator between the default options and the group options
|
||||||
|
options.push(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if all nodes are the same mode
|
||||||
|
let allNodesAreSameMode = true;
|
||||||
|
for (let i = 1; i < nodesInGroup.length; i++) {
|
||||||
|
if (nodesInGroup[i].mode !== nodesInGroup[0].mode) {
|
||||||
|
allNodesAreSameMode = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Modes
|
||||||
|
// 0: Always
|
||||||
|
// 1: On Event
|
||||||
|
// 2: Never
|
||||||
|
// 3: On Trigger
|
||||||
|
// 4: Bypass
|
||||||
|
// If all nodes are the same mode, add a menu option to change the mode
|
||||||
|
if (allNodesAreSameMode) {
|
||||||
|
const mode = nodesInGroup[0].mode;
|
||||||
|
switch (mode) {
|
||||||
|
case 0:
|
||||||
|
// All nodes are always, option to disable, and bypass
|
||||||
|
options.push({
|
||||||
|
content: "Set Group Nodes to Never",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
options.push({
|
||||||
|
content: "Bypass Group Nodes",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
// All nodes are never, option to enable, and bypass
|
||||||
|
options.push({
|
||||||
|
content: "Set Group Nodes to Always",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
options.push({
|
||||||
|
content: "Bypass Group Nodes",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
// All nodes are bypass, option to enable, and disable
|
||||||
|
options.push({
|
||||||
|
content: "Set Group Nodes to Always",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
options.push({
|
||||||
|
content: "Set Group Nodes to Never",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
// All nodes are On Trigger or On Event(Or other?), option to disable, set to always, or bypass
|
||||||
|
options.push({
|
||||||
|
content: "Set Group Nodes to Always",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
options.push({
|
||||||
|
content: "Set Group Nodes to Never",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
options.push({
|
||||||
|
content: "Bypass Group Nodes",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Nodes are not all the same mode, add a menu option to change the mode to always, never, or bypass
|
||||||
|
options.push({
|
||||||
|
content: "Set Group Nodes to Always",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
options.push({
|
||||||
|
content: "Set Group Nodes to Never",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
options.push({
|
||||||
|
content: "Bypass Group Nodes",
|
||||||
|
callback: () => {
|
||||||
|
for (const node of nodesInGroup) {
|
||||||
|
setNodeMode(node, 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@ -1,4 +1,4 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
|
|
||||||
// Inverts the scrolling of context menus
|
// Inverts the scrolling of context menus
|
||||||
|
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import {app} from "/scripts/app.js";
|
import {app} from "../../scripts/app.js";
|
||||||
|
|
||||||
app.registerExtension({
|
app.registerExtension({
|
||||||
name: "Comfy.Keybinds",
|
name: "Comfy.Keybinds",
|
||||||
|
|||||||
25
web/extensions/core/linkRenderMode.js
Normal file
25
web/extensions/core/linkRenderMode.js
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { app } from "../../scripts/app.js";
|
||||||
|
|
||||||
|
const id = "Comfy.LinkRenderMode";
|
||||||
|
const ext = {
|
||||||
|
name: id,
|
||||||
|
async setup(app) {
|
||||||
|
app.ui.settings.addSetting({
|
||||||
|
id,
|
||||||
|
name: "Link Render Mode",
|
||||||
|
defaultValue: 2,
|
||||||
|
type: "combo",
|
||||||
|
options: [...LiteGraph.LINK_RENDER_MODES, "Hidden"].map((m, i) => ({
|
||||||
|
value: i,
|
||||||
|
text: m,
|
||||||
|
selected: i == app.canvas.links_render_mode,
|
||||||
|
})),
|
||||||
|
onChange(value) {
|
||||||
|
app.canvas.links_render_mode = +value;
|
||||||
|
app.graph.setDirtyCanvas(true);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
app.registerExtension(ext);
|
||||||
@ -1,7 +1,8 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
import { ComfyDialog, $el } from "/scripts/ui.js";
|
import { ComfyDialog, $el } from "../../scripts/ui.js";
|
||||||
import { ComfyApp } from "/scripts/app.js";
|
import { ComfyApp } from "../../scripts/app.js";
|
||||||
import { ClipspaceDialog } from "/extensions/core/clipspace.js";
|
import { api } from "../../scripts/api.js"
|
||||||
|
import { ClipspaceDialog } from "./clipspace.js";
|
||||||
|
|
||||||
// Helper function to convert a data URL to a Blob object
|
// Helper function to convert a data URL to a Blob object
|
||||||
function dataURLToBlob(dataURL) {
|
function dataURLToBlob(dataURL) {
|
||||||
@ -33,7 +34,7 @@ function loadedImageToBlob(image) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function uploadMask(filepath, formData) {
|
async function uploadMask(filepath, formData) {
|
||||||
await fetch('/upload/mask', {
|
await api.fetchApi('/upload/mask', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: formData
|
body: formData
|
||||||
}).then(response => {}).catch(error => {
|
}).then(response => {}).catch(error => {
|
||||||
@ -41,7 +42,7 @@ async function uploadMask(filepath, formData) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']] = new Image();
|
ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']] = new Image();
|
||||||
ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src = "/view?" + new URLSearchParams(filepath).toString() + app.getPreviewFormatParam();
|
ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src = api.apiURL("/view?" + new URLSearchParams(filepath).toString() + app.getPreviewFormatParam());
|
||||||
|
|
||||||
if(ComfyApp.clipspace.images)
|
if(ComfyApp.clipspace.images)
|
||||||
ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] = filepath;
|
ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] = filepath;
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
import { ComfyDialog, $el } from "/scripts/ui.js";
|
import { ComfyDialog, $el } from "../../scripts/ui.js";
|
||||||
|
|
||||||
// Adds the ability to save and add multiple nodes as a template
|
// Adds the ability to save and add multiple nodes as a template
|
||||||
// To save:
|
// To save:
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
|
|
||||||
// Use widget values and dates in output filenames
|
// Use widget values and dates in output filenames
|
||||||
|
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
import { ComfyWidgets } from "/scripts/widgets.js";
|
import { ComfyWidgets } from "../../scripts/widgets.js";
|
||||||
// Adds defaults for quickly adding nodes with middle click on the input/output
|
// Adds defaults for quickly adding nodes with middle click on the input/output
|
||||||
|
|
||||||
app.registerExtension({
|
app.registerExtension({
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
|
|
||||||
// Shift + drag/resize to snap to grid
|
// Shift + drag/resize to snap to grid
|
||||||
|
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
|
|
||||||
// Adds an upload button to the nodes
|
// Adds an upload button to the nodes
|
||||||
|
|
||||||
app.registerExtension({
|
app.registerExtension({
|
||||||
name: "Comfy.UploadImage",
|
name: "Comfy.UploadImage",
|
||||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||||
if (nodeData.name === "LoadImage" || nodeData.name === "LoadImageMask") {
|
if (nodeData?.input?.required?.image?.[1]?.image_upload === true) {
|
||||||
nodeData.input.required.upload = ["IMAGEUPLOAD"];
|
nodeData.input.required.upload = ["IMAGEUPLOAD"];
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
import { ComfyWidgets, addValueControlWidget } from "/scripts/widgets.js";
|
import { ComfyWidgets, addValueControlWidget } from "../../scripts/widgets.js";
|
||||||
import { app } from "/scripts/app.js";
|
import { app } from "../../scripts/app.js";
|
||||||
|
|
||||||
const CONVERTED_TYPE = "converted-widget";
|
const CONVERTED_TYPE = "converted-widget";
|
||||||
const VALID_TYPES = ["STRING", "combo", "number"];
|
const VALID_TYPES = ["STRING", "combo", "number", "BOOLEAN"];
|
||||||
|
|
||||||
function isConvertableWidget(widget, config) {
|
function isConvertableWidget(widget, config) {
|
||||||
return VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0]);
|
return (VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0])) && !widget.options?.forceInput;
|
||||||
}
|
}
|
||||||
|
|
||||||
function hideWidget(node, widget, suffix = "") {
|
function hideWidget(node, widget, suffix = "") {
|
||||||
@ -16,8 +16,12 @@ function hideWidget(node, widget, suffix = "") {
|
|||||||
widget.type = CONVERTED_TYPE + suffix;
|
widget.type = CONVERTED_TYPE + suffix;
|
||||||
widget.serializeValue = () => {
|
widget.serializeValue = () => {
|
||||||
// Prevent serializing the widget if we have no input linked
|
// Prevent serializing the widget if we have no input linked
|
||||||
const { link } = node.inputs.find((i) => i.widget?.name === widget.name);
|
if (!node.inputs) {
|
||||||
if (link == null) {
|
return undefined;
|
||||||
|
}
|
||||||
|
let node_input = node.inputs.find((i) => i.widget?.name === widget.name);
|
||||||
|
|
||||||
|
if (!node_input || !node_input.link) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
return widget.origSerializeValue ? widget.origSerializeValue() : widget.value;
|
return widget.origSerializeValue ? widget.origSerializeValue() : widget.value;
|
||||||
@ -103,6 +107,9 @@ app.registerExtension({
|
|||||||
let toInput = [];
|
let toInput = [];
|
||||||
let toWidget = [];
|
let toWidget = [];
|
||||||
for (const w of this.widgets) {
|
for (const w of this.widgets) {
|
||||||
|
if (w.options?.forceInput) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (w.type === CONVERTED_TYPE) {
|
if (w.type === CONVERTED_TYPE) {
|
||||||
toWidget.push({
|
toWidget.push({
|
||||||
content: `Convert ${w.name} to widget`,
|
content: `Convert ${w.name} to widget`,
|
||||||
@ -130,6 +137,20 @@ app.registerExtension({
|
|||||||
return r;
|
return r;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const origOnNodeCreated = nodeType.prototype.onNodeCreated
|
||||||
|
nodeType.prototype.onNodeCreated = function () {
|
||||||
|
const r = origOnNodeCreated ? origOnNodeCreated.apply(this) : undefined;
|
||||||
|
if (this.widgets) {
|
||||||
|
for (const w of this.widgets) {
|
||||||
|
if (w?.options?.forceInput || w?.options?.defaultInput) {
|
||||||
|
const config = nodeData?.input?.required[w.name] || nodeData?.input?.optional?.[w.name] || [w.type, w.options || {}];
|
||||||
|
convertToInput(this, w, config);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
// On initial configure of nodes hide all converted widgets
|
// On initial configure of nodes hide all converted widgets
|
||||||
const origOnConfigure = nodeType.prototype.onConfigure;
|
const origOnConfigure = nodeType.prototype.onConfigure;
|
||||||
nodeType.prototype.onConfigure = function () {
|
nodeType.prototype.onConfigure = function () {
|
||||||
@ -137,7 +158,7 @@ app.registerExtension({
|
|||||||
|
|
||||||
if (this.inputs) {
|
if (this.inputs) {
|
||||||
for (const input of this.inputs) {
|
for (const input of this.inputs) {
|
||||||
if (input.widget) {
|
if (input.widget && !input.widget.config[1]?.forceInput) {
|
||||||
const w = this.widgets.find((w) => w.name === input.widget.name);
|
const w = this.widgets.find((w) => w.name === input.widget.name);
|
||||||
if (w) {
|
if (w) {
|
||||||
hideWidget(this, w);
|
hideWidget(this, w);
|
||||||
@ -374,7 +395,7 @@ app.registerExtension({
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const k in config1[1]) {
|
for (const k in config1[1]) {
|
||||||
if (k !== "default") {
|
if (k !== "default" && k !== 'forceInput') {
|
||||||
if (config1[1][k] !== config2[1][k]) {
|
if (config1[1][k] !== config2[1][k]) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,12 +4,13 @@
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<title>ComfyUI</title>
|
<title>ComfyUI</title>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||||
<link rel="stylesheet" type="text/css" href="lib/litegraph.css" />
|
<link rel="stylesheet" type="text/css" href="./lib/litegraph.css" />
|
||||||
<link rel="stylesheet" type="text/css" href="style.css" />
|
<link rel="stylesheet" type="text/css" href="./style.css" />
|
||||||
<script type="text/javascript" src="lib/litegraph.core.js"></script>
|
<link rel="stylesheet" type="text/css" href="./user.css" />
|
||||||
<script type="text/javascript" src="lib/litegraph.extensions.js" defer></script>
|
<script type="text/javascript" src="./lib/litegraph.core.js"></script>
|
||||||
|
<script type="text/javascript" src="./lib/litegraph.extensions.js" defer></script>
|
||||||
<script type="module">
|
<script type="module">
|
||||||
import { app } from "/scripts/app.js";
|
import { app } from "./scripts/app.js";
|
||||||
await app.setup();
|
await app.setup();
|
||||||
window.app = app;
|
window.app = app;
|
||||||
window.graph = app.graph;
|
window.graph = app.graph;
|
||||||
|
|||||||
@ -144,6 +144,10 @@
|
|||||||
|
|
||||||
ctrl_shift_v_paste_connect_unselected_outputs: true, //[true!] allows ctrl + shift + v to paste nodes with the outputs of the unselected nodes connected with the inputs of the newly pasted nodes
|
ctrl_shift_v_paste_connect_unselected_outputs: true, //[true!] allows ctrl + shift + v to paste nodes with the outputs of the unselected nodes connected with the inputs of the newly pasted nodes
|
||||||
|
|
||||||
|
// if true, all newly created nodes/links will use string UUIDs for their id fields instead of integers.
|
||||||
|
// use this if you must have node IDs that are unique across all graphs and subgraphs.
|
||||||
|
use_uuids: false,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register a node class so it can be listed when the user wants to create a new one
|
* Register a node class so it can be listed when the user wants to create a new one
|
||||||
* @method registerNodeType
|
* @method registerNodeType
|
||||||
@ -603,6 +607,13 @@
|
|||||||
return target;
|
return target;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/*
|
||||||
|
* https://gist.github.com/jed/982883?permalink_comment_id=852670#gistcomment-852670
|
||||||
|
*/
|
||||||
|
uuidv4: function() {
|
||||||
|
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,a=>(a^Math.random()*16>>a/4).toString(16));
|
||||||
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns if the types of two slots are compatible (taking into account wildcards, etc)
|
* Returns if the types of two slots are compatible (taking into account wildcards, etc)
|
||||||
* @method isValidConnection
|
* @method isValidConnection
|
||||||
@ -1407,7 +1418,12 @@
|
|||||||
console.warn(
|
console.warn(
|
||||||
"LiteGraph: there is already a node with this ID, changing it"
|
"LiteGraph: there is already a node with this ID, changing it"
|
||||||
);
|
);
|
||||||
node.id = ++this.last_node_id;
|
if (LiteGraph.use_uuids) {
|
||||||
|
node.id = LiteGraph.uuidv4();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
node.id = ++this.last_node_id;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this._nodes.length >= LiteGraph.MAX_NUMBER_OF_NODES) {
|
if (this._nodes.length >= LiteGraph.MAX_NUMBER_OF_NODES) {
|
||||||
@ -1415,10 +1431,16 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
//give him an id
|
//give him an id
|
||||||
if (node.id == null || node.id == -1) {
|
if (LiteGraph.use_uuids) {
|
||||||
node.id = ++this.last_node_id;
|
if (node.id == null || node.id == -1)
|
||||||
} else if (this.last_node_id < node.id) {
|
node.id = LiteGraph.uuidv4();
|
||||||
this.last_node_id = node.id;
|
}
|
||||||
|
else {
|
||||||
|
if (node.id == null || node.id == -1) {
|
||||||
|
node.id = ++this.last_node_id;
|
||||||
|
} else if (this.last_node_id < node.id) {
|
||||||
|
this.last_node_id = node.id;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
node.graph = this;
|
node.graph = this;
|
||||||
@ -2415,7 +2437,12 @@
|
|||||||
enumerable: true
|
enumerable: true
|
||||||
});
|
});
|
||||||
|
|
||||||
this.id = -1; //not know till not added
|
if (LiteGraph.use_uuids) {
|
||||||
|
this.id = LiteGraph.uuidv4();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
this.id = -1; //not know till not added
|
||||||
|
}
|
||||||
this.type = null;
|
this.type = null;
|
||||||
|
|
||||||
//inputs available: array of inputs
|
//inputs available: array of inputs
|
||||||
@ -2629,6 +2656,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
delete data["id"];
|
delete data["id"];
|
||||||
|
|
||||||
|
if (LiteGraph.use_uuids) {
|
||||||
|
data["id"] = LiteGraph.uuidv4()
|
||||||
|
}
|
||||||
|
|
||||||
//remove links
|
//remove links
|
||||||
node.configure(data);
|
node.configure(data);
|
||||||
|
|
||||||
@ -3540,8 +3572,8 @@
|
|||||||
/**
|
/**
|
||||||
* computes the minimum size of a node according to its inputs and output slots
|
* computes the minimum size of a node according to its inputs and output slots
|
||||||
* @method computeSize
|
* @method computeSize
|
||||||
* @param {number} minHeight
|
* @param {vec2} minHeight
|
||||||
* @return {number} the total size
|
* @return {vec2} the total size
|
||||||
*/
|
*/
|
||||||
LGraphNode.prototype.computeSize = function(out) {
|
LGraphNode.prototype.computeSize = function(out) {
|
||||||
if (this.constructor.size) {
|
if (this.constructor.size) {
|
||||||
@ -4280,9 +4312,15 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var nextId
|
||||||
|
if (LiteGraph.use_uuids)
|
||||||
|
nextId = LiteGraph.uuidv4();
|
||||||
|
else
|
||||||
|
nextId = ++this.graph.last_link_id;
|
||||||
|
|
||||||
//create link class
|
//create link class
|
||||||
link_info = new LLink(
|
link_info = new LLink(
|
||||||
++this.graph.last_link_id,
|
nextId,
|
||||||
input.type || output.type,
|
input.type || output.type,
|
||||||
this.id,
|
this.id,
|
||||||
slot,
|
slot,
|
||||||
@ -6023,6 +6061,9 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
//it wasn't clicked on the links boxes
|
//it wasn't clicked on the links boxes
|
||||||
if (!skip_action) {
|
if (!skip_action) {
|
||||||
var block_drag_node = false;
|
var block_drag_node = false;
|
||||||
|
if(node && node.flags && node.flags.pinned) {
|
||||||
|
block_drag_node = true;
|
||||||
|
}
|
||||||
var pos = [e.canvasX - node.pos[0], e.canvasY - node.pos[1]];
|
var pos = [e.canvasX - node.pos[0], e.canvasY - node.pos[1]];
|
||||||
|
|
||||||
//widgets
|
//widgets
|
||||||
@ -6192,12 +6233,18 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
,posAdd:[!mClikSlot_isOut?-30:30, -alphaPosY*130] //-alphaPosY*30]
|
,posAdd:[!mClikSlot_isOut?-30:30, -alphaPosY*130] //-alphaPosY*30]
|
||||||
,posSizeFix:[!mClikSlot_isOut?-1:0, 0] //-alphaPosY*2*/
|
,posSizeFix:[!mClikSlot_isOut?-1:0, 0] //-alphaPosY*2*/
|
||||||
});
|
});
|
||||||
|
skip_action = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!skip_action && this.allow_dragcanvas) {
|
||||||
|
//console.log("pointerevents: dragging_canvas start from middle button");
|
||||||
|
this.dragging_canvas = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
} else if (e.which == 3 || this.pointer_is_double) {
|
} else if (e.which == 3 || this.pointer_is_double) {
|
||||||
|
|
||||||
//right button
|
//right button
|
||||||
@ -7070,6 +7117,8 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
var selected_nodes_array = [];
|
var selected_nodes_array = [];
|
||||||
for (var i in this.selected_nodes) {
|
for (var i in this.selected_nodes) {
|
||||||
var node = this.selected_nodes[i];
|
var node = this.selected_nodes[i];
|
||||||
|
if (node.clonable === false)
|
||||||
|
continue;
|
||||||
node._relative_id = index;
|
node._relative_id = index;
|
||||||
selected_nodes_array.push(node);
|
selected_nodes_array.push(node);
|
||||||
index += 1;
|
index += 1;
|
||||||
@ -7077,12 +7126,12 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
|
|
||||||
for (var i = 0; i < selected_nodes_array.length; ++i) {
|
for (var i = 0; i < selected_nodes_array.length; ++i) {
|
||||||
var node = selected_nodes_array[i];
|
var node = selected_nodes_array[i];
|
||||||
var cloned = node.clone();
|
var cloned = node.clone();
|
||||||
if(!cloned)
|
if(!cloned)
|
||||||
{
|
{
|
||||||
console.warn("node type not found: " + node.type );
|
console.warn("node type not found: " + node.type );
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
clipboard_info.nodes.push(cloned.serialize());
|
clipboard_info.nodes.push(cloned.serialize());
|
||||||
if (node.inputs && node.inputs.length) {
|
if (node.inputs && node.inputs.length) {
|
||||||
for (var j = 0; j < node.inputs.length; ++j) {
|
for (var j = 0; j < node.inputs.length; ++j) {
|
||||||
@ -8148,7 +8197,7 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
**/
|
**/
|
||||||
LGraphCanvas.prototype.renderInfo = function(ctx, x, y) {
|
LGraphCanvas.prototype.renderInfo = function(ctx, x, y) {
|
||||||
x = x || 10;
|
x = x || 10;
|
||||||
y = y || this.canvas.height - 80;
|
y = y || this.canvas.offsetHeight - 80;
|
||||||
|
|
||||||
ctx.save();
|
ctx.save();
|
||||||
ctx.translate(x, y);
|
ctx.translate(x, y);
|
||||||
@ -9723,6 +9772,7 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
|
|
||||||
switch (w.type) {
|
switch (w.type) {
|
||||||
case "button":
|
case "button":
|
||||||
|
ctx.fillStyle = background_color;
|
||||||
if (w.clicked) {
|
if (w.clicked) {
|
||||||
ctx.fillStyle = "#AAA";
|
ctx.fillStyle = "#AAA";
|
||||||
w.clicked = false;
|
w.clicked = false;
|
||||||
@ -9792,7 +9842,11 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
ctx.textAlign = "center";
|
ctx.textAlign = "center";
|
||||||
ctx.fillStyle = text_color;
|
ctx.fillStyle = text_color;
|
||||||
ctx.fillText(
|
ctx.fillText(
|
||||||
w.label || w.name + " " + Number(w.value).toFixed(3),
|
w.label || w.name + " " + Number(w.value).toFixed(
|
||||||
|
w.options.precision != null
|
||||||
|
? w.options.precision
|
||||||
|
: 3
|
||||||
|
),
|
||||||
widget_width * 0.5,
|
widget_width * 0.5,
|
||||||
y + H * 0.7
|
y + H * 0.7
|
||||||
);
|
);
|
||||||
@ -9952,7 +10006,7 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
break;
|
break;
|
||||||
case "slider":
|
case "slider":
|
||||||
var old_value = w.value;
|
var old_value = w.value;
|
||||||
var nvalue = Math.clamp((x - 15) / (widget_width - 30), 0, 1);
|
var nvalue = clamp((x - 15) / (widget_width - 30), 0, 1);
|
||||||
if(w.options.read_only) break;
|
if(w.options.read_only) break;
|
||||||
w.value = w.options.min + (w.options.max - w.options.min) * nvalue;
|
w.value = w.options.min + (w.options.max - w.options.min) * nvalue;
|
||||||
if (old_value != w.value) {
|
if (old_value != w.value) {
|
||||||
@ -11475,7 +11529,7 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
if (timeout) {
|
if (timeout) {
|
||||||
clearInterval(timeout);
|
clearInterval(timeout);
|
||||||
}
|
}
|
||||||
timeout = setTimeout(refreshHelper, 250);
|
timeout = setTimeout(refreshHelper, 10);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@ -12949,7 +13003,7 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
var newSelected = {};
|
var newSelected = {};
|
||||||
|
|
||||||
var fApplyMultiNode = function(node){
|
var fApplyMultiNode = function(node){
|
||||||
if (node.clonable == false) {
|
if (node.clonable === false) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var newnode = node.clone();
|
var newnode = node.clone();
|
||||||
@ -13792,7 +13846,7 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
if (!disabled) {
|
if (!disabled) {
|
||||||
element.addEventListener("click", inner_onclick);
|
element.addEventListener("click", inner_onclick);
|
||||||
}
|
}
|
||||||
if (options.autoopen) {
|
if (!disabled && options.autoopen) {
|
||||||
LiteGraph.pointerListenerAdd(element,"enter",inner_over);
|
LiteGraph.pointerListenerAdd(element,"enter",inner_over);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -14148,10 +14202,10 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if( !is_edge_point ) //not edges
|
if( !is_edge_point ) //not edges
|
||||||
point[0] = Math.clamp(x,0,1);
|
point[0] = clamp(x, 0, 1);
|
||||||
else
|
else
|
||||||
point[0] = s == 0 ? 0 : 1;
|
point[0] = s == 0 ? 0 : 1;
|
||||||
point[1] = 1.0 - Math.clamp(y,0,1);
|
point[1] = 1.0 - clamp(y, 0, 1);
|
||||||
points.sort(function(a,b){ return a[0] - b[0]; });
|
points.sort(function(a,b){ return a[0] - b[0]; });
|
||||||
this.selected = points.indexOf(point);
|
this.selected = points.indexOf(point);
|
||||||
this.must_update = true;
|
this.must_update = true;
|
||||||
@ -14300,9 +14354,10 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Math.clamp = function(v, a, b) {
|
function clamp(v, a, b) {
|
||||||
return a > v ? a : b < v ? b : v;
|
return a > v ? a : b < v ? b : v;
|
||||||
};
|
};
|
||||||
|
global.clamp = clamp;
|
||||||
|
|
||||||
if (typeof window != "undefined" && !window["requestAnimationFrame"]) {
|
if (typeof window != "undefined" && !window["requestAnimationFrame"]) {
|
||||||
window.requestAnimationFrame =
|
window.requestAnimationFrame =
|
||||||
@ -14316,6 +14371,13 @@ LGraphNode.prototype.executeAction = function(action)
|
|||||||
|
|
||||||
if (typeof exports != "undefined") {
|
if (typeof exports != "undefined") {
|
||||||
exports.LiteGraph = this.LiteGraph;
|
exports.LiteGraph = this.LiteGraph;
|
||||||
|
exports.LGraph = this.LGraph;
|
||||||
|
exports.LLink = this.LLink;
|
||||||
|
exports.LGraphNode = this.LGraphNode;
|
||||||
|
exports.LGraphGroup = this.LGraphGroup;
|
||||||
|
exports.DragAndScale = this.DragAndScale;
|
||||||
|
exports.LGraphCanvas = this.LGraphCanvas;
|
||||||
|
exports.ContextMenu = this.ContextMenu;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -3,6 +3,16 @@ class ComfyApi extends EventTarget {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
|
this.api_host = location.host;
|
||||||
|
this.api_base = location.pathname.split('/').slice(0, -1).join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
apiURL(route) {
|
||||||
|
return this.api_base + route;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchApi(route, options) {
|
||||||
|
return fetch(this.apiURL(route), options);
|
||||||
}
|
}
|
||||||
|
|
||||||
addEventListener(type, callback, options) {
|
addEventListener(type, callback, options) {
|
||||||
@ -16,7 +26,7 @@ class ComfyApi extends EventTarget {
|
|||||||
#pollQueue() {
|
#pollQueue() {
|
||||||
setInterval(async () => {
|
setInterval(async () => {
|
||||||
try {
|
try {
|
||||||
const resp = await fetch("/prompt");
|
const resp = await this.fetchApi("/prompt");
|
||||||
const status = await resp.json();
|
const status = await resp.json();
|
||||||
this.dispatchEvent(new CustomEvent("status", { detail: status }));
|
this.dispatchEvent(new CustomEvent("status", { detail: status }));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -40,7 +50,7 @@ class ComfyApi extends EventTarget {
|
|||||||
existingSession = "?clientId=" + existingSession;
|
existingSession = "?clientId=" + existingSession;
|
||||||
}
|
}
|
||||||
this.socket = new WebSocket(
|
this.socket = new WebSocket(
|
||||||
`ws${window.location.protocol === "https:" ? "s" : ""}://${location.host}/ws${existingSession}`
|
`ws${window.location.protocol === "https:" ? "s" : ""}://${this.api_host}${this.api_base}/ws${existingSession}`
|
||||||
);
|
);
|
||||||
this.socket.binaryType = "arraybuffer";
|
this.socket.binaryType = "arraybuffer";
|
||||||
|
|
||||||
@ -149,7 +159,7 @@ class ComfyApi extends EventTarget {
|
|||||||
* @returns An array of script urls to import
|
* @returns An array of script urls to import
|
||||||
*/
|
*/
|
||||||
async getExtensions() {
|
async getExtensions() {
|
||||||
const resp = await fetch("/extensions", { cache: "no-store" });
|
const resp = await this.fetchApi("/extensions", { cache: "no-store" });
|
||||||
return await resp.json();
|
return await resp.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -158,7 +168,7 @@ class ComfyApi extends EventTarget {
|
|||||||
* @returns An array of script urls to import
|
* @returns An array of script urls to import
|
||||||
*/
|
*/
|
||||||
async getEmbeddings() {
|
async getEmbeddings() {
|
||||||
const resp = await fetch("/embeddings", { cache: "no-store" });
|
const resp = await this.fetchApi("/embeddings", { cache: "no-store" });
|
||||||
return await resp.json();
|
return await resp.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -167,7 +177,7 @@ class ComfyApi extends EventTarget {
|
|||||||
* @returns The node definitions
|
* @returns The node definitions
|
||||||
*/
|
*/
|
||||||
async getNodeDefs() {
|
async getNodeDefs() {
|
||||||
const resp = await fetch("object_info", { cache: "no-store" });
|
const resp = await this.fetchApi("/object_info", { cache: "no-store" });
|
||||||
return await resp.json();
|
return await resp.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -189,7 +199,7 @@ class ComfyApi extends EventTarget {
|
|||||||
body.number = number;
|
body.number = number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await fetch("/prompt", {
|
const res = await this.fetchApi("/prompt", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@ -202,6 +212,8 @@ class ComfyApi extends EventTarget {
|
|||||||
response: await res.json(),
|
response: await res.json(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return await res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -222,7 +234,7 @@ class ComfyApi extends EventTarget {
|
|||||||
*/
|
*/
|
||||||
async getQueue() {
|
async getQueue() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/queue");
|
const res = await this.fetchApi("/queue");
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
return {
|
return {
|
||||||
// Running action uses a different endpoint for cancelling
|
// Running action uses a different endpoint for cancelling
|
||||||
@ -244,7 +256,7 @@ class ComfyApi extends EventTarget {
|
|||||||
*/
|
*/
|
||||||
async getHistory() {
|
async getHistory() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/history");
|
const res = await this.fetchApi("/history");
|
||||||
return { History: Object.values(await res.json()) };
|
return { History: Object.values(await res.json()) };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
@ -252,6 +264,15 @@ class ComfyApi extends EventTarget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets system & device stats
|
||||||
|
* @returns System stats such as python version, OS, per device info
|
||||||
|
*/
|
||||||
|
async getSystemStats() {
|
||||||
|
const res = await this.fetchApi("/system_stats");
|
||||||
|
return await res.json();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends a POST request to the API
|
* Sends a POST request to the API
|
||||||
* @param {*} type The endpoint to post to
|
* @param {*} type The endpoint to post to
|
||||||
@ -259,7 +280,7 @@ class ComfyApi extends EventTarget {
|
|||||||
*/
|
*/
|
||||||
async #postItem(type, body) {
|
async #postItem(type, body) {
|
||||||
try {
|
try {
|
||||||
await fetch("/" + type, {
|
await this.fetchApi("/" + type, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
|
import { ComfyLogging } from "./logging.js";
|
||||||
import { ComfyWidgets } from "./widgets.js";
|
import { ComfyWidgets } from "./widgets.js";
|
||||||
import { ComfyUI, $el } from "./ui.js";
|
import { ComfyUI, $el } from "./ui.js";
|
||||||
import { api } from "./api.js";
|
import { api } from "./api.js";
|
||||||
@ -31,6 +32,7 @@ export class ComfyApp {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.ui = new ComfyUI(this);
|
this.ui = new ComfyUI(this);
|
||||||
|
this.logging = new ComfyLogging(this);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* List of extensions that are registered with the app
|
* List of extensions that are registered with the app
|
||||||
@ -282,6 +284,11 @@ export class ComfyApp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
options.push({
|
||||||
|
content: "Bypass",
|
||||||
|
callback: (obj) => { if (this.mode === 4) this.mode = 0; else this.mode = 4; this.graph.change(); }
|
||||||
|
});
|
||||||
|
|
||||||
// prevent conflict of clipspace content
|
// prevent conflict of clipspace content
|
||||||
if(!ComfyApp.clipspace_return_node) {
|
if(!ComfyApp.clipspace_return_node) {
|
||||||
options.push({
|
options.push({
|
||||||
@ -368,7 +375,11 @@ export class ComfyApp {
|
|||||||
shiftY = w.last_y;
|
shiftY = w.last_y;
|
||||||
if (w.computeSize) {
|
if (w.computeSize) {
|
||||||
shiftY += w.computeSize()[1] + 4;
|
shiftY += w.computeSize()[1] + 4;
|
||||||
} else {
|
}
|
||||||
|
else if(w.computedHeight) {
|
||||||
|
shiftY += w.computedHeight;
|
||||||
|
}
|
||||||
|
else {
|
||||||
shiftY += LiteGraph.NODE_WIDGET_HEIGHT + 4;
|
shiftY += LiteGraph.NODE_WIDGET_HEIGHT + 4;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -400,7 +411,7 @@ export class ComfyApp {
|
|||||||
this.images = output.images;
|
this.images = output.images;
|
||||||
imagesChanged = true;
|
imagesChanged = true;
|
||||||
imgURLs = imgURLs.concat(output.images.map(params => {
|
imgURLs = imgURLs.concat(output.images.map(params => {
|
||||||
return "/view?" + new URLSearchParams(params).toString() + app.getPreviewFormatParam();
|
return api.apiURL("/view?" + new URLSearchParams(params).toString() + app.getPreviewFormatParam());
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -656,11 +667,40 @@ export class ComfyApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a handler on paste that extracts and loads workflows from pasted JSON data
|
* Adds a handler on paste that extracts and loads images or workflows from pasted JSON data
|
||||||
*/
|
*/
|
||||||
#addPasteHandler() {
|
#addPasteHandler() {
|
||||||
document.addEventListener("paste", (e) => {
|
document.addEventListener("paste", (e) => {
|
||||||
let data = (e.clipboardData || window.clipboardData).getData("text/plain");
|
let data = (e.clipboardData || window.clipboardData);
|
||||||
|
const items = data.items;
|
||||||
|
|
||||||
|
// Look for image paste data
|
||||||
|
for (const item of items) {
|
||||||
|
if (item.type.startsWith('image/')) {
|
||||||
|
var imageNode = null;
|
||||||
|
|
||||||
|
// If an image node is selected, paste into it
|
||||||
|
if (this.canvas.current_node &&
|
||||||
|
this.canvas.current_node.is_selected &&
|
||||||
|
ComfyApp.isImageNode(this.canvas.current_node)) {
|
||||||
|
imageNode = this.canvas.current_node;
|
||||||
|
}
|
||||||
|
|
||||||
|
// No image node selected: add a new one
|
||||||
|
if (!imageNode) {
|
||||||
|
const newNode = LiteGraph.createNode("LoadImage");
|
||||||
|
newNode.pos = [...this.canvas.graph_mouse];
|
||||||
|
imageNode = this.graph.add(newNode);
|
||||||
|
this.graph.change();
|
||||||
|
}
|
||||||
|
const blob = item.getAsFile();
|
||||||
|
imageNode.pasteFile(blob);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// No image found. Look for node data
|
||||||
|
data = data.getData("text/plain");
|
||||||
let workflow;
|
let workflow;
|
||||||
try {
|
try {
|
||||||
data = data.slice(data.indexOf("{"));
|
data = data.slice(data.indexOf("{"));
|
||||||
@ -676,9 +716,41 @@ export class ComfyApp {
|
|||||||
if (workflow && workflow.version && workflow.nodes && workflow.extra) {
|
if (workflow && workflow.version && workflow.nodes && workflow.extra) {
|
||||||
this.loadGraphData(workflow);
|
this.loadGraphData(workflow);
|
||||||
}
|
}
|
||||||
|
else {
|
||||||
|
if (e.target.type === "text" || e.target.type === "textarea") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Litegraph default paste
|
||||||
|
this.canvas.pasteFromClipboard();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a handler on copy that serializes selected nodes to JSON
|
||||||
|
*/
|
||||||
|
#addCopyHandler() {
|
||||||
|
document.addEventListener("copy", (e) => {
|
||||||
|
if (e.target.type === "text" || e.target.type === "textarea") {
|
||||||
|
// Default system copy
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// copy nodes and clear clipboard
|
||||||
|
if (this.canvas.selected_nodes) {
|
||||||
|
this.canvas.copyToClipboard();
|
||||||
|
e.clipboardData.setData('text', ' '); //clearData doesn't remove images from clipboard
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopImmediatePropagation();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle mouse
|
* Handle mouse
|
||||||
*
|
*
|
||||||
@ -734,12 +806,6 @@ export class ComfyApp {
|
|||||||
const self = this;
|
const self = this;
|
||||||
const origProcessKey = LGraphCanvas.prototype.processKey;
|
const origProcessKey = LGraphCanvas.prototype.processKey;
|
||||||
LGraphCanvas.prototype.processKey = function(e) {
|
LGraphCanvas.prototype.processKey = function(e) {
|
||||||
const res = origProcessKey.apply(this, arguments);
|
|
||||||
|
|
||||||
if (res === false) {
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this.graph) {
|
if (!this.graph) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -750,9 +816,10 @@ export class ComfyApp {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (e.type == "keydown") {
|
if (e.type == "keydown" && !e.repeat) {
|
||||||
|
|
||||||
// Ctrl + M mute/unmute
|
// Ctrl + M mute/unmute
|
||||||
if (e.keyCode == 77 && e.ctrlKey) {
|
if (e.key === 'm' && e.ctrlKey) {
|
||||||
if (this.selected_nodes) {
|
if (this.selected_nodes) {
|
||||||
for (var i in this.selected_nodes) {
|
for (var i in this.selected_nodes) {
|
||||||
if (this.selected_nodes[i].mode === 2) { // never
|
if (this.selected_nodes[i].mode === 2) { // never
|
||||||
@ -764,6 +831,32 @@ export class ComfyApp {
|
|||||||
}
|
}
|
||||||
block_default = true;
|
block_default = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ctrl + B bypass
|
||||||
|
if (e.key === 'b' && e.ctrlKey) {
|
||||||
|
if (this.selected_nodes) {
|
||||||
|
for (var i in this.selected_nodes) {
|
||||||
|
if (this.selected_nodes[i].mode === 4) { // never
|
||||||
|
this.selected_nodes[i].mode = 0; // always
|
||||||
|
} else {
|
||||||
|
this.selected_nodes[i].mode = 4; // never
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
block_default = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ctrl+C Copy
|
||||||
|
if ((e.key === 'c') && (e.metaKey || e.ctrlKey)) {
|
||||||
|
// Trigger onCopy
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ctrl+V Paste
|
||||||
|
if ((e.key === 'v' || e.key == 'V') && (e.metaKey || e.ctrlKey)) {
|
||||||
|
// Trigger onPaste
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.graph.change();
|
this.graph.change();
|
||||||
@ -774,7 +867,8 @@ export class ComfyApp {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return res;
|
// Fall through to Litegraph defaults
|
||||||
|
return origProcessKey.apply(this, arguments);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -832,7 +926,7 @@ export class ComfyApp {
|
|||||||
LGraphCanvas.prototype.drawNodeShape = function (node, ctx, size, fgcolor, bgcolor, selected, mouse_over) {
|
LGraphCanvas.prototype.drawNodeShape = function (node, ctx, size, fgcolor, bgcolor, selected, mouse_over) {
|
||||||
const res = origDrawNodeShape.apply(this, arguments);
|
const res = origDrawNodeShape.apply(this, arguments);
|
||||||
|
|
||||||
const nodeErrors = self.lastPromptError?.node_errors[node.id];
|
const nodeErrors = self.lastNodeErrors?.[node.id];
|
||||||
|
|
||||||
let color = null;
|
let color = null;
|
||||||
let lineWidth = 1;
|
let lineWidth = 1;
|
||||||
@ -841,7 +935,7 @@ export class ComfyApp {
|
|||||||
} else if (self.dragOverNode && node.id === self.dragOverNode.id) {
|
} else if (self.dragOverNode && node.id === self.dragOverNode.id) {
|
||||||
color = "dodgerblue";
|
color = "dodgerblue";
|
||||||
}
|
}
|
||||||
else if (self.lastPromptError != null && nodeErrors?.errors) {
|
else if (nodeErrors?.errors) {
|
||||||
color = "red";
|
color = "red";
|
||||||
lineWidth = 2;
|
lineWidth = 2;
|
||||||
}
|
}
|
||||||
@ -910,14 +1004,21 @@ export class ComfyApp {
|
|||||||
const origDrawNode = LGraphCanvas.prototype.drawNode;
|
const origDrawNode = LGraphCanvas.prototype.drawNode;
|
||||||
LGraphCanvas.prototype.drawNode = function (node, ctx) {
|
LGraphCanvas.prototype.drawNode = function (node, ctx) {
|
||||||
var editor_alpha = this.editor_alpha;
|
var editor_alpha = this.editor_alpha;
|
||||||
|
var old_color = node.bgcolor;
|
||||||
|
|
||||||
if (node.mode === 2) { // never
|
if (node.mode === 2) { // never
|
||||||
this.editor_alpha = 0.4;
|
this.editor_alpha = 0.4;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (node.mode === 4) { // never
|
||||||
|
node.bgcolor = "#FF00FF";
|
||||||
|
this.editor_alpha = 0.2;
|
||||||
|
}
|
||||||
|
|
||||||
const res = origDrawNode.apply(this, arguments);
|
const res = origDrawNode.apply(this, arguments);
|
||||||
|
|
||||||
this.editor_alpha = editor_alpha;
|
this.editor_alpha = editor_alpha;
|
||||||
|
node.bgcolor = old_color;
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
};
|
};
|
||||||
@ -963,6 +1064,10 @@ export class ComfyApp {
|
|||||||
api.addEventListener("execution_start", ({ detail }) => {
|
api.addEventListener("execution_start", ({ detail }) => {
|
||||||
this.runningNodeId = null;
|
this.runningNodeId = null;
|
||||||
this.lastExecutionError = null
|
this.lastExecutionError = null
|
||||||
|
this.graph._nodes.forEach((node) => {
|
||||||
|
if (node.onExecutionStart)
|
||||||
|
node.onExecutionStart()
|
||||||
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
api.addEventListener("execution_error", ({ detail }) => {
|
api.addEventListener("execution_error", ({ detail }) => {
|
||||||
@ -995,17 +1100,21 @@ export class ComfyApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads all extensions from the API into the window
|
* Loads all extensions from the API into the window in parallel
|
||||||
*/
|
*/
|
||||||
async #loadExtensions() {
|
async #loadExtensions() {
|
||||||
const extensions = await api.getExtensions();
|
const extensions = await api.getExtensions();
|
||||||
for (const ext of extensions) {
|
this.logging.addEntry("Comfy.App", "debug", { Extensions: extensions });
|
||||||
try {
|
|
||||||
await import(ext);
|
const extensionPromises = extensions.map(async ext => {
|
||||||
} catch (error) {
|
try {
|
||||||
console.error("Error loading extension", ext, error);
|
await import(api.apiURL(ext));
|
||||||
}
|
} catch (error) {
|
||||||
}
|
console.error("Error loading extension", ext, error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await Promise.all(extensionPromises);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -1034,8 +1143,12 @@ export class ComfyApp {
|
|||||||
this.graph.start();
|
this.graph.start();
|
||||||
|
|
||||||
function resizeCanvas() {
|
function resizeCanvas() {
|
||||||
canvasEl.width = canvasEl.offsetWidth;
|
// Limit minimal scale to 1, see https://github.com/comfyanonymous/ComfyUI/pull/845
|
||||||
canvasEl.height = canvasEl.offsetHeight;
|
const scale = Math.max(window.devicePixelRatio, 1);
|
||||||
|
const { width, height } = canvasEl.getBoundingClientRect();
|
||||||
|
canvasEl.width = Math.round(width * scale);
|
||||||
|
canvasEl.height = Math.round(height * scale);
|
||||||
|
canvasEl.getContext("2d").scale(scale, scale);
|
||||||
canvas.draw(true, true);
|
canvas.draw(true, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1071,6 +1184,7 @@ export class ComfyApp {
|
|||||||
this.#addDrawGroupsHandler();
|
this.#addDrawGroupsHandler();
|
||||||
this.#addApiUpdateHandlers();
|
this.#addApiUpdateHandlers();
|
||||||
this.#addDropHandler();
|
this.#addDropHandler();
|
||||||
|
this.#addCopyHandler();
|
||||||
this.#addPasteHandler();
|
this.#addPasteHandler();
|
||||||
this.#addKeyboardHandler();
|
this.#addKeyboardHandler();
|
||||||
|
|
||||||
@ -1112,22 +1226,29 @@ export class ComfyApp {
|
|||||||
const inputData = inputs[inputName];
|
const inputData = inputs[inputName];
|
||||||
const type = inputData[0];
|
const type = inputData[0];
|
||||||
|
|
||||||
if(inputData[1]?.forceInput) {
|
let widgetCreated = true;
|
||||||
this.addInput(inputName, type);
|
if (Array.isArray(type)) {
|
||||||
|
// Enums
|
||||||
|
Object.assign(config, widgets.COMBO(this, inputName, inputData, app) || {});
|
||||||
|
} else if (`${type}:${inputName}` in widgets) {
|
||||||
|
// Support custom widgets by Type:Name
|
||||||
|
Object.assign(config, widgets[`${type}:${inputName}`](this, inputName, inputData, app) || {});
|
||||||
|
} else if (type in widgets) {
|
||||||
|
// Standard type widgets
|
||||||
|
Object.assign(config, widgets[type](this, inputName, inputData, app) || {});
|
||||||
} else {
|
} else {
|
||||||
if (Array.isArray(type)) {
|
// Node connection inputs
|
||||||
// Enums
|
this.addInput(inputName, type);
|
||||||
Object.assign(config, widgets.COMBO(this, inputName, inputData, app) || {});
|
widgetCreated = false;
|
||||||
} else if (`${type}:${inputName}` in widgets) {
|
}
|
||||||
// Support custom widgets by Type:Name
|
|
||||||
Object.assign(config, widgets[`${type}:${inputName}`](this, inputName, inputData, app) || {});
|
if(widgetCreated && inputData[1]?.forceInput && config?.widget) {
|
||||||
} else if (type in widgets) {
|
if (!config.widget.options) config.widget.options = {};
|
||||||
// Standard type widgets
|
config.widget.options.forceInput = inputData[1].forceInput;
|
||||||
Object.assign(config, widgets[type](this, inputName, inputData, app) || {});
|
}
|
||||||
} else {
|
if(widgetCreated && inputData[1]?.defaultInput && config?.widget) {
|
||||||
// Node connection inputs
|
if (!config.widget.options) config.widget.options = {};
|
||||||
this.addInput(inputName, type);
|
config.widget.options.defaultInput = inputData[1].defaultInput;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1278,6 +1399,9 @@ export class ComfyApp {
|
|||||||
(t) => `<li>${t}</li>`
|
(t) => `<li>${t}</li>`
|
||||||
).join("")}</ul>Nodes that have failed to load will show as red on the graph.`
|
).join("")}</ul>Nodes that have failed to load will show as red on the graph.`
|
||||||
);
|
);
|
||||||
|
this.logging.addEntry("Comfy.App", "warn", {
|
||||||
|
MissingNodes: missingNodeTypes,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1300,7 +1424,7 @@ export class ComfyApp {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (node.mode === 2) {
|
if (node.mode === 2 || node.mode === 4) {
|
||||||
// Don't serialize muted nodes
|
// Don't serialize muted nodes
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -1323,12 +1447,36 @@ export class ComfyApp {
|
|||||||
let parent = node.getInputNode(i);
|
let parent = node.getInputNode(i);
|
||||||
if (parent) {
|
if (parent) {
|
||||||
let link = node.getInputLink(i);
|
let link = node.getInputLink(i);
|
||||||
while (parent && parent.isVirtualNode) {
|
while (parent.mode === 4 || parent.isVirtualNode) {
|
||||||
link = parent.getInputLink(link.origin_slot);
|
let found = false;
|
||||||
if (link) {
|
if (parent.isVirtualNode) {
|
||||||
parent = parent.getInputNode(link.origin_slot);
|
link = parent.getInputLink(link.origin_slot);
|
||||||
} else {
|
if (link) {
|
||||||
parent = null;
|
parent = parent.getInputNode(link.target_slot);
|
||||||
|
if (parent) {
|
||||||
|
found = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (link && parent.mode === 4) {
|
||||||
|
let all_inputs = [link.origin_slot];
|
||||||
|
if (parent.inputs) {
|
||||||
|
all_inputs = all_inputs.concat(Object.keys(parent.inputs))
|
||||||
|
for (let parent_input in all_inputs) {
|
||||||
|
parent_input = all_inputs[parent_input];
|
||||||
|
if (parent.inputs[parent_input].type === node.inputs[i].type) {
|
||||||
|
link = parent.getInputLink(parent_input);
|
||||||
|
if (link) {
|
||||||
|
parent = parent.getInputNode(parent_input);
|
||||||
|
}
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!found) {
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1405,7 +1553,7 @@ export class ComfyApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.#processingQueue = true;
|
this.#processingQueue = true;
|
||||||
this.lastPromptError = null;
|
this.lastNodeErrors = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
while (this.#queueItems.length) {
|
while (this.#queueItems.length) {
|
||||||
@ -1415,12 +1563,16 @@ export class ComfyApp {
|
|||||||
const p = await this.graphToPrompt();
|
const p = await this.graphToPrompt();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.queuePrompt(number, p);
|
const res = await api.queuePrompt(number, p);
|
||||||
|
this.lastNodeErrors = res.node_errors;
|
||||||
|
if (this.lastNodeErrors.length > 0) {
|
||||||
|
this.canvas.draw(true, true);
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const formattedError = this.#formatPromptError(error)
|
const formattedError = this.#formatPromptError(error)
|
||||||
this.ui.dialog.show(formattedError);
|
this.ui.dialog.show(formattedError);
|
||||||
if (error.response) {
|
if (error.response) {
|
||||||
this.lastPromptError = error.response;
|
this.lastNodeErrors = error.response.node_errors;
|
||||||
this.canvas.draw(true, true);
|
this.canvas.draw(true, true);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@ -1526,7 +1678,7 @@ export class ComfyApp {
|
|||||||
clean() {
|
clean() {
|
||||||
this.nodeOutputs = {};
|
this.nodeOutputs = {};
|
||||||
this.nodePreviewImages = {}
|
this.nodePreviewImages = {}
|
||||||
this.lastPromptError = null;
|
this.lastNodeErrors = null;
|
||||||
this.lastExecutionError = null;
|
this.lastExecutionError = null;
|
||||||
this.runningNodeId = null;
|
this.runningNodeId = null;
|
||||||
}
|
}
|
||||||
|
|||||||
367
web/scripts/logging.js
Normal file
367
web/scripts/logging.js
Normal file
@ -0,0 +1,367 @@
|
|||||||
|
import { $el, ComfyDialog } from "./ui.js";
|
||||||
|
import { api } from "./api.js";
|
||||||
|
|
||||||
|
$el("style", {
|
||||||
|
textContent: `
|
||||||
|
.comfy-logging-logs {
|
||||||
|
display: grid;
|
||||||
|
color: var(--fg-color);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
.comfy-logging-log {
|
||||||
|
display: contents;
|
||||||
|
}
|
||||||
|
.comfy-logging-title {
|
||||||
|
background: var(--tr-even-bg-color);
|
||||||
|
font-weight: bold;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.comfy-logging-log div {
|
||||||
|
background: var(--row-bg);
|
||||||
|
padding: 5px;
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
parent: document.body,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Stringify function supporting max depth and removal of circular references
|
||||||
|
// https://stackoverflow.com/a/57193345
|
||||||
|
function stringify(val, depth, replacer, space, onGetObjID) {
|
||||||
|
depth = isNaN(+depth) ? 1 : depth;
|
||||||
|
var recursMap = new WeakMap();
|
||||||
|
function _build(val, depth, o, a, r) {
|
||||||
|
// (JSON.stringify() has it's own rules, which we respect here by using it for property iteration)
|
||||||
|
return !val || typeof val != "object"
|
||||||
|
? val
|
||||||
|
: ((r = recursMap.has(val)),
|
||||||
|
recursMap.set(val, true),
|
||||||
|
(a = Array.isArray(val)),
|
||||||
|
r
|
||||||
|
? (o = (onGetObjID && onGetObjID(val)) || null)
|
||||||
|
: JSON.stringify(val, function (k, v) {
|
||||||
|
if (a || depth > 0) {
|
||||||
|
if (replacer) v = replacer(k, v);
|
||||||
|
if (!k) return (a = Array.isArray(v)), (val = v);
|
||||||
|
!o && (o = a ? [] : {});
|
||||||
|
o[k] = _build(v, a ? depth : depth - 1);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
o === void 0 ? (a ? [] : {}) : o);
|
||||||
|
}
|
||||||
|
return JSON.stringify(_build(val, depth), null, space);
|
||||||
|
}
|
||||||
|
|
||||||
|
const jsonReplacer = (k, v, ui) => {
|
||||||
|
if (v instanceof Array && v.length === 1) {
|
||||||
|
v = v[0];
|
||||||
|
}
|
||||||
|
if (v instanceof Date) {
|
||||||
|
v = v.toISOString();
|
||||||
|
if (ui) {
|
||||||
|
v = v.split("T")[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (v instanceof Error) {
|
||||||
|
let err = "";
|
||||||
|
if (v.name) err += v.name + "\n";
|
||||||
|
if (v.message) err += v.message + "\n";
|
||||||
|
if (v.stack) err += v.stack + "\n";
|
||||||
|
if (!err) {
|
||||||
|
err = v.toString();
|
||||||
|
}
|
||||||
|
v = err;
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
};
|
||||||
|
|
||||||
|
const fileInput = $el("input", {
|
||||||
|
type: "file",
|
||||||
|
accept: ".json",
|
||||||
|
style: { display: "none" },
|
||||||
|
parent: document.body,
|
||||||
|
});
|
||||||
|
|
||||||
|
class ComfyLoggingDialog extends ComfyDialog {
|
||||||
|
constructor(logging) {
|
||||||
|
super();
|
||||||
|
this.logging = logging;
|
||||||
|
}
|
||||||
|
|
||||||
|
clear() {
|
||||||
|
this.logging.clear();
|
||||||
|
this.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
export() {
|
||||||
|
const blob = new Blob([stringify([...this.logging.entries], 20, jsonReplacer, "\t")], {
|
||||||
|
type: "application/json",
|
||||||
|
});
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = $el("a", {
|
||||||
|
href: url,
|
||||||
|
download: `comfyui-logs-${Date.now()}.json`,
|
||||||
|
style: { display: "none" },
|
||||||
|
parent: document.body,
|
||||||
|
});
|
||||||
|
a.click();
|
||||||
|
setTimeout(function () {
|
||||||
|
a.remove();
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
import() {
|
||||||
|
fileInput.onchange = () => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => {
|
||||||
|
fileInput.remove();
|
||||||
|
try {
|
||||||
|
const obj = JSON.parse(reader.result);
|
||||||
|
if (obj instanceof Array) {
|
||||||
|
this.show(obj);
|
||||||
|
} else {
|
||||||
|
throw new Error("Invalid file selected.");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
alert("Unable to load logs: " + error.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsText(fileInput.files[0]);
|
||||||
|
};
|
||||||
|
fileInput.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
createButtons() {
|
||||||
|
return [
|
||||||
|
$el("button", {
|
||||||
|
type: "button",
|
||||||
|
textContent: "Clear",
|
||||||
|
onclick: () => this.clear(),
|
||||||
|
}),
|
||||||
|
$el("button", {
|
||||||
|
type: "button",
|
||||||
|
textContent: "Export logs...",
|
||||||
|
onclick: () => this.export(),
|
||||||
|
}),
|
||||||
|
$el("button", {
|
||||||
|
type: "button",
|
||||||
|
textContent: "View exported logs...",
|
||||||
|
onclick: () => this.import(),
|
||||||
|
}),
|
||||||
|
...super.createButtons(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
getTypeColor(type) {
|
||||||
|
switch (type) {
|
||||||
|
case "error":
|
||||||
|
return "red";
|
||||||
|
case "warn":
|
||||||
|
return "orange";
|
||||||
|
case "debug":
|
||||||
|
return "dodgerblue";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
show(entries) {
|
||||||
|
if (!entries) entries = this.logging.entries;
|
||||||
|
this.element.style.width = "100%";
|
||||||
|
const cols = {
|
||||||
|
source: "Source",
|
||||||
|
type: "Type",
|
||||||
|
timestamp: "Timestamp",
|
||||||
|
message: "Message",
|
||||||
|
};
|
||||||
|
const keys = Object.keys(cols);
|
||||||
|
const headers = Object.values(cols).map((title) =>
|
||||||
|
$el("div.comfy-logging-title", {
|
||||||
|
textContent: title,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const rows = entries.map((entry, i) => {
|
||||||
|
return $el(
|
||||||
|
"div.comfy-logging-log",
|
||||||
|
{
|
||||||
|
$: (el) => el.style.setProperty("--row-bg", `var(--tr-${i % 2 ? "even" : "odd"}-bg-color)`),
|
||||||
|
},
|
||||||
|
keys.map((key) => {
|
||||||
|
let v = entry[key];
|
||||||
|
let color;
|
||||||
|
if (key === "type") {
|
||||||
|
color = this.getTypeColor(v);
|
||||||
|
} else {
|
||||||
|
v = jsonReplacer(key, v, true);
|
||||||
|
|
||||||
|
if (typeof v === "object") {
|
||||||
|
v = stringify(v, 5, jsonReplacer, " ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $el("div", {
|
||||||
|
style: {
|
||||||
|
color,
|
||||||
|
},
|
||||||
|
textContent: v,
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const grid = $el(
|
||||||
|
"div.comfy-logging-logs",
|
||||||
|
{
|
||||||
|
style: {
|
||||||
|
gridTemplateColumns: `repeat(${headers.length}, 1fr)`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[...headers, ...rows]
|
||||||
|
);
|
||||||
|
const els = [grid];
|
||||||
|
if (!this.logging.enabled) {
|
||||||
|
els.unshift(
|
||||||
|
$el("h3", {
|
||||||
|
style: { textAlign: "center" },
|
||||||
|
textContent: "Logging is disabled",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
super.show($el("div", els));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ComfyLogging {
|
||||||
|
/**
|
||||||
|
* @type Array<{ source: string, type: string, timestamp: Date, message: any }>
|
||||||
|
*/
|
||||||
|
entries = [];
|
||||||
|
|
||||||
|
#enabled;
|
||||||
|
#console = {};
|
||||||
|
|
||||||
|
get enabled() {
|
||||||
|
return this.#enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
set enabled(value) {
|
||||||
|
if (value === this.#enabled) return;
|
||||||
|
if (value) {
|
||||||
|
this.patchConsole();
|
||||||
|
} else {
|
||||||
|
this.unpatchConsole();
|
||||||
|
}
|
||||||
|
this.#enabled = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(app) {
|
||||||
|
this.app = app;
|
||||||
|
|
||||||
|
this.dialog = new ComfyLoggingDialog(this);
|
||||||
|
this.addSetting();
|
||||||
|
this.catchUnhandled();
|
||||||
|
this.addInitData();
|
||||||
|
}
|
||||||
|
|
||||||
|
addSetting() {
|
||||||
|
const settingId = "Comfy.Logging.Enabled";
|
||||||
|
const htmlSettingId = settingId.replaceAll(".", "-");
|
||||||
|
const setting = this.app.ui.settings.addSetting({
|
||||||
|
id: settingId,
|
||||||
|
name: settingId,
|
||||||
|
defaultValue: true,
|
||||||
|
type: (name, setter, value) => {
|
||||||
|
return $el("tr", [
|
||||||
|
$el("td", [
|
||||||
|
$el("label", {
|
||||||
|
textContent: "Logging",
|
||||||
|
for: htmlSettingId,
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
$el("td", [
|
||||||
|
$el("input", {
|
||||||
|
id: htmlSettingId,
|
||||||
|
type: "checkbox",
|
||||||
|
checked: value,
|
||||||
|
onchange: (event) => {
|
||||||
|
setter((this.enabled = event.target.checked));
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
$el("button", {
|
||||||
|
textContent: "View Logs",
|
||||||
|
onclick: () => {
|
||||||
|
this.app.ui.settings.element.close();
|
||||||
|
this.dialog.show();
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
fontSize: "14px",
|
||||||
|
display: "block",
|
||||||
|
marginTop: "5px",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.enabled = setting.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
patchConsole() {
|
||||||
|
// Capture common console outputs
|
||||||
|
const self = this;
|
||||||
|
for (const type of ["log", "warn", "error", "debug"]) {
|
||||||
|
const orig = console[type];
|
||||||
|
this.#console[type] = orig;
|
||||||
|
console[type] = function () {
|
||||||
|
orig.apply(console, arguments);
|
||||||
|
self.addEntry("console", type, ...arguments);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unpatchConsole() {
|
||||||
|
// Restore original console functions
|
||||||
|
for (const type of Object.keys(this.#console)) {
|
||||||
|
console[type] = this.#console[type];
|
||||||
|
}
|
||||||
|
this.#console = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
catchUnhandled() {
|
||||||
|
// Capture uncaught errors
|
||||||
|
window.addEventListener("error", (e) => {
|
||||||
|
this.addEntry("window", "error", e.error ?? "Unknown error");
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener("unhandledrejection", (e) => {
|
||||||
|
this.addEntry("unhandledrejection", "error", e.reason ?? "Unknown error");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
clear() {
|
||||||
|
this.entries = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
addEntry(source, type, ...args) {
|
||||||
|
if (this.enabled) {
|
||||||
|
this.entries.push({
|
||||||
|
source,
|
||||||
|
type,
|
||||||
|
timestamp: new Date(),
|
||||||
|
message: args,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log(source, ...args) {
|
||||||
|
this.addEntry(source, "log", ...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
async addInitData() {
|
||||||
|
if (!this.enabled) return;
|
||||||
|
const source = "ComfyUI.Logging";
|
||||||
|
this.addEntry(source, "debug", { UserAgent: navigator.userAgent });
|
||||||
|
const systemStats = await api.getSystemStats();
|
||||||
|
this.addEntry(source, "debug", systemStats);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -234,7 +234,7 @@ class ComfySettingsDialog extends ComfyDialog {
|
|||||||
localStorage[settingId] = JSON.stringify(value);
|
localStorage[settingId] = JSON.stringify(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
addSetting({id, name, type, defaultValue, onChange, attrs = {}, tooltip = "",}) {
|
addSetting({id, name, type, defaultValue, onChange, attrs = {}, tooltip = "", options = undefined}) {
|
||||||
if (!id) {
|
if (!id) {
|
||||||
throw new Error("Settings must have an ID");
|
throw new Error("Settings must have an ID");
|
||||||
}
|
}
|
||||||
@ -347,6 +347,32 @@ class ComfySettingsDialog extends ComfyDialog {
|
|||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
break;
|
break;
|
||||||
|
case "combo":
|
||||||
|
element = $el("tr", [
|
||||||
|
labelCell,
|
||||||
|
$el("td", [
|
||||||
|
$el(
|
||||||
|
"select",
|
||||||
|
{
|
||||||
|
oninput: (e) => {
|
||||||
|
setter(e.target.value);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
(typeof options === "function" ? options(value) : options || []).map((opt) => {
|
||||||
|
if (typeof opt === "string") {
|
||||||
|
opt = { text: opt };
|
||||||
|
}
|
||||||
|
const v = opt.value ?? opt.text;
|
||||||
|
return $el("option", {
|
||||||
|
value: v,
|
||||||
|
textContent: opt.text,
|
||||||
|
selected: value + "" === v + "",
|
||||||
|
});
|
||||||
|
})
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
break;
|
||||||
case "text":
|
case "text":
|
||||||
default:
|
default:
|
||||||
if (type !== "text") {
|
if (type !== "text") {
|
||||||
@ -405,10 +431,12 @@ class ComfySettingsDialog extends ComfyDialog {
|
|||||||
class ComfyList {
|
class ComfyList {
|
||||||
#type;
|
#type;
|
||||||
#text;
|
#text;
|
||||||
|
#reverse;
|
||||||
|
|
||||||
constructor(text, type) {
|
constructor(text, type, reverse) {
|
||||||
this.#text = text;
|
this.#text = text;
|
||||||
this.#type = type || text.toLowerCase();
|
this.#type = type || text.toLowerCase();
|
||||||
|
this.#reverse = reverse || false;
|
||||||
this.element = $el("div.comfy-list");
|
this.element = $el("div.comfy-list");
|
||||||
this.element.style.display = "none";
|
this.element.style.display = "none";
|
||||||
}
|
}
|
||||||
@ -425,7 +453,7 @@ class ComfyList {
|
|||||||
textContent: section,
|
textContent: section,
|
||||||
}),
|
}),
|
||||||
$el("div.comfy-list-items", [
|
$el("div.comfy-list-items", [
|
||||||
...items[section].map((item) => {
|
...(this.#reverse ? items[section].reverse() : items[section]).map((item) => {
|
||||||
// Allow items to specify a custom remove action (e.g. for interrupt current prompt)
|
// Allow items to specify a custom remove action (e.g. for interrupt current prompt)
|
||||||
const removeAction = item.remove || {
|
const removeAction = item.remove || {
|
||||||
name: "Delete",
|
name: "Delete",
|
||||||
@ -480,7 +508,7 @@ class ComfyList {
|
|||||||
|
|
||||||
hide() {
|
hide() {
|
||||||
this.element.style.display = "none";
|
this.element.style.display = "none";
|
||||||
this.button.textContent = "See " + this.#text;
|
this.button.textContent = "View " + this.#text;
|
||||||
}
|
}
|
||||||
|
|
||||||
toggle() {
|
toggle() {
|
||||||
@ -503,7 +531,7 @@ export class ComfyUI {
|
|||||||
this.batchCount = 1;
|
this.batchCount = 1;
|
||||||
this.lastQueueSize = 0;
|
this.lastQueueSize = 0;
|
||||||
this.queue = new ComfyList("Queue");
|
this.queue = new ComfyList("Queue");
|
||||||
this.history = new ComfyList("History");
|
this.history = new ComfyList("History", "history", true);
|
||||||
|
|
||||||
api.addEventListener("status", () => {
|
api.addEventListener("status", () => {
|
||||||
this.queue.update();
|
this.queue.update();
|
||||||
@ -542,6 +570,13 @@ export class ComfyUI {
|
|||||||
defaultValue: "",
|
defaultValue: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.settings.addSetting({
|
||||||
|
id: "Comfy.DisableSliders",
|
||||||
|
name: "Disable sliders.",
|
||||||
|
type: "boolean",
|
||||||
|
defaultValue: false,
|
||||||
|
});
|
||||||
|
|
||||||
const fileInput = $el("input", {
|
const fileInput = $el("input", {
|
||||||
id: "comfy-file-input",
|
id: "comfy-file-input",
|
||||||
type: "file",
|
type: "file",
|
||||||
@ -584,7 +619,9 @@ export class ComfyUI {
|
|||||||
]),
|
]),
|
||||||
]),
|
]),
|
||||||
$el("div", {id: "extraOptions", style: {width: "100%", display: "none"}}, [
|
$el("div", {id: "extraOptions", style: {width: "100%", display: "none"}}, [
|
||||||
$el("label", {innerHTML: "Batch count"}, [
|
$el("div",[
|
||||||
|
|
||||||
|
$el("label", {innerHTML: "Batch count"}),
|
||||||
$el("input", {
|
$el("input", {
|
||||||
id: "batchCountInputNumber",
|
id: "batchCountInputNumber",
|
||||||
type: "number",
|
type: "number",
|
||||||
@ -607,13 +644,22 @@ export class ComfyUI {
|
|||||||
document.getElementById("batchCountInputNumber").value = i.srcElement.value;
|
document.getElementById("batchCountInputNumber").value = i.srcElement.value;
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
]),
|
||||||
|
|
||||||
|
$el("div",[
|
||||||
|
$el("label",{
|
||||||
|
for:"autoQueueCheckbox",
|
||||||
|
innerHTML: "Auto Queue"
|
||||||
|
// textContent: "Auto Queue"
|
||||||
|
}),
|
||||||
$el("input", {
|
$el("input", {
|
||||||
id: "autoQueueCheckbox",
|
id: "autoQueueCheckbox",
|
||||||
type: "checkbox",
|
type: "checkbox",
|
||||||
checked: false,
|
checked: false,
|
||||||
title: "automatically queue prompt when the queue size hits 0",
|
title: "Automatically queue prompt when the queue size hits 0",
|
||||||
|
|
||||||
}),
|
}),
|
||||||
]),
|
])
|
||||||
]),
|
]),
|
||||||
$el("div.comfy-menu-btns", [
|
$el("div.comfy-menu-btns", [
|
||||||
$el("button", {
|
$el("button", {
|
||||||
@ -670,6 +716,37 @@ export class ComfyUI {
|
|||||||
}, 0);
|
}, 0);
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
$el("button", {
|
||||||
|
id: "comfy-dev-save-api-button",
|
||||||
|
textContent: "Save (API Format)",
|
||||||
|
style: {width: "100%", display: "none"},
|
||||||
|
onclick: () => {
|
||||||
|
let filename = "workflow_api.json";
|
||||||
|
if (promptFilename.value) {
|
||||||
|
filename = prompt("Save workflow (API) as:", filename);
|
||||||
|
if (!filename) return;
|
||||||
|
if (!filename.toLowerCase().endsWith(".json")) {
|
||||||
|
filename += ".json";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
app.graphToPrompt().then(p=>{
|
||||||
|
const json = JSON.stringify(p.output, null, 2); // convert the data to a JSON string
|
||||||
|
const blob = new Blob([json], {type: "application/json"});
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = $el("a", {
|
||||||
|
href: url,
|
||||||
|
download: filename,
|
||||||
|
style: {display: "none"},
|
||||||
|
parent: document.body,
|
||||||
|
});
|
||||||
|
a.click();
|
||||||
|
setTimeout(function () {
|
||||||
|
a.remove();
|
||||||
|
window.URL.revokeObjectURL(url);
|
||||||
|
}, 0);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}),
|
||||||
$el("button", {id: "comfy-load-button", textContent: "Load", onclick: () => fileInput.click()}),
|
$el("button", {id: "comfy-load-button", textContent: "Load", onclick: () => fileInput.click()}),
|
||||||
$el("button", {
|
$el("button", {
|
||||||
id: "comfy-refresh-button",
|
id: "comfy-refresh-button",
|
||||||
@ -694,6 +771,14 @@ export class ComfyUI {
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const devMode = this.settings.addSetting({
|
||||||
|
id: "Comfy.DevMode",
|
||||||
|
name: "Enable Dev mode Options",
|
||||||
|
type: "boolean",
|
||||||
|
defaultValue: false,
|
||||||
|
onChange: function(value) { document.getElementById("comfy-dev-save-api-button").style.display = value ? "block" : "none"},
|
||||||
|
});
|
||||||
|
|
||||||
dragElement(this.menuContainer, this.settings);
|
dragElement(this.menuContainer, this.settings);
|
||||||
|
|
||||||
this.setStatus({exec_info: {queue_remaining: "X"}});
|
this.setStatus({exec_info: {queue_remaining: "X"}});
|
||||||
|
|||||||
@ -1,3 +1,5 @@
|
|||||||
|
import { api } from "./api.js"
|
||||||
|
|
||||||
function getNumberDefaults(inputData, defaultStep) {
|
function getNumberDefaults(inputData, defaultStep) {
|
||||||
let defaultVal = inputData[1]["default"];
|
let defaultVal = inputData[1]["default"];
|
||||||
let { min, max, step } = inputData[1];
|
let { min, max, step } = inputData[1];
|
||||||
@ -6,8 +8,13 @@ function getNumberDefaults(inputData, defaultStep) {
|
|||||||
if (min == undefined) min = 0;
|
if (min == undefined) min = 0;
|
||||||
if (max == undefined) max = 2048;
|
if (max == undefined) max = 2048;
|
||||||
if (step == undefined) step = defaultStep;
|
if (step == undefined) step = defaultStep;
|
||||||
|
// precision is the number of decimal places to show.
|
||||||
|
// by default, display the the smallest number of decimal places such that changes of size step are visible.
|
||||||
|
let precision = Math.max(-Math.floor(Math.log10(step)),0)
|
||||||
|
// by default, round the value to those decimal places shown.
|
||||||
|
let round = Math.round(1000000*Math.pow(0.1,precision))/1000000;
|
||||||
|
|
||||||
return { val: defaultVal, config: { min, max, step: 10.0 * step } };
|
return { val: defaultVal, config: { min, max, step: 10.0 * step, round, precision } };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function addValueControlWidget(node, targetWidget, defaultValue = "randomize", values) {
|
export function addValueControlWidget(node, targetWidget, defaultValue = "randomize", values) {
|
||||||
@ -77,8 +84,8 @@ export function addValueControlWidget(node, targetWidget, defaultValue = "random
|
|||||||
return valueControl;
|
return valueControl;
|
||||||
};
|
};
|
||||||
|
|
||||||
function seedWidget(node, inputName, inputData) {
|
function seedWidget(node, inputName, inputData, app) {
|
||||||
const seed = ComfyWidgets.INT(node, inputName, inputData);
|
const seed = ComfyWidgets.INT(node, inputName, inputData, app);
|
||||||
const seedControl = addValueControlWidget(node, seed.widget, "randomize");
|
const seedControl = addValueControlWidget(node, seed.widget, "randomize");
|
||||||
|
|
||||||
seed.widget.linkedWidgets = [seedControl];
|
seed.widget.linkedWidgets = [seedControl];
|
||||||
@ -129,6 +136,7 @@ function addMultilineWidget(node, name, opts, app) {
|
|||||||
w.y = y;
|
w.y = y;
|
||||||
if (w.type === "customtext") {
|
if (w.type === "customtext") {
|
||||||
y += freeSpace;
|
y += freeSpace;
|
||||||
|
w.computedHeight = freeSpace - multi.length*4;
|
||||||
} else if (w.computeSize) {
|
} else if (w.computeSize) {
|
||||||
y += w.computeSize()[1] + 4;
|
y += w.computeSize()[1] + 4;
|
||||||
} else {
|
} else {
|
||||||
@ -162,11 +170,12 @@ function addMultilineWidget(node, name, opts, app) {
|
|||||||
.multiplySelf(ctx.getTransform())
|
.multiplySelf(ctx.getTransform())
|
||||||
.translateSelf(margin, margin + y);
|
.translateSelf(margin, margin + y);
|
||||||
|
|
||||||
|
const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)
|
||||||
Object.assign(this.inputEl.style, {
|
Object.assign(this.inputEl.style, {
|
||||||
transformOrigin: "0 0",
|
transformOrigin: "0 0",
|
||||||
transform: transform,
|
transform: scale,
|
||||||
left: "0px",
|
left: `${transform.a + transform.e}px`,
|
||||||
top: "0px",
|
top: `${transform.d + transform.f}px`,
|
||||||
width: `${widgetWidth - (margin * 2)}px`,
|
width: `${widgetWidth - (margin * 2)}px`,
|
||||||
height: `${this.parent.inputHeight - (margin * 2)}px`,
|
height: `${this.parent.inputHeight - (margin * 2)}px`,
|
||||||
position: "absolute",
|
position: "absolute",
|
||||||
@ -246,19 +255,32 @@ function addMultilineWidget(node, name, opts, app) {
|
|||||||
return { minWidth: 400, minHeight: 200, widget };
|
return { minWidth: 400, minHeight: 200, widget };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isSlider(display, app) {
|
||||||
|
if (app.ui.settings.getSettingValue("Comfy.DisableSliders")) {
|
||||||
|
return "number"
|
||||||
|
}
|
||||||
|
|
||||||
|
return (display==="slider") ? "slider" : "number"
|
||||||
|
}
|
||||||
|
|
||||||
export const ComfyWidgets = {
|
export const ComfyWidgets = {
|
||||||
"INT:seed": seedWidget,
|
"INT:seed": seedWidget,
|
||||||
"INT:noise_seed": seedWidget,
|
"INT:noise_seed": seedWidget,
|
||||||
FLOAT(node, inputName, inputData) {
|
FLOAT(node, inputName, inputData, app) {
|
||||||
|
let widgetType = isSlider(inputData[1]["display"], app);
|
||||||
const { val, config } = getNumberDefaults(inputData, 0.5);
|
const { val, config } = getNumberDefaults(inputData, 0.5);
|
||||||
return { widget: node.addWidget("number", inputName, val, () => {}, config) };
|
return { widget: node.addWidget(widgetType, inputName, val,
|
||||||
|
function (v) {
|
||||||
|
this.value = Math.round(v/config.round)*config.round;
|
||||||
|
}, config) };
|
||||||
},
|
},
|
||||||
INT(node, inputName, inputData) {
|
INT(node, inputName, inputData, app) {
|
||||||
|
let widgetType = isSlider(inputData[1]["display"], app);
|
||||||
const { val, config } = getNumberDefaults(inputData, 1);
|
const { val, config } = getNumberDefaults(inputData, 1);
|
||||||
Object.assign(config, { precision: 0 });
|
Object.assign(config, { precision: 0 });
|
||||||
return {
|
return {
|
||||||
widget: node.addWidget(
|
widget: node.addWidget(
|
||||||
"number",
|
widgetType,
|
||||||
inputName,
|
inputName,
|
||||||
val,
|
val,
|
||||||
function (v) {
|
function (v) {
|
||||||
@ -269,15 +291,33 @@ export const ComfyWidgets = {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
BOOLEAN(node, inputName, inputData) {
|
||||||
|
let defaultVal = inputData[1]["default"];
|
||||||
|
return {
|
||||||
|
widget: node.addWidget(
|
||||||
|
"toggle",
|
||||||
|
inputName,
|
||||||
|
defaultVal,
|
||||||
|
() => {},
|
||||||
|
{"on": inputData[1].label_on, "off": inputData[1].label_off}
|
||||||
|
)
|
||||||
|
};
|
||||||
|
},
|
||||||
STRING(node, inputName, inputData, app) {
|
STRING(node, inputName, inputData, app) {
|
||||||
const defaultVal = inputData[1].default || "";
|
const defaultVal = inputData[1].default || "";
|
||||||
const multiline = !!inputData[1].multiline;
|
const multiline = !!inputData[1].multiline;
|
||||||
|
|
||||||
|
let res;
|
||||||
if (multiline) {
|
if (multiline) {
|
||||||
return addMultilineWidget(node, inputName, { defaultVal, ...inputData[1] }, app);
|
res = addMultilineWidget(node, inputName, { defaultVal, ...inputData[1] }, app);
|
||||||
} else {
|
} else {
|
||||||
return { widget: node.addWidget("text", inputName, defaultVal, () => {}, {}) };
|
res = { widget: node.addWidget("text", inputName, defaultVal, () => {}, {}) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(inputData[1].dynamicPrompts != undefined)
|
||||||
|
res.widget.dynamicPrompts = inputData[1].dynamicPrompts;
|
||||||
|
|
||||||
|
return res;
|
||||||
},
|
},
|
||||||
COMBO(node, inputName, inputData) {
|
COMBO(node, inputName, inputData) {
|
||||||
const type = inputData[0];
|
const type = inputData[0];
|
||||||
@ -303,7 +343,7 @@ export const ComfyWidgets = {
|
|||||||
subfolder = name.substring(0, folder_separator);
|
subfolder = name.substring(0, folder_separator);
|
||||||
name = name.substring(folder_separator + 1);
|
name = name.substring(folder_separator + 1);
|
||||||
}
|
}
|
||||||
img.src = `/view?filename=${name}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}`;
|
img.src = api.apiURL(`/view?filename=${encodeURIComponent(name)}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}`);
|
||||||
node.setSizeForImage?.();
|
node.setSizeForImage?.();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -355,27 +395,30 @@ export const ComfyWidgets = {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
async function uploadFile(file, updateNode) {
|
async function uploadFile(file, updateNode, pasted = false) {
|
||||||
try {
|
try {
|
||||||
// Wrap file in formdata so it includes filename
|
// Wrap file in formdata so it includes filename
|
||||||
const body = new FormData();
|
const body = new FormData();
|
||||||
body.append("image", file);
|
body.append("image", file);
|
||||||
const resp = await fetch("/upload/image", {
|
if (pasted) body.append("subfolder", "pasted");
|
||||||
|
const resp = await api.fetchApi("/upload/image", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body,
|
body,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (resp.status === 200) {
|
if (resp.status === 200) {
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
// Add the file as an option and update the widget value
|
// Add the file to the dropdown list and update the widget value
|
||||||
if (!imageWidget.options.values.includes(data.name)) {
|
let path = data.name;
|
||||||
imageWidget.options.values.push(data.name);
|
if (data.subfolder) path = data.subfolder + "/" + path;
|
||||||
|
|
||||||
|
if (!imageWidget.options.values.includes(path)) {
|
||||||
|
imageWidget.options.values.push(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (updateNode) {
|
if (updateNode) {
|
||||||
showImage(data.name);
|
showImage(path);
|
||||||
|
imageWidget.value = path;
|
||||||
imageWidget.value = data.name;
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
alert(resp.status + " - " + resp.statusText);
|
alert(resp.status + " - " + resp.statusText);
|
||||||
@ -407,7 +450,7 @@ export const ComfyWidgets = {
|
|||||||
// Add handler to check if an image is being dragged over our node
|
// Add handler to check if an image is being dragged over our node
|
||||||
node.onDragOver = function (e) {
|
node.onDragOver = function (e) {
|
||||||
if (e.dataTransfer && e.dataTransfer.items) {
|
if (e.dataTransfer && e.dataTransfer.items) {
|
||||||
const image = [...e.dataTransfer.items].find((f) => f.kind === "file" && f.type.startsWith("image/"));
|
const image = [...e.dataTransfer.items].find((f) => f.kind === "file");
|
||||||
return !!image;
|
return !!image;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -428,6 +471,16 @@ export const ComfyWidgets = {
|
|||||||
return handled;
|
return handled;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
node.pasteFile = function(file) {
|
||||||
|
if (file.type.startsWith("image/")) {
|
||||||
|
const is_pasted = (file.name === "image.png") &&
|
||||||
|
(file.lastModified - Date.now() < 2000);
|
||||||
|
uploadFile(file, true, is_pasted);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
return { widget: uploadWidget };
|
return { widget: uploadWidget };
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@ -88,7 +88,7 @@ body {
|
|||||||
top: 50%;
|
top: 50%;
|
||||||
right: 0;
|
right: 0;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
z-index: 100;
|
z-index: 999;
|
||||||
width: 170px;
|
width: 170px;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
6
web/types/comfy.d.ts
vendored
6
web/types/comfy.d.ts
vendored
@ -1,5 +1,5 @@
|
|||||||
import { LGraphNode, IWidget } from "./litegraph";
|
import { LGraphNode, IWidget } from "./litegraph";
|
||||||
import { ComfyApp } from "/scripts/app";
|
import { ComfyApp } from "../../scripts/app";
|
||||||
|
|
||||||
export interface ComfyExtension {
|
export interface ComfyExtension {
|
||||||
/**
|
/**
|
||||||
@ -30,9 +30,7 @@ export interface ComfyExtension {
|
|||||||
getCustomWidgets(
|
getCustomWidgets(
|
||||||
app: ComfyApp
|
app: ComfyApp
|
||||||
): Promise<
|
): Promise<
|
||||||
Array<
|
Record<string, (node, inputName, inputData, app) => { widget?: IWidget; minWidth?: number; minHeight?: number }>
|
||||||
Record<string, (node, inputName, inputData, app) => { widget?: IWidget; minWidth?: number; minHeight?: number }>
|
|
||||||
>
|
|
||||||
>;
|
>;
|
||||||
/**
|
/**
|
||||||
* Allows the extension to add additional handling to the node before it is registered with LGraph
|
* Allows the extension to add additional handling to the node before it is registered with LGraph
|
||||||
|
|||||||
1
web/user.css
Normal file
1
web/user.css
Normal file
@ -0,0 +1 @@
|
|||||||
|
/* Put custom styles here */
|
||||||
Loading…
x
Reference in New Issue
Block a user