Author SHA1 Message Date
kaidu 04eaa3074f fix missing mask issue 2025-04-19 12:24:37 +02:00
kaidu e8652d4b65 add redux combine node 2025-04-19 11:29:35 +02:00
kaidu a693901f26 merge 2025-04-18 15:18:52 +02:00
kaidu 87b9b0655f bugfixes 2025-04-18 15:16:06 +02:00
kaibioinfo 54ee24e8b4 Merge pull request #23 from vojtajina/float-downsampling_factor
ReduxAdvanced: float downsampling_factor for better control
2025-04-18 15:15:23 +02:00
kaibioinfo 96d4ab1256 Merge pull request #26 from huixingyun/fix/mask-output
bugfix: reshape mask to (B, H, W)
2025-04-18 14:58:24 +02:00
kaibioinfo 0e928526e9 Merge pull request #28 from TangYanxin/main
Support 512 siglip model.
2025-04-18 14:55:56 +02:00
TangYanxin fcbaa24050 Support 512 siglip model. 2025-04-17 16:34:14 +08:00
hongbo.mo 56df41ef2b bugfix: reshape mask to (B, H, W) 2025-04-10 16:46:11 +08:00
Vojta Jina c7dba75b80 ReduxAdvanced: float downsampling_factor for better control 2025-01-17 09:31:29 -08:00
kaidu 0a87efa252 Merge branch 'main' of https://github.com/kaibioinfo/ComfyUI_AdvancedRefluxControl 2024-11-24 21:24:54 +01:00
kaibioinfo 8e13afbfc9 Update README.md 2024-11-24 21:24:18 +01:00
kaidu a2e2032c8c fix naming 2024-11-24 21:24:07 +01:00
kaibioinfo 97c7fe05e6 Update README.md 2024-11-24 21:17:17 +01:00
kaidu 768d5c0d24 fix naming 2024-11-24 21:11:03 +01:00
kaidu f1a3822404 forgot interpolation method 2024-11-24 21:00:34 +01:00
kaidu 89a665de0f add workflows 2024-11-24 20:51:33 +01:00
kaibioinfo da1be06732 Update README.md 2024-11-24 20:46:41 +01:00
kaidu 564e93041d masking and aspect ratios 2024-11-24 20:17:32 +01:00
kaibioinfo 37136e1a4c Update nodes.py
streamline simple node settings
2024-11-23 12:29:44 +01:00
kaibioinfo 4f6b78df66 Update README.md 2024-11-23 00:04:31 +01:00
kaidu 3aa7bd746a add high strengh mode 2024-11-22 23:51:57 +01:00
kaibioinfo b84294d70d Update README.md 2024-11-22 23:51:19 +01:00
kaidu 428e9412bc Merge remote-tracking branch 'refs/remotes/origin/main' 2024-11-22 23:40:00 +01:00
kaidu 97f41ef9ae update nodes 2024-11-22 23:39:26 +01:00
kaibioinfo 6b4e6fea75 Update README.md
spelling errors
2024-11-22 20:47:44 +01:00
4 changed files with 2493 additions and 89 deletions
+98 -29
View File
@@ -1,10 +1,14 @@
# ComfyUI_AdvancedRefluxControl
# ComfyUI_AdvancedReduxControl
As many of you might noticed, the recently released Reflux model is rather a model for generating multiple variants of an image, but it does not allow for changing an image based on a prompt.
As many of you might noticed, the recently released Redux model is rather a model for generating multiple variants of an image, but it does not allow for changing an image based on a prompt.
If you use Reflux with an Image and add a prompt, your prompt is just ignored. In general, there is no strength slider or anything in Reflux to control how much the coniditioning image should determine the final outcome of your image.
If you use Redux with an Image and add a prompt, your prompt is just ignored. In general, there is no strength slider or anything in Redux to control how much the coniditioning image should determine the final outcome of your image.
For this purpose I wrote this little custom node that allows you change the strength of the Reflux effect.
For this purpose I wrote this little custom node that allows you change the strength of the Redux effect.
## Changelog
- **v2.0** This version adds the option to mask the conditioning image and to submit non-square images. The simple node hasn't changed and is backcompatible, the advanced mode is completely redesigned, so use v1 if you need backward compatibility.
## Examples
@@ -14,73 +18,138 @@ I used the following pexel image as an example conditioning image: [[https://www
Lets say we want to have a similar image, but as comic/cartoon. The prompt I use is "comic, cartoon, vintage comic"
Using Reflux on Flux1-dev I obtain the following image.
Using Redux on Flux1-dev I obtain the following image.
**original Reflux setting**
**original Redux setting**
![ComfyUI_00106_](https://github.com/user-attachments/assets/0c5506ef-5131-4b57-962c-ab3703881363)
As you can see, the prompt is vastly ignored. Using the custom node and "medium" setting I obtain
**Reflux medium strength**
**Redux medium strength**
![image](https://github.com/user-attachments/assets/eb81a55a-6bdd-43ef-a8da-8d27f210c116)
Lets do the same with anime. The prompt is "anime drawing in anime style. Studio Ghibli, Makoto Shinkai."
As the anime keyword has a strong effect in Flux, we see a better prompt following on default than with comics.
**original Reflux setting**
**original Redux setting**
![image](https://github.com/user-attachments/assets/e5795369-2b8e-477a-974f-e0250d8689b6)
Still, its far from perfect. With "medium" setting we get an image that is much closer to anime or studio Ghibli.
**Reflux medium strength**
**Redux medium strength**
![image](https://github.com/user-attachments/assets/b632457a-3a7e-4d99-981e-6c2682d16e2e)
Finally, we try a very challenging prompt: "Marble statues, sculptures, stone statues. stone and marble texture. Two sculptures made out of marble stone.". As you can see, I repeated the prompt multiple times to increase its strength.
But despite the repeats, the default Reflux workflow will just give us the input image refluxed - our prompt is totally ignored.
**original Reflux setting**
You can also mix more than one images together. Here is an example with adding a second image: [[https://www.pexels.com/de-de/foto/komplizierte-bogen-der-mogul-architektur-in-jaipur-29406307/]]
Mixing both together and using the anime prompt above gives me
![image](https://github.com/user-attachments/assets/1385b22f-4497-4fdf-8255-3a15bda74a1d)
Finally, we try a very challenging prompt: "Marble statues, sculptures, stone statues. stone and marble texture. Two sculptures made out of marble stone.". As you can see, I repeated the prompt multiple times to increase its strength.
But despite the repeats, the default Redux workflow will just give us the input image Reduxed - our prompt is totally ignored.
**original Redux setting**
![ComfyUI_00108_](https://github.com/user-attachments/assets/24ad66e9-4f21-497d-8d0e-cb4778f0d1e9)
With medium we get an image back that looks more like porcelain instead of marble, but at least the two women are sculptures now.
**Reflux medium strength**
**Redux medium strength**
![image](https://github.com/user-attachments/assets/dce4aa6f-52ab-4ef0-b027-193318895969)
Further decreasing the Reflux strength will transform the woman into statues finally, but it will also further decrease their likeness to the conditioning image. In almost all my experiments, it was better to repeat multiple seeds with the "medium" setting instead of further decreasing the strength.
Further decreasing the Redux strength will transform the woman into statues finally, but it will also further decrease their likeness to the conditioning image. In almost all my experiments, it was better to repeat multiple seeds with the "medium" setting instead of further decreasing the strength.
# Masked Conditioning Images
With **v.2** you can now also add a mask to the conditioning image.
![image](https://github.com/user-attachments/assets/71644833-1169-47b9-a843-83fd739b17c8)
In this example I just masked the flower pattern on the clothing of the right women. I then prompt for "Man walking in New York, smiling, holding a smart phone in his hand.". As you can see, his shirt adapts to the flower pattern, while nothing outside the mask has any impact on the outcoming image.
![image](https://github.com/user-attachments/assets/2163c140-4980-4738-88db-77c8286742e6)
When the masking area is very small, you have to increase the strength of the conditioning image as "less of the image" is used to condition your generation.
## Non-Square Images
Redux (or better CLIP) cannot deal with non-square images by default. It will just center-crop your conditioning image such that it has a square resolution. Now that the node supports masking, we can simply support non-square images, too. We just make the image square by adding black borders to the shorter edge. Of course, we do not want to have these borders in the generated image, so we add a mask that cover the original image but not the black padding border.
You do not have to do this yourself. There is a "keep aspect ratio" option that automatically generates the padding and adjust the mask for you.
Here is an example: the input image (again from Pexel: ) is this one: https://www.pexels.com/photo/man-wearing-blue-gray-and-black-crew-neck-shirt-1103832/
To make a point, I cropped the images to make it maximal non-square.
![image](https://github.com/user-attachments/assets/8add3187-77b3-49b2-bd9e-c82297925a8d)
With the normal workflow and the prompt "comic, vintage comic, cartoon" we would get this image back:
![image](https://github.com/user-attachments/assets/169d33e0-27db-4e4c-b5cc-ec0b6729032a)
With the "keep aspect ratio" option enabled, we get this instead:
![image](https://github.com/user-attachments/assets/10e3a8b8-9752-4060-b6b5-ed35f9764320)
Similar to masks, the conditioning effect will be weaker when we use only a small mask (or here: when the aspect ratio is extremely unbalanced). Thus, I would still recommend to avoid images with too extreme aspect ratios as this example image above.
## Usage
You can use the images above for example workflows.
I was told that the images above for some reason do not contain the workflow. So I just uploaded the workflow files into the github. The **simple_workflow.json** is the workflow containing a single setting, the **advanced_workflow.json** has several customization options as well as masking and aspect ratio.
The ComfyUI plugin comes with two additional nodes: StyleModelApplySimple and StyleModelApplyAdvanced. Usually, you can just replace your ApplyStyle node with the StyleModelApplySimple node and "medium" strength and you will get best results. However, feel free to experiment with the StyleModelApplyAdvanced node.
### StyleModelApplySimple
## Short background on Reflux
This workflow is a replacement for the ComfyUI StyleModelApply node. It has a single option that controls the influence of the conditioning image on the generation. The example images are all generated with the "medium" strength option. However, when using masking, you might have to use "strongest" or "strong" instead.
Reflux works in two steps. First there is a Clip Vision model that crops your input image into square aspect ratio and reduce its size to 384x384 pixels. It splits this image into 27x27 small patches and each patch is projected into CLIP space.
Reflux itself is just a very small linear function that projects these clip image patches into the T5 latent space. The resulting tokens are then added to your T5 prompt.
### ReduxAdvanced
Intuitively, Reflux is translating your conditioning input image into "a prompt" that is added at the end of your own prompt.
This node allows for more customization. As input it gets the conditioning (prompt), the Redux style model, the CLIP vision model and optionally(!) the mask. Its parameters are:
So why is Reflux dominating the final prompt? It's because the user prompt is usually very short (255 or 512 tokens). Reflux, in contrast, adds 729 new tokens to your prompt. This might be 3 times as much as your original prompt. Also, the Reflux prompt might contain much more information than a user written prompt that just contains the word "anime".
- **downsampling_factor**: This is the most important parameter and it determines how strongly the conditioning image influences the generated image. In fact, the strength value in the StyleModelApplySimple node is just changing this single value from 1 (strongest), to 5 (weakest). The "medium" strength option is a downsampling_factor of 3. You can also choose other values up to 9.
- **downsampling_function**: These functions are the same as in any graphics program when you resize an image. The default is "area", but "bicubic" and "nearest_exact" are also interesting choices. The chosen function can very much change the outcome, so its worth experimenting a bit.
- **mode**: How the image should be cropped:
- - center crop (square) is what Redux is doing by default: cropping your image to a square image and then resizing it to 384x384 pixel
- - keep aspect ratio will add a padding to your image such that it gets square. It will adjust the mask (or generate one if no one is given) such that the padding is not part of the mask. Note that the final image is still resized to 384x384, so your image will be compressed more if you add more padding.
- - autocrop with mask will crop your image in a way that the masked area is in the center. It will also crop your image such that only the masked area and a margin remains. The margin is specified as the autocrop_margin parameter and is relative to the total size of the image. So autocropping with a margin of 0.1 means the crop is done on the masked area + 10% of the image on each side.
- **weight**: This option downscales the Redux tokens by the given value squared. This is very similar to the "conditioning average" approach many people use to reduce the effect of Redux on the generated image. This is an alternative way of reducing Redux' impact, but downsampling works better in most cases. However, feel free to also experiment with this value, or even with a combination of both: downsampling AND weight.
- **autocrop_margin** this parameter is only used when "autocrop with mask" is selected as mode
So there are two solutions here: Either we shrink the strength of the Reflux prompt, or we shorten the Reflux prompt.
The node outputs the conditioning, as well as the cropped and resized image and its mask. You neither need the image nor the mask, they are just for debugging. Play around with the cropping option and use the "Image preview" node to see how it effects the cropped image and mask.
## Token merging by downsampling
To shrink the Reflux prompt and increase the influence of the user prompt, we can use a simple trick: We take the 27x27 image patches and split them into 9x9 blocks, each containing 3x3 patches. We then merge all 3x3 tokens into one by averaging its latent embedding. So instead of having a very long prompt with 27x27=729 tokens we now only have 9x9=81 tokens. So our newly added prompt is much smaller than the user provided prompt and, thus, have less influence on the image generation.
## Short background on Redux
Downsampling is what happens when you use the "medium" setting. Of all three techniques I tried to decrease the Reflux effect, downsampling worked best. However, there are no further customization options. You can only downsample to 81 tokens (downsampling more is too much).
Redux works in two steps. First there is a Clip Vision model that crops your input image into square aspect ratio and reduce its size to 384x384 pixels. It splits this image into 27x27 small patches and each patch is projected into CLIP space.
## Controling Reflux with Token merging
Redux itself is just a very small linear function that projects these clip image patches into the T5 latent space. The resulting tokens are then added to your T5 prompt.
The idea here is to shrink the Reflux prompt length by merging similar tokens together. Just think about large part of your input image contain more or less the same stuff anyways, so why having always 729 tokens? My implementation here is extremely simple and stupid and not very efficient, but anyways: I just go over all Reflux tokens and merge two tokens if their cosine similarity is above a user defined threshold.
Intuitively, Redux is translating your conditioning input image into "a prompt" that is added at the end of your own prompt.
Even a threshold like 0.9 is already removing half of the Reflux tokens. A threshold of 0.8 is often reducing the Reflux tokens so much that they are in similar length as the user prompt.
So why is Redux dominating the final prompt? It's because the user prompt is usually very short (255 or 512 tokens). Redux, in contrast, adds 729 new tokens to your prompt. This might be 3 times as much as your original prompt. Also, the Redux prompt might contain much more information than a user written prompt that just contains the word "anime".
So there are two solutions here: Either we shrink the strength of the Redux prompt, or we shorten the Redux prompt.
The next sections are a bit chaotic: I changed the method several times and many stuff I tried is outdated already. The only and best technique I found so far is described in **Interpolation methods**.
## Controling Redux with Token downsampling
To shrink the Redux prompt and increase the influence of the user prompt, we can use a simple trick: We take the 27x27 image patches and split them into 9x9 blocks, each containing 3x3 patches. We then merge all 3x3 tokens into one by averaging their latent embeddings. So instead of having a very long prompt with 27x27=729 tokens we now only have 9x9=81 tokens. So our newly added prompt is much smaller than the user provided prompt and, thus, have less influence on the image generation.
Downsampling is what happens when you use the "medium" setting. Of all three techniques I tried to decrease the Redux effect, downsampling worked best. ~~However, there are no further customization options. You can only downsample to 81 tokens (downsampling more is too much)~~.
## Interpolation methods
Instead of averaging over small blocks of tokens, we can use a convolution function to shrink our 27x27 images patches to an arbitrary size. There are different functions available which most of you probably know from image resizing (its the same procedure). The averaging method above is "area", but there are also other methods available such as "bicubic".
## Controling Redux with Token merging
The idea here is to shrink the Redux prompt length by merging similar tokens together. Just think about large part of your input image contain more or less the same stuff anyways, so why having always 729 tokens? My implementation here is extremely simple and stupid and not very efficient, but anyways: I just go over all Redux tokens and merge two tokens if their cosine similarity is above a user defined threshold.
Even a threshold like 0.9 is already removing half of the Redux tokens. A threshold of 0.8 is often reducing the Redux tokens so much that they are in similar length as the user prompt.
I would start with a threshold of 0.8. If the image is blurry, increase the value a bit. If there is no effect of your prompt, decrease the threshold slightly.
## Controling Reflux with Token downscaling
## Controling Redux with Token downscaling
We can also just multiply the tokens by a certain strength value. As lower the strength, as closer the values are to zero. This is similar to prompt weighting which was quite popular for earlier stable diffusion versions, but never really worked that well for T5. Nevertheless, this technique seem to work well enough for flux.
File diff suppressed because it is too large Load Diff
+262 -60
View File
@@ -32,10 +32,8 @@ def automerge(tensor, threshold):
newTensor.append(torch.stack(tokens))
return torch.stack(newTensor)
DownScalingFactors = {"1:1": 1, "1:3":3, "1:9": 9}
STRENGTHS = ["very high", "medium", "low", "very low", "lowest"]
STRENGTHS_VALUES = [1,3,3,3,3]
WEIGHTING_VALUES = [1,1,0.75, 0.35,0.2]
STRENGTHS = ["highest", "high", "medium", "low", "lowest"]
STRENGTHS_VALUES = [1,2, 3,4,5]
class StyleModelApplySimple:
@classmethod
@@ -51,37 +49,9 @@ class StyleModelApplySimple:
CATEGORY = "conditioning/style_model"
def apply_stylemodel(self, clip_vision_output, style_model, conditioning, image_strength):
cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
stren = STRENGTHS.index(image_strength)
factor = STRENGTHS_VALUES[stren]
weighting = WEIGHTING_VALUES[stren]
if factor>1:
(b,t,h)=cond.shape
m = int(np.sqrt(t))
cond=torch.nn.PixelUnshuffle(factor)(cond.view(b, m, m, h).transpose(-1, 1)).transpose(1,-1)
cond=cond.view(b,m//factor, m//factor, h, factor*factor).mean(-1).view(b,-1, h) * weighting
c = []
for t in conditioning:
n = [torch.cat((t[0], cond), dim=1), t[1].copy()]
c.append(n)
return (c, )
class StyleModelApplyInterpolation:
@classmethod
def INPUT_TYPES(s):
return {"required": {"conditioning": ("CONDITIONING", ),
"style_model": ("STYLE_MODEL", ),
"clip_vision_output": ("CLIP_VISION_OUTPUT", ),
"downsampling_factor": ("INT", {"default": 3, "min": 1, "max": 9}),
"mode": (["nearest", "bicubic", "bilinear","area", "nearest-exact" ], {"default": "area"})
}}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "apply_stylemodel"
CATEGORY = "conditioning/style_model"
def apply_stylemodel(self, clip_vision_output, style_model, conditioning, downsampling_factor, mode):
downsampling_factor = STRENGTHS_VALUES[stren]
mode="area" if downsampling_factor==3 else "bicubic"
cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
if downsampling_factor>1:
(b,t,h)=cond.shape
@@ -94,52 +64,284 @@ class StyleModelApplyInterpolation:
c.append(n)
return (c, )
def standardizeMask(mask):
if mask is None:
return None
if len(mask.shape) == 2:
(h,w)=mask.shape
mask=mask.view(1,1,h,w)
elif len(mask.shape)==3:
(b,h,w)=mask.shape
mask=mask.view(b,1,h,w)
return mask
class StyleModelApplyAdvanced:
def combine_attention_mask(conditioning, clip_vision_tokens, mask, attention_bias_maximum, attention_bias_minimum):
# mask is (b,h,w) with [0,1] -> we transform to [attention_bias_maximum, attention_bias_minimum]
attn_bias = attention_bias_maximum*(mask) + attention_bias_minimum*(1-mask)
txt, keys = conditioning
keys = keys.copy()
n = clip_vision_tokens.shape[1]
# get the size of the mask image
mask_ref_size = keys.get("attention_mask_img_shape", (1, 1))
n_ref = mask_ref_size[0] * mask_ref_size[1]
n_txt = txt.shape[1]
# grab the existing mask
mask = keys.get("attention_mask", None)
# create a default mask if it doesn't exist
if mask is None:
mask = torch.zeros((txt.shape[0], n_txt + n_ref, n_txt + n_ref), dtype=torch.float16)
# convert the mask dtype, because it might be boolean
# we want it to be interpreted as a bias
if mask.dtype == torch.bool:
# log(True) = log(1) = 0
# log(False) = log(0) = -inf
mask = torch.log(mask.to(dtype=torch.float16))
# now we make the mask bigger to add space for our new tokens
new_mask = torch.zeros((txt.shape[0], n_txt + n + n_ref, n_txt + n + n_ref), dtype=torch.float16)
# copy over the old mask, in quandrants
new_mask[:, :n_txt, :n_txt] = mask[:, :n_txt, :n_txt]
new_mask[:, :n_txt, n_txt+n:] = mask[:, :n_txt, n_txt:]
new_mask[:, n_txt+n:, :n_txt] = mask[:, n_txt:, :n_txt]
new_mask[:, n_txt+n:, n_txt+n:] = mask[:, n_txt:, n_txt:]
# now fill in the attention bias to our redux tokens
new_mask[:, :n_txt, n_txt:n_txt+n] = attn_bias
new_mask[:, n_txt+n:, n_txt:n_txt+n] = attn_bias
keys["attention_mask"] = new_mask.to(txt.device)
keys["attention_mask_img_shape"] = mask_ref_size
return (txt,keys)
def crop(img, mask, box, desiredSize):
(ox,oy,w,h) = box
if mask is not None:
mask=torch.nn.functional.interpolate(mask, size=(h,w), mode="area").view(-1,h,w,1)
img = torch.nn.functional.interpolate(img.transpose(-1,1), size=(w,h), mode="bicubic", antialias=True)
return (img[:, :, ox:(desiredSize+ox), oy:(desiredSize+oy)].transpose(1,-1), None if mask == None else mask[:, oy:(desiredSize+oy), ox:(desiredSize+ox),:])
def letterbox(img, mask, w, h, desiredSize):
(b,oh,ow,c) = img.shape
img = torch.nn.functional.interpolate(img.transpose(-1,1), size=(w,h), mode="bicubic", antialias=True).transpose(1,-1)
letterbox = torch.zeros(size=(b,desiredSize,desiredSize, c))
offsetx = (desiredSize-w)//2
offsety = (desiredSize-h)//2
letterbox[:, offsety:(offsety+h), offsetx:(offsetx+w), :] += img
img = letterbox
if mask is not None:
mask=torch.nn.functional.interpolate(mask, size=(h,w), mode="bicubic")
letterbox = torch.zeros(size=(b,1,desiredSize,desiredSize))
letterbox[:, :, offsety:(offsety+h), offsetx:(offsetx+w)] += mask
mask = letterbox.view(b,1,desiredSize,desiredSize)
return (img, mask)
def getBoundingBox(mask, w, h, relativeMargin, desiredSize):
mask=mask.view(h,w)
marginW = math.ceil(relativeMargin * w)
marginH = math.ceil(relativeMargin * h)
indices = torch.nonzero(mask, as_tuple=False)
y_min, x_min = indices.min(dim=0).values
y_max, x_max = indices.max(dim=0).values
x_min = max(0, x_min.item() - marginW)
y_min = max(0, y_min.item() - marginH)
x_max = min(w, x_max.item() + marginW)
y_max = min(h, y_max.item() + marginH)
box_width = x_max - x_min
box_height = y_max - y_min
larger_edge = max(box_width, box_height, desiredSize)
if box_width < larger_edge:
delta = larger_edge - box_width
left_space = x_min
right_space = w - x_max
expand_left = min(delta // 2, left_space)
expand_right = min(delta - expand_left, right_space)
expand_left += min(delta - (expand_left+expand_right), left_space-expand_left)
x_min -= expand_left
x_max += expand_right
if box_height < larger_edge:
delta = larger_edge - box_height
top_space = y_min
bottom_space = h - y_max
expand_top = min(delta // 2, top_space)
expand_bottom = min(delta - expand_top, bottom_space)
expand_top += min(delta - (expand_top+expand_bottom), top_space-expand_top)
y_min -= expand_top
y_max += expand_bottom
x_min = max(0, x_min)
y_min = max(0, y_min)
x_max = min(w, x_max)
y_max = min(h, y_max)
return x_min, y_min, x_max, y_max
def patchifyMask(mask, patchSize=14):
if mask is None:
return mask
(b, imgSize, imgSize,_) = mask.shape
toks = imgSize//patchSize
return torch.nn.MaxPool2d(kernel_size=(patchSize,patchSize),stride=patchSize)(mask.view(b,imgSize,imgSize)).view(b,toks,toks,1)
def prepareImageAndMask(visionEncoder, image, mask, mode, autocrop_margin, desiredSize=384):
mode = IMAGE_MODES.index(mode)
(B,H,W,C) = image.shape
if mode==0: # center crop square
imgsize = min(H,W)
ratio = desiredSize/imgsize
(w,h) = (round(W*ratio), round(H*ratio))
image, mask = crop(image, standardizeMask(mask), ((w - desiredSize)//2, (h - desiredSize)//2, w, h), desiredSize)
elif mode==1:
if mask is None:
mask = torch.ones(size=(B,H,W))
imgsize = max(H,W)
ratio = desiredSize/imgsize
(w,h) = (round(W*ratio), round(H*ratio))
image, mask = letterbox(image, standardizeMask(mask), w, h, desiredSize)
elif mode==2:
(bx,by,bx2,by2) = getBoundingBox(mask,W,H,autocrop_margin, desiredSize)
image = image[:,by:by2,bx:bx2,:]
mask = mask[:,by:by2,bx:bx2]
imgsize = max(bx2-bx,by2-by)
ratio = desiredSize/imgsize
(w,h) = (round((bx2-bx)*ratio), round((by2-by)*ratio))
image, mask = letterbox(image, standardizeMask(mask), w, h, desiredSize)
return (image,mask)
def processMask(mask,imgSize=384, patchSize=14):
if len(mask.shape) == 2:
(h,w)=mask.shape
mask=mask.view(1,1,h,w)
elif len(mask.shape)==3:
(b,h,w)=mask.shape
mask=mask.view(b,1,h,w)
scalingFactor = imgSize/min(h,w)
# scale
mask=torch.nn.functional.interpolate(mask, size=(round(h*scalingFactor),round(w*scalingFactor)), mode="bicubic")
# crop
horizontalBorder = (imgSize-mask.shape[3])//2
verticalBorder = (imgSize-mask.shape[2])//2
mask=mask[:, :, verticalBorder:(verticalBorder+imgSize),horizontalBorder:(horizontalBorder+imgSize)].view(b,imgSize,imgSize)
toks = imgSize//patchSize
return torch.nn.MaxPool2d(kernel_size=(patchSize,patchSize),stride=patchSize)(mask).view(b,toks,toks,1)
IMAGE_MODES = [
"center crop (square)",
"keep aspect ratio",
"autocrop with mask"
]
class ReduxCombine:
@classmethod
def INPUT_TYPES(s):
return {"required": {"a": ("CONDITIONING", ),
"b": ("CONDITIONING", )
}}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "combine"
CATEGORY = "conditioning/style_model"
def combine(self, a, b):
c = []
for (ta,tb) in zip(a,b):
tensorsA, keysA = ta
tensorsB, keysB = tb
shapeA = keysA["style_model_tokenspace"]
(batchSizeB, seqB, hB) = keysB["style_model_tokenspace"]
continuous_maskB = keysB["style_model_continuous_mask"]
(attention_bias_maximumB, attention_bias_minimumB) = keysB["style_model_attn_bias"]
# copy tokens from b to a
extr = tensorsB[:, -seqB:, :]
(tensorsC, keysC) = combine_attention_mask(ta, extr, continuous_maskB, attention_bias_maximumB, attention_bias_minimumB)
print(tensorsC.shape)
print(extr.shape)
tensorsC = torch.cat((tensorsC, extr),dim=1)
c.append([tensorsC, keysC])
return (c,)
class ReduxAdvanced:
@classmethod
def INPUT_TYPES(s):
return {"required": {"conditioning": ("CONDITIONING", ),
"style_model": ("STYLE_MODEL", ),
"clip_vision_output": ("CLIP_VISION_OUTPUT", ),
"downscale": (["1:1", "1:3", "1:9"], {"default": "1:3"}),
"merge_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
"clipWeight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01})
}}
RETURN_TYPES = ("CONDITIONING",)
"clip_vision": ("CLIP_VISION", ),
"image": ("IMAGE",),
"downsampling_factor": ("FLOAT", {"default": 3, "min": 1, "max":9, "step": 0.1}),
"downsampling_function": (["nearest", "bilinear", "bicubic","area","nearest-exact"], {"default": "area"}),
"mode": (IMAGE_MODES, {"default": "center crop (square)"}),
"weight": ("FLOAT", {"default": 1.0, "min":0.0, "max":1.0, "step":0.01})
},
"optional": {
"mask": ("MASK", ),
"autocrop_margin": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1.0, "step": 0.01}),
"attention_bias_maximum": ("FLOAT", {"default": 0.0, "min": -50, "max": 50}),
"attention_bias_minimum": ("FLOAT", {"default": -50.0, "min": -50, "max": 50})
}}
RETURN_TYPES = ("CONDITIONING","IMAGE", "MASK")
FUNCTION = "apply_stylemodel"
CATEGORY = "conditioning/style_model"
def apply_stylemodel(self, clip_vision_output, style_model, conditioning, downscale, merge_strength, clipWeight):
def apply_stylemodel(self, clip_vision, image, style_model, conditioning, downsampling_factor, downsampling_function,mode,weight, mask=None, autocrop_margin=0.0, attention_bias_maximum=0.0, attention_bias_minimum=-50):
desiredSize = 384
patchSize = 14
if clip_vision.model.vision_model.embeddings.position_embedding.weight.shape[0] == 1024:
desiredSize = 512
patchSize = 16
image, masko = prepareImageAndMask(clip_vision, image, mask, mode, autocrop_margin, desiredSize)
clip_vision_output,mask=(clip_vision.encode_image(image), patchifyMask(masko, patchSize))
mode="area"
cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
if downscale!="1:1":
(b,t,h)=cond.shape
m = int(np.sqrt(t))
factor = DownScalingFactors[downscale]
cond=torch.nn.PixelUnshuffle(factor)(cond.view(b, m, m, h).transpose(-1, 1)).transpose(1,-1)
cond=cond.view(b,m//factor, m//factor, h, factor*factor).mean(-1).view(b,-1, h)
cond = automerge(cond, merge_strength)*clipWeight
(b,t,h)=cond.shape
m = int(np.sqrt(t))
if downsampling_factor>1:
cond = cond.view(b, m, m, h)
if mask is not None:
cond = cond*mask
downsampled_size = (round(m/downsampling_factor), round(m/downsampling_factor))
cond=torch.nn.functional.interpolate(cond.transpose(1,-1), size=downsampled_size, mode=downsampling_function)
cond=cond.transpose(1,-1).reshape(b,-1,h)
mask = None if mask is None else torch.nn.functional.interpolate(mask.view(b, m, m, 1).transpose(1,-1), size=downsampled_size, mode=mode).transpose(-1,1)
cond = cond*(weight*weight)
c = []
if mask is not None:
binary_mask = (mask>0).reshape(b,-1)
max_len = binary_mask.sum(dim=1).max().item()
padded_embeddings = torch.zeros((b, max_len, h), dtype=cond.dtype, device=cond.device)
continuous_mask = torch.zeros((b, max_len))
for i in range(b):
filtered = cond[i][binary_mask[i]]
padded_embeddings[i, :filtered.size(0)] = filtered
continuous_mask[i, :filtered.size(0)] = mask[i].reshape(-1)[binary_mask[i]].float()
cond = padded_embeddings
else:
continuous_mask = torch.ones(cond.shape[0], cond.shape[1])
for t in conditioning:
n = [torch.cat((t[0], cond), dim=1), t[1].copy()]
t = combine_attention_mask(t, cond, continuous_mask, attention_bias_maximum, attention_bias_minimum)
adict = t[1].copy()
adict["style_model_tokenspace"] = cond.shape
adict["style_model_continuous_mask"] = continuous_mask
adict["style_model_attn_bias"] = (attention_bias_maximum, attention_bias_minimum)
n = [torch.cat((t[0], cond), dim=1), adict]
c.append(n)
return (c, )
return (c, image, masko.squeeze(-1) if masko is not None else None)
# A dictionary that contains all nodes you want to export with their names
# NOTE: names should be globally unique
NODE_CLASS_MAPPINGS = {
"StyleModelApplySimple": StyleModelApplySimple,
"StyleModelApplyAdvanced": StyleModelApplyAdvanced,
"StyleModelApplyInterpolation": StyleModelApplyInterpolation
"ReduxAdvanced": ReduxAdvanced,
"ReduxCombine": ReduxCombine
}
# A dictionary that contains the friendly/humanly readable titles for the nodes
NODE_DISPLAY_NAME_MAPPINGS = {
"StyleModelApplySimple": "Apply Style model (simple)",
"StyleModelApplyAdvanced": "Apply Style model (advanced)",
"StyleModelApplyInterpolation": "Apply style model (interpolation)"
}
"StyleModelApplySimple": "Apply style model (simple)",
"ReduxAdvanced": "Apply Redux model (advanced)"
}
+1078
View File
File diff suppressed because it is too large Load Diff