Skip to content
Python

added flux2 support

DeepBeepMeepf3a287a6bb5c
diff --git a/README.md b/README.md
index 2740b88..24b62c9 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,17 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models
-----
## 🔥 Latest Updates :
+
+### November 27 2025: WanGP v9.7, Flux Strikes Back
+
+**Flux 2**, the best ever open source *Image Generator* has just landed. It does everything very well: generate an *Image* based a *Text Prompt* or combine up to 10 *Images References*
+
+The only snag is that it is a 60B parameters for the *Transformer* part and 40B parameters for the *Text Encoder* part.
+
+Behold the *WanGP Miracle* ! Flux 2 wil work with only 10 GB of VRAM (maybe less!) if you are happy with 8 bits quantization (no need for 4bits). With 12GB of VRAM you can run the model at full power. You will need at least 64 GB of RAM. If not maybe *Memory Profile 5* will be your friend.
+
+I have added a new Memory Profile *Profile 4+* that is sligthly slower than *Profile 4* but can save you up to 1GB of VRAM.
+
### November 24 2025: WanGP v9.62, The Return of the King
So here is *Tencet* who is back in the race: let's welcome **Hunyuan Video 1.5**
diff --git a/defaults/flux2_dev.json b/defaults/flux2_dev.json
new file mode 100644
index 0000000..e4f034d
--- /dev/null
+++ b/defaults/flux2_dev.json
@@ -0,0 +1,18 @@
+{
+ "model": {
+ "name": "Flux 2 Dev",
+ "architecture": "flux2_dev",
+ "description": "FLUX.2 Dev is the latest rectified flow transformer from Black Forest Labs for image generation and editing.",
+ "URLs": [
+ "https://huggingface.co/DeepBeepMeep/Flux2/resolve/main/flux2-dev.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Flux2/resolve/main/flux2-dev_quanto_bf16_int8.safetensors"
+ ],
+ "image_outputs": true,
+ "no_negative_prompt": true
+ },
+ "prompt": "draw a hat on top of a hat inside a hat",
+ "resolution": "1024x1024",
+ "batch_size": 1,
+ "embedded_guidance_scale": 4,
+ "sampling_steps": 30
+}
diff --git a/loras_flux2/readme.txt b/loras_flux2/readme.txt
new file mode 100644
index 0000000..fad90af
--- /dev/null
+++ b/loras_flux2/readme.txt
@@ -0,0 +1 @@
+add here loras for flux2
\ No newline at end of file
diff --git a/models/flux/flux2_adapter.py b/models/flux/flux2_adapter.py
new file mode 100644
index 0000000..b71b4a6
--- /dev/null
+++ b/models/flux/flux2_adapter.py
@@ -0,0 +1,243 @@
+import sys
+from pathlib import Path
+from typing import List, Optional, Sequence
+
+import torch
+import torch.nn as nn
+from PIL import Image
+from einops import rearrange
+from PIL import Image
+from torch import Tensor
+import torchvision
+import math
+
+from shared.utils.utils import convert_image_to_tensor
+
+
+
+
+
+def compress_time(t_ids: Tensor) -> Tensor:
+ assert t_ids.ndim == 1
+ t_ids_max = torch.max(t_ids)
+ t_remap = torch.zeros((t_ids_max + 1,), device=t_ids.device, dtype=t_ids.dtype)
+ t_unique_sorted_ids = torch.unique(t_ids, sorted=True)
+ t_remap[t_unique_sorted_ids] = torch.arange(
+ len(t_unique_sorted_ids), device=t_ids.device, dtype=t_ids.dtype
+ )
+ t_ids_compressed = t_remap[t_ids]
+ return t_ids_compressed
+
+from einops import rearrange
+from torch import Tensor
+
+def center_crop_to_multiple_of_x(
+ img: Image.Image | list[Image.Image], x: int
+) -> Image.Image | list[Image.Image]:
+ if isinstance(img, list):
+ return [center_crop_to_multiple_of_x(_img, x) for _img in img] # type: ignore
+
+ w, h = img.size
+ new_w = (w // x) * x
+ new_h = (h // x) * x
+
+ left = (w - new_w) // 2
+ top = (h - new_h) // 2
+ right = left + new_w
+ bottom = top + new_h
+
+ resized = img.crop((left, top, right, bottom))
+ return resized
+
+def cap_pixels(img: Image.Image | list[Image.Image], k):
+ if isinstance(img, list):
+ return [cap_pixels(_img, k) for _img in img]
+ w, h = img.size
+ pixel_count = w * h
+
+ if pixel_count <= k:
+ return img
+
+ # Scaling factor to reduce total pixels below K
+ scale = math.sqrt(k / pixel_count)
+ new_w = int(w * scale)
+ new_h = int(h * scale)
+
+ return img.resize((new_w, new_h), Image.Resampling.LANCZOS)
+
+
+def cap_min_pixels(img: Image.Image | list[Image.Image], max_ar=8, min_sidelength=64):
+ if isinstance(img, list):
+ return [cap_min_pixels(_img, max_ar=max_ar, min_sidelength=min_sidelength) for _img in img]
+ w, h = img.size
+ if w < min_sidelength or h < min_sidelength:
+ raise ValueError(f"Skipping due to minimal sidelength underschritten h {h} w {w}")
+ if w / h > max_ar or h / w > max_ar:
+ raise ValueError(f"Skipping due to maximal ar overschritten h {h} w {w}")
+ return img
+
+
+def to_rgb(img: Image.Image | list[Image.Image]):
+ if isinstance(img, list):
+ return [
+ to_rgb(
+ _img,
+ )
+ for _img in img
+ ]
+ return img.convert("RGB")
+
+
+def default_images_prep(
+ x: Image.Image | list[Image.Image],
+) -> torch.Tensor | list[torch.Tensor]:
+ if isinstance(x, list):
+ return [default_images_prep(e) for e in x] # type: ignore
+ x_tensor = torchvision.transforms.ToTensor()(x)
+ return 2 * x_tensor - 1
+
+def default_prep(
+ img: Image.Image | list[Image.Image], limit_pixels: int | None, ensure_multiple: int = 16
+) -> torch.Tensor | list[torch.Tensor]:
+ img_rgb = to_rgb(img)
+ img_min = cap_min_pixels(img_rgb) # type: ignore
+ if limit_pixels is not None:
+ img_cap = cap_pixels(img_min, limit_pixels) # type: ignore
+ else:
+ img_cap = img_min
+ img_crop = center_crop_to_multiple_of_x(img_cap, ensure_multiple) # type: ignore
+ img_tensor = default_images_prep(img_crop)
+ return img_tensor
+
+
+def encode_image_refs(ae, img_ctx: list[Image.Image]):
+ scale = 10
+
+ if len(img_ctx) > 1:
+ limit_pixels = 1024**2
+ elif len(img_ctx) == 1:
+ limit_pixels = 2024**2
+ else:
+ limit_pixels = None
+
+ if not img_ctx:
+ return None, None
+
+ img_ctx_prep = default_prep(img=img_ctx, limit_pixels=limit_pixels)
+ if not isinstance(img_ctx_prep, list):
+ img_ctx_prep = [img_ctx_prep]
+
+ # Encode each reference image
+ encoded_refs = []
+ for img in img_ctx_prep:
+ encoded = ae.encode(img[None].cuda())[0]
+ encoded_refs.append(encoded)
+
+ # Create time offsets for each reference
+ t_off = [scale + scale * t for t in torch.arange(0, len(encoded_refs))]
+ t_off = [t.view(-1) for t in t_off]
+
+ # Process with position IDs
+ ref_tokens, ref_ids = listed_prc_img(encoded_refs, t_coord=t_off)
+
+ # Concatenate all references along sequence dimension
+ ref_tokens = torch.cat(ref_tokens, dim=0) # (total_ref_tokens, C)
+ ref_ids = torch.cat(ref_ids, dim=0) # (total_ref_tokens, 4)
+
+ # Add batch dimension
+ ref_tokens = ref_tokens.unsqueeze(0) # (1, total_ref_tokens, C)
+ ref_ids = ref_ids.unsqueeze(0) # (1, total_ref_tokens, 4)
+
+ return ref_tokens.to(torch.bfloat16), ref_ids
+def listed_wrapper(fn):
+ def listed_prc(
+ x: list[Tensor],
+ t_coord: list[Tensor] | None = None,
+ ) -> tuple[list[Tensor], list[Tensor]]:
+ results = []
+ for i in range(len(x)):
+ results.append(
+ fn(
+ x[i],
+ t_coord[i] if t_coord is not None else None,
+ )
+ )
+ x, x_ids = zip(*results)
+ return list(x), list(x_ids)
+
+ return listed_prc
+
+def prc_txt(x: Tensor, t_coord: Tensor | None = None) -> tuple[Tensor, Tensor]:
+ _l, _ = x.shape # noqa: F841
+
+ coords = {
+ "t": torch.arange(1) if t_coord is None else t_coord,
+ "h": torch.arange(1), # dummy dimension
+ "w": torch.arange(1), # dummy dimension
+ "l": torch.arange(_l),
+ }
+ x_ids = torch.cartesian_prod(coords["t"], coords["h"], coords["w"], coords["l"])
+ return x, x_ids.to(x.device)
+
+def prc_img(x: Tensor, t_coord: Tensor | None = None) -> tuple[Tensor, Tensor]:
+ _, h, w = x.shape # noqa: F841
+ x_coords = {
+ "t": torch.arange(1) if t_coord is None else t_coord,
+ "h": torch.arange(h),
+ "w": torch.arange(w),
+ "l": torch.arange(1),
+ }
+ x_ids = torch.cartesian_prod(x_coords["t"], x_coords["h"], x_coords["w"], x_coords["l"])
+ x = rearrange(x, "c h w -> (h w) c")
+ return x, x_ids.to(x.device)
+
+def batched_wrapper(fn):
+ def batched_prc(x, t_coord = None):
+ results = []
+ for i in range(len(x)):
+ results.append(
+ fn(
+ x[i],
+ t_coord[i] if t_coord is not None else None,
+ )
+ )
+ x, x_ids = zip(*results)
+ return torch.stack(x), torch.stack(x_ids)
+
+ return batched_prc
+
+
+listed_prc_img = listed_wrapper(prc_img)
+batched_prc_img = batched_wrapper(prc_img)
+batched_prc_txt = batched_wrapper(prc_txt)
+
+
+
+def scatter_ids(x: Tensor, x_ids: Tensor) -> list[Tensor]:
+ """
+ using position ids to scatter tokens into place
+ """
+ x_list = []
+ t_coords = []
+ for data, pos in zip(x, x_ids):
+ _, ch = data.shape # noqa: F841
+ t_ids = pos[:, 0].to(torch.int64)
+ h_ids = pos[:, 1].to(torch.int64)
+ w_ids = pos[:, 2].to(torch.int64)
+
+ t_ids_cmpr = compress_time(t_ids)
+
+ t = torch.max(t_ids_cmpr) + 1
+ h = torch.max(h_ids) + 1
+ w = torch.max(w_ids) + 1
+
+ flat_ids = t_ids_cmpr * w * h + h_ids * w + w_ids
+
+ out = torch.zeros((t * h * w, ch), device=data.device, dtype=data.dtype)
+ out.scatter_(0, flat_ids.unsqueeze(1).expand(-1, ch), data)
+
+ x_list.append(rearrange(out, "(t h w) c -> 1 c t h w", t=t, h=h, w=w))
+
+ t_coords.append(torch.unique(t_ids, sorted=True))
+ return x_list
+
diff --git a/models/flux/flux_handler.py b/models/flux/flux_handler.py
index 6ec0827..a3c29c3 100644
--- a/models/flux/flux_handler.py
+++ b/models/flux/flux_handler.py
@@ -2,16 +2,34 @@ import torch
from PIL import Image
from shared.utils import files_locator as fl
-def get_ltxv_text_encoder_filename(text_encoder_quantization):
- text_encoder_filename = "T5_xxl_1.1/T5_xxl_1.1_enc_bf16.safetensors"
+def test_flux2(base_model_type):
+ return base_model_type in ["flux2_dev"]
+
+
+def get_flux_text_encoder_filename(text_encoder_quantization, base_model_type):
+ if test_flux2( base_model_type):
+ text_encoder_filename = "mistral3small/mistral3_small_bf16.safetensors"
+ else:
+ text_encoder_filename = "T5_xxl_1.1/T5_xxl_1.1_enc_bf16.safetensors"
if text_encoder_quantization =="int8":
text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_bf16_int8")
return fl.locate_file(text_encoder_filename, True)
+
class family_handler():
@staticmethod
def query_supported_types():
- return ["flux", "flux_chroma", "flux_chroma_radiance", "flux_dev_kontext", "flux_dev_umo", "flux_dev_uso", "flux_schnell", "flux_dev_kontext_dreamomni2" ]
+ return [
+ "flux",
+ "flux2_dev",
+ "flux_chroma",
+ "flux_chroma_radiance",
+ "flux_dev_kontext",
+ "flux_dev_umo",
+ "flux_dev_uso",
+ "flux_schnell",
+ "flux_dev_kontext_dreamomni2",
+ ]
@staticmethod
def query_family_maps():
@@ -24,15 +42,17 @@ class family_handler():
"flux_chroma" : "flux",
"flux_chroma_radiance": "flux",
"flux_dev_kontext_dreamomni2": "flux",
+ "flux2_dev": "flux",
}
models_comp_map = {
- "flux": ["flux_chroma", "flux_chroma_radiance", "flux_dev_kontext", "flux_dev_umo", "flux_dev_uso", "flux_schnell", "flux_dev_kontext_dreamomni2" ]
+ "flux": ["flux2_dev", "flux_chroma", "flux_chroma_radiance", "flux_dev_kontext", "flux_dev_umo", "flux_dev_uso", "flux_schnell", "flux_dev_kontext_dreamomni2" ]
}
return models_eqv_map, models_comp_map
@staticmethod
def query_model_def(base_model_type, model_def):
flux_model = "flux-dev" if base_model_type == "flux" else base_model_type.replace("_", "-")
+ flux2 = flux_model.startswith("flux2")
flux_schnell = flux_model == "flux-schnell"
flux_chroma = flux_model == "flux-chroma"
flux_chroma_radiance = flux_model == "flux-chroma-radiance"
@@ -43,10 +63,10 @@ class family_handler():
extra_model_def = {
"image_outputs" : True,
- "no_negative_prompt" : not (flux_chroma or flux_chroma_radiance),
+ "no_negative_prompt" : flux2 or not (flux_chroma or flux_chroma_radiance),
"flux-model": flux_model,
}
- extra_model_def["profiles_dir"] = [] if flux_schnell else ["flux"]
+ extra_model_def["profiles_dir"] = [] if (flux_schnell or flux2) else ["flux"]
if flux_chroma or flux_chroma_radiance:
extra_model_def["guidance_max_phases"] = 1
if flux_chroma_radiance:
@@ -64,7 +84,7 @@ class family_handler():
"label": "Reference Images / Style Images"
}
- if flux_kontext or flux_kontext_dreamomni2:
+ if flux_kontext or flux_kontext_dreamomni2 or flux2:
extra_model_def["inpaint_support"] = flux_kontext
extra_model_def["image_ref_choices"] = {
"choices": [
@@ -87,6 +107,9 @@ class family_handler():
"visible": False
}
+ if flux2:
+ extra_model_def["group"] ="flux2"
+ extra_model_def["no_background_removal"] = True
extra_model_def["fit_into_canvas_image_refs"] = 0
@@ -95,10 +118,10 @@ class family_handler():
@staticmethod
def get_rgb_factors(base_model_type ):
- if base_model_type == "flux_chroma_radiance":
+ if base_model_type in ["flux_chroma_radiance"]:
return None, None
from shared.RGB_factors import get_rgb_factors
- latent_rgb_factors, latent_rgb_factors_bias = get_rgb_factors("flux")
+ latent_rgb_factors, latent_rgb_factors_bias = get_rgb_factors("flux", sub_family= "flux2" if test_flux2(base_model_type) else "flux")
return latent_rgb_factors, latent_rgb_factors_bias
@staticmethod
@@ -133,47 +156,60 @@ class family_handler():
@staticmethod
def query_family_infos():
- return {"flux":(30, "Flux 1")}
+ return {"flux":(30, "Flux 1"), "flux2":(31, "Flux 2")}
@staticmethod
def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization):
- text_encoder_filename = get_ltxv_text_encoder_filename(text_encoder_quantization)
- ret = [
- {
- "repoId" : "DeepBeepMeep/LTX_Video",
- "sourceFolderList" : ["T5_xxl_1.1"],
- "fileList" : [ ["added_tokens.json", "special_tokens_map.json", "spiece.model", "tokenizer_config.json"] + computeList(text_encoder_filename) ]
- },
- {
- "repoId" : "DeepBeepMeep/HunyuanVideo",
- "sourceFolderList" : [ "clip_vit_large_patch14", ],
- "fileList" :[
- ["config.json", "merges.txt", "model.safetensors", "preprocessor_config.json", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "vocab.json"],
- ]
- },
- {
- "repoId" : "DeepBeepMeep/Flux",
- "sourceFolderList" : ["",],
- "fileList" : [ ["flux_vae.safetensors"] ]
- }]
-
-
- if base_model_type in ["flux_dev_uso"]:
- ret += [
- {
- "repoId" : "DeepBeepMeep/Flux",
- "sourceFolderList" : ["siglip-so400m-patch14-384"],
- "fileList" : [ ["config.json", "preprocessor_config.json", "model.safetensors"] ]
- }]
+ text_encoder_filename = get_flux_text_encoder_filename(text_encoder_quantization, base_model_type)
+ if test_flux2(base_model_type):
+ ret = [
+ {
+ "repoId": "DeepBeepMeep/Flux2",
+ "sourceFolderList": ["mistral3small", ""],
+ "fileList": [
+ [ "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "processor_config.json", "config.json", "preprocessor_config.json", "chat_template.jinja", ] + computeList(text_encoder_filename),
+ [ "flux2_vae.safetensors", ],
+ ],
+ }
+ ]
- if base_model_type in ["flux_dev_kontext_dreamomni2"]:
- ret += [
+ else:
+ ret = [
+ {
+ "repoId" : "DeepBeepMeep/LTX_Video",
+ "sourceFolderList" : ["T5_xxl_1.1"],
+ "fileList" : [ ["added_tokens.json", "special_tokens_map.json", "spiece.model", "tokenizer_config.json"] + computeList(text_encoder_filename) ]
+ },
+ {
+ "repoId" : "DeepBeepMeep/HunyuanVideo",
+ "sourceFolderList" : [ "clip_vit_large_patch14", ],
+ "fileList" :[
+ ["config.json", "merges.txt", "model.safetensors", "preprocessor_config.json", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "vocab.json"],
+ ]
+ },
{
"repoId" : "DeepBeepMeep/Flux",
- "sourceFolderList" : ["Qwen2.5-VL-7B-DreamOmni2"],
- "fileList" : [ ["Qwen2.5-VL-7B-DreamOmni2_quanto_bf16_int8.safetensors", "merges.txt", "tokenizer_config.json", "config.json", "vocab.json", "video_preprocessor_config.json", "preprocessor_config.json", "chat_template.jinja"] ]
+ "sourceFolderList" : ["",],
+ "fileList" : [ ["flux_vae.safetensors"] ]
}]
+
+ if base_model_type in ["flux_dev_uso"]:
+ ret += [
+ {
+ "repoId" : "DeepBeepMeep/Flux",
+ "sourceFolderList" : ["siglip-so400m-patch14-384"],
+ "fileList" : [ ["config.json", "preprocessor_config.json", "model.safetensors"] ]
+ }]
+
+
+ if base_model_type in ["flux_dev_kontext_dreamomni2"]:
+ ret += [
+ {
+ "repoId" : "DeepBeepMeep/Flux",
+ "sourceFolderList" : ["Qwen2.5-VL-7B-DreamOmni2"],
+ "fileList" : [ ["Qwen2.5-VL-7B-DreamOmni2_quanto_bf16_int8.safetensors", "merges.txt", "tokenizer_config.json", "config.json", "vocab.json", "video_preprocessor_config.json", "preprocessor_config.json", "chat_template.jinja"] ]
+ }]
return ret
@@ -187,7 +223,7 @@ class family_handler():
model_type = model_type,
model_def = model_def,
base_model_type=base_model_type,
- text_encoder_filename= get_ltxv_text_encoder_filename(text_encoder_quantization) if override_text_encoder is None else override_text_encoder,
+ text_encoder_filename= get_flux_text_encoder_filename(text_encoder_quantization, base_model_type) if override_text_encoder is None else override_text_encoder,
quantizeTransformer = quantizeTransformer,
dtype = dtype,
VAE_dtype = VAE_dtype,
@@ -195,7 +231,13 @@ class family_handler():
save_quantized = save_quantized
)
- pipe = { "transformer": flux_model.model, "vae" : flux_model.vae, "text_encoder" : flux_model.clip, "text_encoder_2" : flux_model.t5}
+ pipe = { "transformer": flux_model.model, "vae" : flux_model.vae}
+ if getattr(flux_model, "clip", None) is not None:
+ pipe["text_encoder"] = flux_model.clip
+ if getattr(flux_model, "t5", None) is not None:
+ pipe["text_encoder_2"] = flux_model.t5
+ if getattr(flux_model, "mistral", None) is not None:
+ pipe["text_encoder"] = flux_model.mistral.model
if flux_model.vision_encoder is not None:
pipe["siglip_model"] = flux_model.vision_encoder
@@ -217,6 +259,8 @@ class family_handler():
if settings_version < 2.34:
ui_defaults["denoising_strength"] = 1.
+ if flux_model.startswith("flux2"):
+ ui_defaults["embedded_guidance_scale"] = ui_defaults.get("embedded_guidance_scale", 4.0)
@staticmethod
def update_default_settings(base_model_type, model_def, ui_defaults):
@@ -225,11 +269,19 @@ class family_handler():
flux_umo = flux_model == "flux-dev-umo"
flux_kontext = flux_model == "flux-dev-kontext"
flux_kontext_dreamomni2 = flux_model == "flux-dev-kontext-dreamomni2"
+ flux2 = flux_model.startswith("flux2")
ui_defaults.update({
- "embedded_guidance": 2.5,
+ "embedded_guidance_scale": 2.5,
})
+ if flux2:
+ ui_defaults.update({
+ "embedded_guidance_scale": 4.0,
+ "remove_background_images_ref" : 0,
+
+ })
+
if flux_kontext or flux_uso or flux_kontext_dreamomni2:
ui_defaults.update({
"video_prompt_type": "KI",
diff --git a/models/flux/flux_main.py b/models/flux/flux_main.py
index b99b2df..f2d510e 100644
--- a/models/flux/flux_main.py
+++ b/models/flux/flux_main.py
@@ -6,23 +6,29 @@ from glob import iglob
from mmgp import offload as offload
import torch
from shared.utils.utils import calculate_new_dimensions
-from .sampling import denoise, get_schedule, prepare_kontext, prepare_prompt, prepare_multi_ip, unpack, resizeinput, patches_to_image
+from .sampling import denoise, get_schedule, get_schedule_flux2, prepare_kontext, prepare_prompt, prepare_multi_ip, unpack, resizeinput, patches_to_image
from .modules.layers import get_linear_split_map
from transformers import SiglipVisionModel, SiglipImageProcessor
import torchvision.transforms.functional as TVF
import math
from shared.utils.utils import convert_image_to_tensor, convert_tensor_to_image
from shared.utils import files_locator as fl
-from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer, AutoTokenizer, Qwen2VLProcessor
+from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2VLProcessor
+from .modules.autoencoder_flux2 import AutoencoderKLFlux2, AutoEncoderParamsFlux2
from .util import (
- aspect_ratio_to_height_width,
load_ae,
load_clip,
load_flow_model,
load_t5,
- save_image,
)
+from .flux2_adapter import (
+ scatter_ids ,
+ batched_prc_img,
+ batched_prc_txt,
+ encode_image_refs,
+ )
+from .modules.autoencoder_flux2 import AutoencoderKLFlux2
from PIL import Image
def preprocess_ref(raw_image: Image.Image, long_size: int = 512):
@@ -83,23 +89,40 @@ class model_factory:
mixed_precision_transformer = False
):
self.device = torch.device(f"cuda")
+ self._interrupt = False
self.VAE_dtype = VAE_dtype
self.dtype = dtype
torch_device = "cpu"
+ self.model_def = model_def
+ self.name = model_def.get("flux-model", "flux-dev")
self.guidance_max_phases = model_def.get("guidance_max_phases", 0)
+ self.is_flux2 = self.name.startswith("flux2")
# model_filename = ["c:/temp/flux1-schnell.safetensors"]
-
- self.t5 = load_t5(torch_device, text_encoder_filename, max_length=512)
- self.clip = load_clip(torch_device)
- self.name = model_def.get("flux-model", "flux-dev")
- # self.name= "flux-dev-kontext"
- # self.name= "flux-dev"
- # self.name= "flux-schnell"
- source = model_def.get("source", None)
- self.model = load_flow_model(self.name, model_filename[0] if source is None else source, torch_device)
- self.model_def = model_def
- self.vae = None if getattr(self.model, "radiance", False) else load_ae(self.name, device=torch_device)
+ source = model_def.get("source", None)
+ self.clip = self.t5 = self.vision_encoder = self.mistal = None
+ if self.is_flux2:
+ self.model = load_flow_model(self.name, model_filename[0] if source is None else source, torch_device)
+
+ from .modules.text_encoder_mistral import Mistral3SmallEmbedder
+ self.mistral = Mistral3SmallEmbedder( model_spec = text_encoder_filename)
+
+ with torch.device("meta"):
+ self.vae = AutoencoderKLFlux2(AutoEncoderParamsFlux2())
+
+ offload.load_model_data(self.vae, fl.locate_file("flux2_vae.safetensors"), writable_tensors= False, )
+ self.vae_scale_factor = 8
+ else:
+ self.t5 = load_t5(torch_device, text_encoder_filename, max_length=512)
+ self.clip = load_clip(torch_device)
+ self.name = model_def.get("flux-model", "flux-dev")
+ # self.name= "flux-dev-kontext"
+ # self.name= "flux-dev"
+ # self.name= "flux-schnell"
+ source = model_def.get("source", None)
+ self.model = load_flow_model(self.name, model_filename[0] if source is None else source, torch_device)
+ self.model_def = model_def
+ self.vae = None if getattr(self.model, "radiance", False) else load_ae(self.name, device=torch_device)
siglip_processor = siglip_model = feature_embedder = None
if self.name == 'flux-dev-uso':
@@ -138,7 +161,12 @@ class model_factory:
from wgp import save_quantized_model
save_quantized_model(self.model, model_type, model_filename[0], dtype, None)
- split_linear_modules_map = get_linear_split_map()
+ split_linear_modules_map = get_linear_split_map(
+ self.model.hidden_size,
+ getattr(self.model.params, "mlp_ratio", 4.0),
+ getattr(self.model.params, "single_linear1_mlp_ratio", None),
+ getattr(self.model.params, "double_linear1_mlp_ratio", None),
+ )
self.model.split_linear_modules_map = split_linear_modules_map
offload.split_linear_modules(self.model, split_linear_modules_map )
@@ -202,118 +230,146 @@ class model_factory:
joint_pass = False,
image_refs_relative_size = 100,
denoising_strength = 1.,
- masking_strength = 1.,
- **bbargs
+ masking_strength = 1.,
+ **bbargs
):
if self._interrupt:
return None
+ device="cuda"
+ flux2 = self.is_flux2
+ if flux2:
+ guide_scale = 1.0
if self.guidance_max_phases < 1: guide_scale = 1
if n_prompt is None or len(n_prompt) == 0: n_prompt = "low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors"
- device="cuda"
flux_dev_uso = self.name in ['flux-dev-uso']
flux_dev_umo = self.name in ['flux-dev-umo']
radiance = self.name in ['flux-chroma-radiance']
flux_kontext_dreamomni2 = self.name in ['flux-dev-kontext-dreamomni2']
- latent_stiching = flux_dev_uso or flux_dev_umo or flux_kontext_dreamomni2
- lock_dimensions= False
-
- input_ref_images = [] if input_ref_images is None else input_ref_images[:]
- if flux_dev_umo:
- ref_long_side = 512 if len(input_ref_images) <= 1 else 320
- input_ref_images = [preprocess_ref(img, ref_long_side) for img in input_ref_images]
- lock_dimensions = True
-
- elif flux_kontext_dreamomni2:
- for i, img in enumerate(input_ref_images):
- input_ref_images[i] = resizeinput(img)
- input_prompt= self.infer_vlm(input_ref_images,input_prompt, " It is editing task." if "K" in video_prompt_type else " It is generation task." )
- input_prompt = input_prompt[6:-7]
- print(input_prompt)
- lock_dimensions = True
-
- ref_style_imgs = []
- if "I" in video_prompt_type and len(input_ref_images) > 0:
- if flux_dev_uso :
- if "J" in video_prompt_type:
- ref_style_imgs = input_ref_images
- input_ref_images = []
- elif len(input_ref_images) > 1 :
- ref_style_imgs = input_ref_images[-1:]
- input_ref_images = input_ref_images[:-1]
-
- if latent_stiching:
- # latents stiching with resize
- if not lock_dimensions :
- for i in range(len(input_ref_images)):
- w, h = input_ref_images[i].size
- image_height, image_width = calculate_new_dimensions(int(height*image_refs_relative_size/100), int(width*image_refs_relative_size/100), h, w, 0)
- input_ref_images[i] = input_ref_images[i].resize((image_width, image_height), resample=Image.Resampling.LANCZOS)
- else:
- # image stiching method
- stiched = input_ref_images[0]
- for new_img in input_ref_images[1:]:
- stiched = stitch_images(stiched, new_img)
- input_ref_images = [stiched]
- elif input_frames is not None:
- input_ref_images = [convert_tensor_to_image(input_frames) ]
- else:
- input_ref_images = None
- image_mask = None if input_masks is None else convert_tensor_to_image(input_masks, mask_levels= True)
-
- noise_patch_size = self.model.patch_size if radiance else 2
- noise_channels = self.model.out_channels if radiance else 16
-
- if latent_stiching :
- inp, height, width = prepare_multi_ip(
- ae=self.vae,
- img_cond_list=input_ref_images,
- target_width=width,
- target_height=height,
- bs=batch_size,
- seed=seed,
- device=device,
- res_match_output= flux_dev_uso or flux_dev_umo,
- pe = 'w' if flux_kontext_dreamomni2 else 'd',
- set_cond_index = flux_kontext_dreamomni2,
- conditions_zero_start= flux_kontext_dreamomni2
- )
- else:
- inp, height, width = prepare_kontext(
- ae=self.vae,
- img_cond_list=input_ref_images,
- target_width=width,
- target_height=height,
- bs=batch_size,
- seed=seed,
- device=device,
- img_mask=image_mask,
- patch_size=noise_patch_size,
- noise_channels=noise_channels,
- )
-
- radiance_cache = None
- inp.update(prepare_prompt(self.t5, self.clip, batch_size, input_prompt))
- if guide_scale != 1:
- inp.update(prepare_prompt(self.t5, self.clip, batch_size, n_prompt, neg = True, device=device))
+ if flux2:
+ shape = (batch_size, 128, height // 16, width // 16)
+ generator = torch.Generator(device="cuda").manual_seed(seed)
+ randn = torch.randn(shape, generator=generator, dtype=torch.bfloat16, device="cuda")
+ img, img_ids = batched_prc_img(randn)
+ ctx = self.mistral([input_prompt]).to(torch.bfloat16)
+ txt_embeds, txt_ids = batched_prc_txt(ctx)
+ txt_embeds, txt_ids = txt_embeds.expand(batch_size, -1, -1), txt_ids.expand(batch_size, -1, -1)
+ vec = torch.zeros(batch_size, 1, device=device, dtype=self.dtype)
+ inp = { "img": img, "img_ids": img_ids, "txt": txt_embeds.to(device), "txt_ids": txt_ids.to(device), "vec": vec }
+ if guide_scale != 1:
+ ctx = self.mistral([n_prompt]).to(torch.bfloat16)
+ txt_embeds, txt_ids = batched_prc_txt(ctx)
+ txt_embeds, txt_ids = txt_embeds.expand(batch_size, -1, -1), txt_ids.expand(batch_size, -1, -1)
+ inp.update({ "neg_txt": txt_embeds.to(device), "neg_txt_ids": txt_ids.to(device), "neg_vec": vec })
+
+ if input_ref_images is not None and len(input_ref_images):
+ cond_latents, cond_ids = encode_image_refs(self.vae, input_ref_images)
+ inp.update({"img_cond_seq": cond_latents, "img_cond_seq_ids": cond_ids})
+
+ noise_patch_size = 2
+ timesteps = get_schedule_flux2(sampling_steps, inp["img"].shape[1])
+ unpack_latent = lambda x : self.vae.pre_decode(torch.cat(scatter_ids(x, inp["img_ids"])).squeeze(2))
+ ref_style_imgs = []
+ image_mask = None
- timesteps = get_schedule(sampling_steps, inp["img"].shape[1], shift=(self.name != "flux-schnell"))
-
- ref_style_imgs = [self.vision_encoder_processor(img, return_tensors="pt").to(self.device) for img in ref_style_imgs]
- if self.feature_embedder is not None and ref_style_imgs is not None and len(ref_style_imgs) > 0 and self.vision_encoder is not None:
- # processing style feat into textural hidden space
- siglip_embedding = [self.vision_encoder(**emb, output_hidden_states=True) for emb in ref_style_imgs]
- siglip_embedding = torch.cat([self.feature_embedder(emb) for emb in siglip_embedding], dim=1)
- siglip_embedding_ids = torch.zeros( siglip_embedding.shape[0], siglip_embedding.shape[1], 3 ).to(device)
- inp["siglip_embedding"] = siglip_embedding
- inp["siglip_embedding_ids"] = siglip_embedding_ids
-
- if radiance:
- def unpack_latent(x):
- return patches_to_image(x.float(), height, width, noise_patch_size)
else:
- def unpack_latent(x):
- return unpack(x.float(), height, width)
+ latent_stiching = flux_dev_uso or flux_dev_umo or flux_kontext_dreamomni2
+ lock_dimensions= False
+ input_ref_images = [] if input_ref_images is None else input_ref_images[:]
+ if flux_dev_umo:
+ ref_long_side = 512 if len(input_ref_images) <= 1 else 320
+ input_ref_images = [preprocess_ref(img, ref_long_side) for img in input_ref_images]
+ lock_dimensions = True
+
+ elif flux_kontext_dreamomni2:
+ for i, img in enumerate(input_ref_images):
+ input_ref_images[i] = resizeinput(img)
+ input_prompt= self.infer_vlm(input_ref_images,input_prompt, " It is editing task." if "K" in video_prompt_type else " It is generation task." )
+ input_prompt = input_prompt[6:-7]
+ print(input_prompt)
+ lock_dimensions = True
+
+ ref_style_imgs = []
+ if "I" in video_prompt_type and len(input_ref_images) > 0:
+ if flux_dev_uso :
+ if "J" in video_prompt_type:
+ ref_style_imgs = input_ref_images
+ input_ref_images = []
+ elif len(input_ref_images) > 1 :
+ ref_style_imgs = input_ref_images[-1:]
+ input_ref_images = input_ref_images[:-1]
+
+ if latent_stiching:
+ # latents stiching with resize
+ if not lock_dimensions :
+ for i in range(len(input_ref_images)):
+ w, h = input_ref_images[i].size
+ image_height, image_width = calculate_new_dimensions(int(height*image_refs_relative_size/100), int(width*image_refs_relative_size/100), h, w, 0)
+ input_ref_images[i] = input_ref_images[i].resize((image_width, image_height), resample=Image.Resampling.LANCZOS)
+ else:
+ # image stiching method
+ stiched = input_ref_images[0]
+ for new_img in input_ref_images[1:]:
+ stiched = stitch_images(stiched, new_img)
+ input_ref_images = [stiched]
+ elif input_frames is not None:
+ input_ref_images = [convert_tensor_to_image(input_frames) ]
+ else:
+ input_ref_images = None
+ image_mask = None if input_masks is None else convert_tensor_to_image(input_masks, mask_levels= True)
+
+ noise_patch_size = self.model.patch_size if radiance else 2
+ noise_channels = self.model.out_channels if radiance else 16
+
+ if latent_stiching :
+ inp, height, width = prepare_multi_ip(
+ ae=self.vae,
+ img_cond_list=input_ref_images,
+ target_width=width,
+ target_height=height,
+ bs=batch_size,
+ seed=seed,
+ device=device,
+ res_match_output= flux_dev_uso or flux_dev_umo,
+ pe = 'w' if flux_kontext_dreamomni2 else 'd',
+ set_cond_index = flux_kontext_dreamomni2,
+ conditions_zero_start= flux_kontext_dreamomni2
+ )
+ else:
+ inp, height, width = prepare_kontext(
+ ae=self.vae,
+ img_cond_list=input_ref_images,
+ target_width=width,
+ target_height=height,
+ bs=batch_size,
+ seed=seed,
+ device=device,
+ img_mask=image_mask,
+ patch_size=noise_patch_size,
+ noise_channels=noise_channels,
+ )
+
+ inp.update(prepare_prompt(self.t5, self.clip, batch_size, input_prompt))
+ if guide_scale != 1:
+ inp.update(prepare_prompt(self.t5, self.clip, batch_size, n_prompt, neg = True, device=device))
+
+ timesteps = get_schedule(sampling_steps, inp["img"].shape[1], shift=(self.name != "flux-schnell"))
+
+ ref_style_imgs = [self.vision_encoder_processor(img, return_tensors="pt").to(self.device) for img in ref_style_imgs]
+ if self.feature_embedder is not None and ref_style_imgs is not None and len(ref_style_imgs) > 0 and self.vision_encoder is not None:
+ # processing style feat into textural hidden space
+ siglip_embedding = [self.vision_encoder(**emb, output_hidden_states=True) for emb in ref_style_imgs]
+ siglip_embedding = torch.cat([self.feature_embedder(emb) for emb in siglip_embedding], dim=1)
+ siglip_embedding_ids = torch.zeros( siglip_embedding.shape[0], siglip_embedding.shape[1], 3 ).to(device)
+ inp["siglip_embedding"] = siglip_embedding
+ inp["siglip_embedding_ids"] = siglip_embedding_ids
+
+ if radiance:
+ def unpack_latent(x):
+ return patches_to_image(x.float(), height, width, noise_patch_size)
+ else:
+ def unpack_latent(x):
+ return unpack(x.float(), height, width)
# denoise initial noise
x = denoise(
@@ -329,7 +385,6 @@ class model_factory:
joint_pass=joint_pass,
denoising_strength=denoising_strength,
masking_strength=masking_strength,
- radiance_cache=radiance_cache,
)
if x==None: return None
# decode latents to pixel space
@@ -338,7 +393,7 @@ class model_factory:
with torch.autocast(device_type=device, dtype=torch.bfloat16):
x = self.vae.decode(x)
- if image_mask is not None and masking_strength == 1:
+ if image_mask is not None and masking_strength == 1 and not flux2:
img_msk_rebuilt = inp["img_msk_rebuilt"]
img= input_frames.squeeze(1).unsqueeze(0) # convert_image_to_tensor(image_guide)
x = img * (1 - img_msk_rebuilt) + x.to(img) * img_msk_rebuilt
@@ -353,4 +408,4 @@ class model_factory:
preloadURLs = get_model_recursive_prop(model_type, "preload_URLs")
if len(preloadURLs) < 2: return [], []
edit = "K" in video_prompt_type
- return [ fl.locate_file(os.path.basename(preloadURLs[0 if edit else 1]))] , [1]
\ No newline at end of file
+ return [ fl.locate_file(os.path.basename(preloadURLs[0 if edit else 1]))] , [1]
diff --git a/models/flux/model.py b/models/flux/model.py
index 0cc86fd..c83b709 100644
--- a/models/flux/model.py
+++ b/models/flux/model.py
@@ -7,8 +7,10 @@ import torch.nn.functional as F
from .modules.layers import (
DoubleStreamBlock,
EmbedND,
+ EmbedNDFlux2,
LastLayer,
MLPEmbedder,
+ Modulation,
SingleStreamBlock,
timestep_embedding,
DistilledGuidance,
@@ -44,6 +46,11 @@ class FluxParams:
radiance_max_freqs: int = 8
radiance_tile_size: int = 0
radiance_final_head_type: str = "conv"
+ single_linear1_mlp_ratio: float | None = None
+ single_mlp_hidden_ratio: float | None = None
+ double_mlp_ratio: float | None = None
+ double_linear1_mlp_ratio: float | None = None
+ flux2: bool = False
class Flux(nn.Module):
"""
@@ -83,6 +90,7 @@ class Flux(nn.Module):
self.in_channels = params.in_channels
self.out_channels = params.out_channels
self.chroma = params.chroma
+ self.is_flux2 = getattr(params, "flux2", False)
self.radiance = getattr(params, "radiance", False)
if params.hidden_size % params.num_heads != 0:
raise ValueError(
@@ -93,17 +101,28 @@ class Flux(nn.Module):
raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
self.hidden_size = params.hidden_size
self.num_heads = params.num_heads
- self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
+
+ if self.is_flux2:
+ self.pe_embedder = EmbedNDFlux2(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
+ else:
+ self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
+
self.img_in = (
nn.Identity()
if self.radiance
- else nn.Linear(self.in_channels, self.hidden_size, bias=True)
+ else nn.Linear(self.in_channels, self.hidden_size, bias=not self.is_flux2)
)
self.guidance_in = (
- MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()
+ MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size, bias=not self.is_flux2)
+ if params.guidance_embed
+ else None
)
- self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
+ self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size, bias=not self.is_flux2)
+ if self.is_flux2:
+ self.double_stream_modulation_img = Modulation(self.hidden_size, double=True, bias=False)
+ self.double_stream_modulation_txt = Modulation(self.hidden_size, double=True, bias=False)
+ self.single_stream_modulation = Modulation(self.hidden_size, double=False, bias=False)
if self.chroma:
self.distilled_guidance_layer = DistilledGuidance(
in_dim=64,
@@ -112,8 +131,8 @@ class Flux(nn.Module):
n_layers=5,
)
else:
- self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)
- self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size)
+ self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size, bias=not self.is_flux2)
+ self.vector_in = MLPEmbedder(params.vec_in_dim, self.hidden_size, bias=not self.is_flux2) if not self.is_flux2 else nn.Identity()
self.double_blocks = nn.ModuleList(
[
@@ -121,8 +140,13 @@ class Flux(nn.Module):
self.hidden_size,
self.num_heads,
mlp_ratio=params.mlp_ratio,
+ double_mlp_ratio=getattr(params, "double_mlp_ratio", None),
+ double_linear1_mlp_ratio=getattr(params, "double_linear1_mlp_ratio", None),
+ mod_bias=not self.is_flux2,
+ mlp_bias=not self.is_flux2,
+ proj_bias=not self.is_flux2,
qkv_bias=params.qkv_bias,
- chroma_modulation = self.chroma,
+ shared_modulation = self.chroma or self.is_flux2,
)
for _ in range(params.depth)
]
@@ -130,7 +154,17 @@ class Flux(nn.Module):
self.single_blocks = nn.ModuleList(
[
- SingleStreamBlock(self.hidden_size, self.num_heads, mlp_ratio=params.mlp_ratio, chroma_modulation = self.chroma)
+ SingleStreamBlock(
+ self.hidden_size,
+ self.num_heads,
+ mlp_ratio=params.mlp_ratio,
+ shared_modulation=self.chroma or self.is_flux2,
+ single_linear1_mlp_ratio=getattr(params, "single_linear1_mlp_ratio", None),
+ single_mlp_hidden_ratio=getattr(params, "single_mlp_hidden_ratio", None),
+ qk_scale=None,
+ linear_bias=not self.is_flux2,
+ modulation_bias=not self.is_flux2,
+ )
for _ in range(params.depth_single_blocks)
]
)
@@ -145,6 +179,8 @@ class Flux(nn.Module):
self.out_channels,
chroma_modulation=self.chroma,
use_linear=True,
+ linear_bias=not self.is_flux2,
+ modulation_bias=not self.is_flux2,
)
def _apply_final_layer(self, tokens: Tensor, vec):
@@ -263,7 +299,6 @@ class Flux(nn.Module):
pipeline =None,
siglip_embedding = None,
siglip_embedding_ids = None,
- radiance_cache: dict | None = None,
) -> Tensor:
sz = len(txt_list)
@@ -303,11 +338,12 @@ class Flux(nn.Module):
mod_vectors = self.distilled_guidance_layer(input_vec)
else:
vec = self.time_in(timestep_embedding(timesteps, 256))
- if self.params.guidance_embed:
+ if self.params.guidance_embed and self.guidance_in is not None:
if guidance is None:
raise ValueError("Didn't get guidance strength for guidance distilled model.")
vec += self.guidance_in(timestep_embedding(guidance, 256))
- vec_list = [ vec + self.vector_in(y) for y in y_list]
+ base_vec_list = [vec + self.vector_in(y) for y in y_list]
+ vec_list = base_vec_list
img = None
txt_list = [self.txt_in(txt) for txt in txt_list ]
@@ -317,8 +353,14 @@ class Flux(nn.Module):
pe_list = [self.pe_embedder(torch.cat((txt_ids, img_ids), dim=1)) for txt_ids in txt_ids_list]
+ if self.is_flux2:
+ double_vec_list = [ ( self.double_stream_modulation_img(base_vec_list[i]), self.double_stream_modulation_txt(base_vec_list[i]), ) for i in range(sz) ]
+
for i, block in enumerate(self.double_blocks):
- if self.chroma: vec_list = [( self.get_modulations(mod_vectors, "double_img", idx=i), self.get_modulations(mod_vectors, "double_txt", idx=i))] * sz
+ if self.chroma:
+ vec_list = [( self.get_modulations(mod_vectors, "double_img", idx=i), self.get_modulations(mod_vectors, "double_txt", idx=i))] * sz
+ elif self.is_flux2:
+ vec_list = double_vec_list
if callback != None:
callback(-1, None, False, True)
if pipeline._interrupt:
@@ -329,8 +371,15 @@ class Flux(nn.Module):
img_list = [torch.cat((txt, img), 1) for txt, img in zip(txt_list, img_list)]
+ if self.is_flux2:
+ single_vec_list = [self.single_stream_modulation(base_vec_list[i])[0] for i in range(sz)]
+
for i, block in enumerate(self.single_blocks):
- if self.chroma: vec_list= [self.get_modulations(mod_vectors, "single", idx=i)] * sz
+ if self.chroma:
+ vec_list= [self.get_modulations(mod_vectors, "single", idx=i)] * sz
+ elif self.is_flux2:
+ vec_list = single_vec_list
+
if callback != None:
callback(-1, None, False, True)
if pipeline._interrupt:
@@ -345,7 +394,7 @@ class Flux(nn.Module):
elif self.chroma:
final_vecs = [self.get_modulations(mod_vectors, "final")] * sz
else:
- final_vecs = vec_list
+ final_vecs = base_vec_list
out_list = []
for i in range(sz):
hidden_seq = img_list[i]
diff --git a/models/flux/modules/autoencoder_flux2.py b/models/flux/modules/autoencoder_flux2.py
new file mode 100644
index 0000000..f93fa42
--- /dev/null
+++ b/models/flux/modules/autoencoder_flux2.py
@@ -0,0 +1,340 @@
+import math
+from dataclasses import dataclass, field
+
+import torch
+from einops import rearrange
+from torch import Tensor, nn
+
+
+@dataclass
+class AutoEncoderParamsFlux2:
+ resolution: int = 256
+ in_channels: int = 3
+ ch: int = 128
+ out_ch: int = 3
+ ch_mult: list[int] = field(default_factory=lambda: [1, 2, 4, 4])
+ num_res_blocks: int = 2
+ z_channels: int = 32
+
+
+def swish(x: Tensor) -> Tensor:
+ return x * torch.sigmoid(x)
+
+
+class AttnBlock(nn.Module):
+ def __init__(self, in_channels: int):
+ super().__init__()
+ self.in_channels = in_channels
+
+ self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
+
+ self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1)
+ self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1)
+ self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1)
+ self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1)
+
+ def attention(self, h_: Tensor) -> Tensor:
+ h_ = self.norm(h_)
+ q = self.q(h_)
+ k = self.k(h_)
+ v = self.v(h_)
+
+ b, c, h, w = q.shape
+ q = rearrange(q, "b c h w -> b 1 (h w) c").contiguous()
+ k = rearrange(k, "b c h w -> b 1 (h w) c").contiguous()
+ v = rearrange(v, "b c h w -> b 1 (h w) c").contiguous()
+ h_ = nn.functional.scaled_dot_product_attention(q, k, v)
+
+ return rearrange(h_, "b 1 (h w) c -> b c h w", h=h, w=w, c=c, b=b)
+
+ def forward(self, x: Tensor) -> Tensor:
+ return x + self.proj_out(self.attention(x))
+
+
+class ResnetBlock(nn.Module):
+ def __init__(self, in_channels: int, out_channels: int):
+ super().__init__()
+ self.in_channels = in_channels
+ out_channels = in_channels if out_channels is None else out_channels
+ self.out_channels = out_channels
+
+ self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
+ self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)
+ self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
+ if self.in_channels != self.out_channels:
+ self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
+
+ def forward(self, x):
+ h = x
+ h = self.norm1(h)
+ h = swish(h)
+ h = self.conv1(h)
+
+ h = self.norm2(h)
+ h = swish(h)
+ h = self.conv2(h)
+
+ if self.in_channels != self.out_channels:
+ x = self.nin_shortcut(x)
+
+ return x + h
+
+
+class Downsample(nn.Module):
+ def __init__(self, in_channels: int):
+ super().__init__()
+ # no asymmetric padding in torch conv, must do it ourselves
+ self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
+
+ def forward(self, x: Tensor):
+ pad = (0, 1, 0, 1)
+ x = nn.functional.pad(x, pad, mode="constant", value=0)
+ x = self.conv(x)
+ return x
+
+
+class Upsample(nn.Module):
+ def __init__(self, in_channels: int):
+ super().__init__()
+ self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
+
+ def forward(self, x: Tensor):
+ x = nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
+ x = self.conv(x)
+ return x
+
+
+class Encoder(nn.Module):
+ def __init__(
+ self,
+ resolution: int,
+ in_channels: int,
+ ch: int,
+ ch_mult: list[int],
+ num_res_blocks: int,
+ z_channels: int,
+ ):
+ super().__init__()
+ self.quant_conv = torch.nn.Conv2d(2 * z_channels, 2 * z_channels, 1)
+ self.ch = ch
+ self.num_resolutions = len(ch_mult)
+ self.num_res_blocks = num_res_blocks
+ self.resolution = resolution
+ self.in_channels = in_channels
+ # downsampling
+ self.conv_in = nn.Conv2d(in_channels, self.ch, kernel_size=3, stride=1, padding=1)
+
+ curr_res = resolution
+ in_ch_mult = (1,) + tuple(ch_mult)
+ self.in_ch_mult = in_ch_mult
+ self.down = nn.ModuleList()
+ block_in = self.ch
+ for i_level in range(self.num_resolutions):
+ block = nn.ModuleList()
+ attn = nn.ModuleList()
+ block_in = ch * in_ch_mult[i_level]
+ block_out = ch * ch_mult[i_level]
+ for _ in range(self.num_res_blocks):
+ block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))
+ block_in = block_out
+ down = nn.Module()
+ down.block = block
+ down.attn = attn
+ if i_level != self.num_resolutions - 1:
+ down.downsample = Downsample(block_in)
+ curr_res = curr_res // 2
+ self.down.append(down)
+
+ # middle
+ self.mid = nn.Module()
+ self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)
+ self.mid.attn_1 = AttnBlock(block_in)
+ self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
+
+ # end
+ self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
+ self.conv_out = nn.Conv2d(block_in, 2 * z_channels, kernel_size=3, stride=1, padding=1)
+
+ def forward(self, x: Tensor) -> Tensor:
+ # downsampling
+ hs = [self.conv_in(x)]
+ for i_level in range(self.num_resolutions):
+ for i_block in range(self.num_res_blocks):
+ h = self.down[i_level].block[i_block](hs[-1])
+ if len(self.down[i_level].attn) > 0:
+ h = self.down[i_level].attn[i_block](h)
+ hs.append(h)
+ if i_level != self.num_resolutions - 1:
+ hs.append(self.down[i_level].downsample(hs[-1]))
+
+ # middle
+ h = hs[-1]
+ h = self.mid.block_1(h)
+ h = self.mid.attn_1(h)
+ h = self.mid.block_2(h)
+ # end
+ h = self.norm_out(h)
+ h = swish(h)
+ h = self.conv_out(h)
+ h = self.quant_conv(h)
+ return h
+
+
+class Decoder(nn.Module):
+ def __init__(
+ self,
+ ch: int,
+ out_ch: int,
+ ch_mult: list[int],
+ num_res_blocks: int,
+ in_channels: int,
+ resolution: int,
+ z_channels: int,
+ ):
+ super().__init__()
+ self.post_quant_conv = torch.nn.Conv2d(z_channels, z_channels, 1)
+ self.ch = ch
+ self.num_resolutions = len(ch_mult)
+ self.num_res_blocks = num_res_blocks
+ self.resolution = resolution
+ self.in_channels = in_channels
+ self.ffactor = 2 ** (self.num_resolutions - 1)
+
+ # compute in_ch_mult, block_in and curr_res at lowest res
+ block_in = ch * ch_mult[self.num_resolutions - 1]
+ curr_res = resolution // 2 ** (self.num_resolutions - 1)
+ self.z_shape = (1, z_channels, curr_res, curr_res)
+
+ # z to block_in
+ self.conv_in = nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
+
+ # middle
+ self.mid = nn.Module()
+ self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)
+ self.mid.attn_1 = AttnBlock(block_in)
+ self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
+
+ # upsampling
+ self.up = nn.ModuleList()
+ for i_level in reversed(range(self.num_resolutions)):
+ block = nn.ModuleList()
+ attn = nn.ModuleList()
+ block_out = ch * ch_mult[i_level]
+ for _ in range(self.num_res_blocks + 1):
+ block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))
+ block_in = block_out
+ up = nn.Module()
+ up.block = block
+ up.attn = attn
+ if i_level != 0:
+ up.upsample = Upsample(block_in)
+ curr_res = curr_res * 2
+ self.up.insert(0, up) # prepend to get consistent order
+
+ # end
+ self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
+ self.conv_out = nn.Conv2d(block_in, out_ch, kernel_size=3, stride=1, padding=1)
+
+ def forward(self, z: Tensor) -> Tensor:
+ z = self.post_quant_conv(z)
+
+ # get dtype for proper tracing
+ upscale_dtype = next(self.up.parameters()).dtype
+
+ # z to block_in
+ h = self.conv_in(z)
+
+ # middle
+ h = self.mid.block_1(h)
+ h = self.mid.attn_1(h)
+ h = self.mid.block_2(h)
+
+ # cast to proper dtype
+ h = h.to(upscale_dtype)
+ # upsampling
+ for i_level in reversed(range(self.num_resolutions)):
+ for i_block in range(self.num_res_blocks + 1):
+ h = self.up[i_level].block[i_block](h)
+ if len(self.up[i_level].attn) > 0:
+ h = self.up[i_level].attn[i_block](h)
+ if i_level != 0:
+ h = self.up[i_level].upsample(h)
+
+ # end
+ h = self.norm_out(h)
+ h = swish(h)
+ h = self.conv_out(h)
+ return h
+
+
+class AutoencoderKLFlux2(nn.Module):
+ def __init__(self, params: AutoEncoderParamsFlux2):
+ super().__init__()
+ self.params = params
+ self.encoder = Encoder(
+ resolution=params.resolution,
+ in_channels=params.in_channels,
+ ch=params.ch,
+ ch_mult=params.ch_mult,
+ num_res_blocks=params.num_res_blocks,
+ z_channels=params.z_channels,
+ )
+ self.decoder = Decoder(
+ resolution=params.resolution,
+ in_channels=params.in_channels,
+ ch=params.ch,
+ out_ch=params.out_ch,
+ ch_mult=params.ch_mult,
+ num_res_blocks=params.num_res_blocks,
+ z_channels=params.z_channels,
+ )
+
+ self.bn_eps = 1e-4
+ self.bn_momentum = 0.1
+ self.ps = [2, 2]
+ self.bn = torch.nn.BatchNorm2d(
+ math.prod(self.ps) * params.z_channels,
+ eps=self.bn_eps,
+ momentum=self.bn_momentum,
+ affine=False,
+ track_running_stats=True,
+ )
+
+ def normalize(self, z):
+ self.bn.eval()
+ return self.bn(z)
+
+ def inv_normalize(self, z):
+ self.bn.eval()
+ s = torch.sqrt(self.bn.running_var.view(1, -1, 1, 1) + self.bn_eps)
+ m = self.bn.running_mean.view(1, -1, 1, 1)
+ return z * s.to(z) + m.to(z)
+
+ def encode(self, x: Tensor) -> Tensor:
+ moments = self.encoder(x)
+ mean = torch.chunk(moments, 2, dim=1)[0]
+
+ z = rearrange(
+ mean,
+ "... c (i pi) (j pj) -> ... (c pi pj) i j",
+ pi=self.ps[0],
+ pj=self.ps[1],
+ )
+ z = self.normalize(z)
+ return z
+
+ def pre_decode(self, z: Tensor) -> Tensor:
+ z = self.inv_normalize(z)
+ z = rearrange(
+ z,
+ "... (c pi pj) i j -> ... c (i pi) (j pj)",
+ pi=self.ps[0],
+ pj=self.ps[1],
+ )
+ return z
+
+ def decode(self, z: Tensor) -> Tensor:
+
+ dec = self.decoder(z)
+ return dec
diff --git a/models/flux/modules/layers.py b/models/flux/modules/layers.py
index 1af382c..c9f8a69 100644
--- a/models/flux/modules/layers.py
+++ b/models/flux/modules/layers.py
@@ -7,13 +7,29 @@ from torch import Tensor, nn
from ..math import attention, rope
-def get_linear_split_map():
- hidden_size = 3072
- split_linear_modules_map = {
- "qkv" : {"mapped_modules" : ["q", "k", "v"] , "split_sizes": [hidden_size, hidden_size, hidden_size]},
- "linear1" : {"mapped_modules" : ["linear1_attn_q", "linear1_attn_k", "linear1_attn_v", "linear1_mlp"] , "split_sizes": [hidden_size, hidden_size, hidden_size, 7*hidden_size- 3*hidden_size]},
- "linear1_qkv" : {"mapped_modules" : ["linear1_attn_q", "linear1_attn_k", "linear1_attn_v"] , "split_sizes": [hidden_size, hidden_size, hidden_size]},
- }
+def get_linear_split_map(
+ hidden_size: int = 3072,
+ mlp_ratio: float = 4.0,
+ single_linear1_mlp_ratio: float | None = None,
+ linear1_mlp_ratio: float | None = None,
+):
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
+ if linear1_mlp_ratio is None and mlp_ratio == 3.0:
+ lin1_ratio = mlp_ratio * 2
+ else:
+ lin1_ratio = linear1_mlp_ratio if linear1_mlp_ratio is not None else mlp_ratio
+ lin1_mlp = int(hidden_size * (single_linear1_mlp_ratio if single_linear1_mlp_ratio is not None else lin1_ratio))
+ split_linear_modules_map = {
+ "qkv": {"mapped_modules": ["q", "k", "v"], "split_sizes": [hidden_size, hidden_size, hidden_size]},
+ "linear1": {
+ "mapped_modules": ["linear1_attn_q", "linear1_attn_k", "linear1_attn_v", "linear1_mlp"],
+ "split_sizes": [hidden_size, hidden_size, hidden_size, lin1_mlp],
+ },
+ "linear1_qkv": {
+ "mapped_modules": ["linear1_attn_q", "linear1_attn_k", "linear1_attn_v"],
+ "split_sizes": [hidden_size, hidden_size, hidden_size],
+ },
+ }
return split_linear_modules_map
@@ -33,6 +49,21 @@ class EmbedND(nn.Module):
return emb.unsqueeze(1)
+class EmbedNDFlux2(nn.Module):
+ def __init__(self, dim: int, theta: int, axes_dim: list[int]):
+ super().__init__()
+ self.dim = dim
+ self.theta = theta
+ self.axes_dim = axes_dim
+
+ def forward(self, ids: Tensor) -> Tensor:
+ emb = torch.cat(
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(len(self.axes_dim))],
+ dim=-3,
+ )
+
+ return emb.unsqueeze(1)
+
def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):
"""
@@ -59,11 +90,11 @@ def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 10
class MLPEmbedder(nn.Module):
- def __init__(self, in_dim: int, hidden_dim: int):
+ def __init__(self, in_dim: int, hidden_dim: int, bias: bool = True):
super().__init__()
- self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=bias)
self.silu = nn.SiLU()
- self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=bias)
def forward(self, x: Tensor) -> Tensor:
return self.out_layer(self.silu(self.in_layer(x)))
@@ -99,14 +130,14 @@ class QKNorm(torch.nn.Module):
class SelfAttention(nn.Module):
- def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False):
+ def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False, proj_bias: bool = True):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.norm = QKNorm(head_dim)
- self.proj = nn.Linear(dim, dim)
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
def forward(self, x: Tensor, pe: Tensor) -> Tensor:
raise Exception("not implemented")
@@ -140,11 +171,11 @@ def split_mlp(mlp, x, divide = 8):
return x.reshape(x_shape)
class Modulation(nn.Module):
- def __init__(self, dim: int, double: bool):
+ def __init__(self, dim: int, double: bool, bias: bool = True):
super().__init__()
self.is_double = double
self.multiplier = 6 if double else 3
- self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)
+ self.lin = nn.Linear(dim, self.multiplier * dim, bias=bias)
def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:
out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)
@@ -154,41 +185,68 @@ class Modulation(nn.Module):
ModulationOut(*out[3:]) if self.is_double else None,
)
+class SiLUActivation(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.gate_fn = nn.SiLU()
+
+ def forward(self, x: Tensor) -> Tensor:
+ x1, x2 = x.chunk(2, dim=-1)
+ return self.gate_fn(x1) * x2
+
class DoubleStreamBlock(nn.Module):
- def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False, chroma_modulation = False):
+ def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False, shared_modulation = False, double_mlp_ratio: float | None = None, double_linear1_mlp_ratio: float | None = None, mod_bias: bool = True, mlp_bias: bool = True, proj_bias: bool = True):
super().__init__()
-
- mlp_hidden_dim = int(hidden_size * mlp_ratio)
+ lin1_ratio = double_linear1_mlp_ratio
+ if lin1_ratio is None:
+ base_ratio = double_mlp_ratio if double_mlp_ratio is not None else mlp_ratio
+ lin1_ratio = base_ratio * 2 if base_ratio == 3.0 else base_ratio
+ mlp_hidden_dim = int(hidden_size * (double_mlp_ratio if double_mlp_ratio is not None else mlp_ratio))
+ lin1_mlp_dim = int(hidden_size * lin1_ratio)
self.num_heads = num_heads
self.hidden_size = hidden_size
- self.chroma_modulation = chroma_modulation
- if not chroma_modulation:
- self.img_mod = Modulation(hidden_size, double=True)
+ self.shared_modulation = shared_modulation
+ if not shared_modulation:
+ self.img_mod = Modulation(hidden_size, double=True, bias=mod_bias)
self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
- self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
+ self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, proj_bias=proj_bias)
self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
- self.img_mlp = nn.Sequential(
- nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
- nn.GELU(approximate="tanh"),
- nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
- )
-
- if not chroma_modulation:
- self.txt_mod = Modulation(hidden_size, double=True)
+ if double_linear1_mlp_ratio is not None:
+ self.img_mlp = nn.Sequential(
+ nn.Linear(hidden_size, lin1_mlp_dim, bias=mlp_bias),
+ SiLUActivation(),
+ nn.Linear(lin1_mlp_dim // 2, hidden_size, bias=mlp_bias),
+ )
+ else:
+ self.img_mlp = nn.Sequential(
+ nn.Linear(hidden_size, lin1_mlp_dim, bias=mlp_bias),
+ nn.GELU(approximate="tanh"),
+ nn.Linear(mlp_hidden_dim, hidden_size, bias=mlp_bias),
+ )
+
+ if not shared_modulation:
+ self.txt_mod = Modulation(hidden_size, double=True, bias=mod_bias)
self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
- self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias)
+ self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, proj_bias=proj_bias)
self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
- self.txt_mlp = nn.Sequential(
- nn.Linear(hidden_size, mlp_hidden_dim, bias=True),
- nn.GELU(approximate="tanh"),
- nn.Linear(mlp_hidden_dim, hidden_size, bias=True),
- )
+ if double_linear1_mlp_ratio is not None:
+ self.txt_mlp = nn.Sequential(
+ nn.Linear(hidden_size, lin1_mlp_dim, bias=mlp_bias),
+ SiLUActivation(),
+ nn.Linear(lin1_mlp_dim // 2, hidden_size, bias=mlp_bias),
+ )
+ else:
+ self.txt_mlp = nn.Sequential(
+ nn.Linear(hidden_size, lin1_mlp_dim, bias=mlp_bias),
+ nn.GELU(approximate="tanh"),
+ nn.Linear(mlp_hidden_dim, hidden_size, bias=mlp_bias),
+ )
def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
- if self.chroma_modulation:
+ if self.shared_modulation:
(img_mod1, img_mod2), (txt_mod1, txt_mod2) = vec
else:
img_mod1, img_mod2 = self.img_mod(vec)
@@ -266,34 +324,44 @@ class SingleStreamBlock(nn.Module):
num_heads: int,
mlp_ratio: float = 4.0,
qk_scale: float | None = None,
- chroma_modulation = False,
+ shared_modulation = False,
+ single_linear1_mlp_ratio: float | None = None,
+ single_mlp_hidden_ratio: float | None = None,
+ linear_bias: bool = True,
+ modulation_bias: bool = True,
):
super().__init__()
self.hidden_dim = hidden_size
self.num_heads = num_heads
- self.chroma_modulation = chroma_modulation
+ self.shared_modulation = shared_modulation
head_dim = hidden_size // num_heads
self.scale = qk_scale or head_dim**-0.5
-
- self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
+ lin1_mlp_dim = int(hidden_size * (single_linear1_mlp_ratio if single_linear1_mlp_ratio is not None else mlp_ratio))
+ self.use_silu = single_linear1_mlp_ratio is not None
+ if self.use_silu:
+ self.mlp_hidden_dim = lin1_mlp_dim // 2
+ else:
+ self.mlp_hidden_dim = int(hidden_size * (single_mlp_hidden_ratio if single_mlp_hidden_ratio is not None else mlp_ratio))
# qkv and mlp_in
- self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
+ self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + lin1_mlp_dim, bias=linear_bias)
# proj and mlp_out
- self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
+ self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size, bias=linear_bias)
self.norm = QKNorm(head_dim)
self.hidden_size = hidden_size
self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
- self.mlp_act = nn.GELU(approximate="tanh")
- if not chroma_modulation:
- self.modulation = Modulation(hidden_size, double=False)
+ self.mlp_act = SiLUActivation() if self.use_silu else nn.GELU(approximate="tanh")
+ if not shared_modulation:
+ self.modulation = Modulation(hidden_size, double=False, bias=modulation_bias)
+ else:
+ self.modulation = None
def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
- if self.chroma_modulation:
+ if self.shared_modulation:
mod = vec
- else:
+ elif self.modulation is not None:
mod, _ = self.modulation(vec)
x_mod = self.pre_norm(x)
x_mod.mul_(1 + mod.scale)
@@ -345,18 +413,23 @@ class LastLayer(nn.Module):
out_channels: int,
chroma_modulation: bool = False,
use_linear: bool = True,
+ linear_bias: bool = True,
+ modulation_bias: bool = True,
):
super().__init__()
self.chroma_modulation = chroma_modulation
self.use_linear = use_linear
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = (
- nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
+ nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=linear_bias)
if use_linear
else None
)
if not chroma_modulation:
- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=modulation_bias)
+ )
+
def forward(self, x: Tensor, vec: Tensor) -> Tensor:
if self.chroma_modulation:
@@ -367,8 +440,6 @@ class LastLayer(nn.Module):
shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)
# x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]
x = torch.addcmul(shift[:, None, :], 1 + scale[:, None, :], self.norm_final(x))
- if self.linear is None:
- raise RuntimeError("LastLayer.linear is disabled for this configuration.")
x = self.linear(x)
return x
diff --git a/models/flux/modules/system_messages.py b/models/flux/modules/system_messages.py
new file mode 100644
index 0000000..c6d4ad5
--- /dev/null
+++ b/models/flux/modules/system_messages.py
@@ -0,0 +1,82 @@
+SYSTEM_MESSAGE = """You are an AI that reasons about image descriptions. You give structured responses focusing on object relationships, object
+attribution and actions without speculation."""
+
+SYSTEM_MESSAGE_UPSAMPLING_T2I = """You are an expert prompt engineer for FLUX.2 by Black Forest Labs. Rewrite user prompts to be more descriptive while strictly preserving their core subject and intent.
+
+Guidelines:
+1. Structure: Keep structured inputs structured (enhance within fields). Convert natural language to detailed paragraphs.
+2. Details: Add concrete visual specifics - form, scale, textures, materials, lighting (quality, direction, color), shadows, spatial relationships, and environmental context.
+3. Text in Images: Put ALL text in quotation marks, matching the prompt's language. Always provide explicit quoted text for objects that would contain text in reality (signs, labels, screens, etc.) - without it, the model generates gibberish.
+
+Output only the revised prompt and nothing else."""
+
+SYSTEM_MESSAGE_UPSAMPLING_I2I = """You are FLUX.2 by Black Forest Labs, an image-editing expert. You convert editing requests into one concise instruction (50-80 words, ~30 for brief requests).
+
+Rules:
+- Single instruction only, no commentary
+- Use clear, analytical language (avoid "whimsical," "cascading," etc.)
+- Specify what changes AND what stays the same (face, lighting, composition)
+- Reference actual image elements
+- Turn negatives into positives ("don't change X" → "keep X")
+- Make abstractions concrete ("futuristic" → "glowing cyan neon, metallic panels")
+- Keep content PG-13
+
+Output only the final instruction in plain text and nothing else."""
+
+
+SYSTEM_PROMPT_CONTENT_FILTER = """
+You are Mistral Small 3, a Large Language Model (LLM) created by Mistral AI, a French startup headquartered in Paris.
+Your task is identifying images and text for copyright concerns and depictions of public personas.
+"""
+
+PROMPT_IMAGE_INTEGRITY = """
+Task: Analyze an image to identify potential copyright concerns or depictions of public figures.
+
+Output: Respond with only "yes" or "no"
+
+Criteria for "yes":
+- The image contains a recognizable character from copyrighted media (movies, TV, comics, games, etc.)
+- The image displays a trademarked logo or brand
+- The image depicts a recognizable public figure (celebrities, politicians, athletes, influencers, historical figures, etc.)
+
+Criteria for "no":
+- All other cases
+- When you cannot identify the specific copyrighted work or named individual
+
+Critical Requirements:
+1. You must be able to name the exact copyrighted work or specific person depicted
+2. General references to demographics or characteristics are not sufficient
+3. Base your decision solely on visual content, not interpretation
+4. Provide only the one-word answer: "yes" or "no"
+""".strip()
+
+
+PROMPT_IMAGE_INTEGRITY_FOLLOW_UP = "Does this image have copyright concerns or includes public figures?"
+
+PROMPT_TEXT_INTEGRITY = """
+Task: Analyze a text prompt to identify potential copyright concerns or requests to depict living public figures.
+
+Output: Respond with only "yes" or "no"
+
+Criteria for "Yes":
+- The prompt explicitly names a character from copyrighted media (movies, TV, comics, games, etc.)
+- The prompt explicitly mentions a trademarked logo or brand
+- The prompt names or describes a specific living public figure (celebrities, politicians, athletes, influencers, etc.)
+
+Criteria for "No":
+- All other cases
+- When you cannot identify the specific copyrighted work or named individual
+
+Critical Requirements:
+1. You must be able to name the exact copyrighted work or specific person referenced
+2. General demographic descriptions or characteristics are not sufficient
+3. Analyze only the prompt text, not potential image outcomes
+4. Provide only the one-word answer: "yes" or "no"
+
+The prompt to check is:
+-----
+{prompt}
+-----
+
+Does this prompt have copyright concerns or includes public figures?
+""".strip()
diff --git a/models/flux/modules/text_encoder_mistral.py b/models/flux/modules/text_encoder_mistral.py
new file mode 100644
index 0000000..e05b3b0
--- /dev/null
+++ b/models/flux/modules/text_encoder_mistral.py
@@ -0,0 +1,354 @@
+from pathlib import Path
+
+import torch
+import torch.nn as nn
+from einops import rearrange
+from PIL import Image
+from transformers import AutoProcessor, Mistral3ForConditionalGeneration, pipeline
+from shared.utils import files_locator as fl
+from .sampling import cap_pixels, concatenate_images
+from .system_messages import (
+ PROMPT_IMAGE_INTEGRITY,
+ PROMPT_IMAGE_INTEGRITY_FOLLOW_UP,
+ PROMPT_TEXT_INTEGRITY,
+ SYSTEM_MESSAGE,
+ SYSTEM_MESSAGE_UPSAMPLING_I2I,
+ SYSTEM_MESSAGE_UPSAMPLING_T2I,
+ SYSTEM_PROMPT_CONTENT_FILTER,
+)
+
+OUTPUT_LAYERS = [10, 20, 30]
+MAX_LENGTH = 512
+NSFW_THRESHOLD = 0.85
+UPSAMPLING_MAX_IMAGE_SIZE = 768**2
+
+from mmgp import offload
+import os
+
+class Mistral3SmallEmbedder(nn.Module):
+ def __init__(
+ self,
+ model_spec = None,
+ torch_dtype: str = "bfloat16",
+ ):
+ super().__init__()
+ file_path = model_spec
+ self.model = offload.fast_load_transformers_model(file_path, writable_tensors= False, defaultConfigPath= os.path.join(os.path.dirname(file_path), "config.json"))
+ self.processor = AutoProcessor.from_pretrained(os.path.dirname(file_path), use_fast=False)
+ self.yes_token, self.no_token = self.processor.tokenizer.encode(
+ ["yes", "no"], add_special_tokens=False
+ )
+
+ self.max_length = MAX_LENGTH
+ self.upsampling_max_image_size = UPSAMPLING_MAX_IMAGE_SIZE
+
+ self.nsfw_classifier = None
+
+ def _validate_and_process_images(
+ self, img: list[list[Image.Image]] | list[Image.Image]
+ ) -> list[list[Image.Image]]:
+ # Simple validation: ensure it's a list of PIL images or list of lists of PIL images
+ if not img:
+ return []
+
+ # Check if it's a list of lists or a list of images
+ if isinstance(img[0], Image.Image):
+ # It's a list of images, convert to list of lists
+ img = [[im] for im in img]
+
+ # potentially concatenate multiple images to reduce the size
+ img = [[concatenate_images(img_i)] if len(img_i) > 1 else img_i for img_i in img]
+
+ # cap the pixels
+ img = [[cap_pixels(img_i, self.upsampling_max_image_size) for img_i in img_i] for img_i in img]
+ return img
+
+ def format_input(
+ self,
+ txt: list[str],
+ system_message: str = SYSTEM_MESSAGE,
+ img: list[Image.Image] | list[list[Image.Image]] | None = None,
+ ) -> list[list[dict]]:
+ """
+ Format a batch of text prompts into the conversation format expected by apply_chat_template.
+ Optionally, add images to the input.
+
+ Args:
+ txt: List of text prompts
+ system_message: System message to use (default: CREATIVE_SYSTEM_MESSAGE)
+ img: List of images to add to the input.
+
+ Returns:
+ List of conversations, where each conversation is a list of message dicts
+ """
+ # Remove [IMG] tokens from prompts to avoid Pixtral validation issues
+ # when truncation is enabled. The processor counts [IMG] tokens and fails
+ # if the count changes after truncation.
+ cleaned_txt = [prompt.replace("[IMG]", "") for prompt in txt]
+
+ if img is None or len(img) == 0:
+ return [
+ [
+ {
+ "role": "system",
+ "content": [{"type": "text", "text": system_message}],
+ },
+ {"role": "user", "content": [{"type": "text", "text": prompt}]},
+ ]
+ for prompt in cleaned_txt
+ ]
+ else:
+ assert len(img) == len(txt), "Number of images must match number of prompts"
+ img = self._validate_and_process_images(img)
+
+ messages = [
+ [
+ {
+ "role": "system",
+ "content": [{"type": "text", "text": system_message}],
+ },
+ ]
+ for _ in cleaned_txt
+ ]
+
+ for i, (el, images) in enumerate(zip(messages, img)):
+ # optionally add the images per batch element.
+ if images is not None:
+ el.append(
+ {
+ "role": "user",
+ "content": [{"type": "image", "image": image_obj} for image_obj in images],
+ }
+ )
+ # add the text.
+ el.append(
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": cleaned_txt[i]}],
+ }
+ )
+
+ return messages
+
+ @torch.no_grad()
+ def upsample_prompt(
+ self,
+ txt: list[str],
+ img: list[Image.Image] | list[list[Image.Image]] | None = None,
+ temperature: float = 0.15,
+ ) -> list[str]:
+ """
+ Upsample prompts using the model's generate method.
+
+ Args:
+ txt: List of input prompts to upsample
+ img: Optional list of images or list of lists of images. If None or all None, uses t2i mode, otherwise i2i mode.
+
+ Returns:
+ List of upsampled prompts
+ """
+ # Set system message based on whether images are provided
+ if img is None or len(img) == 0 or img[0] is None:
+ system_message = SYSTEM_MESSAGE_UPSAMPLING_T2I
+ else:
+ system_message = SYSTEM_MESSAGE_UPSAMPLING_I2I
+
+ # Format input messages
+ messages_batch = self.format_input(txt=txt, system_message=system_message, img=img)
+
+ # Process all messages at once
+ # with image processing a too short max length can throw an error in here.
+ try:
+ inputs = self.processor.apply_chat_template(
+ messages_batch,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ return_tensors="pt",
+ padding="max_length",
+ truncation=True,
+ max_length=2048,
+ )
+ except ValueError as e:
+ print(
+ f"Error processing input: {e}, your max length is probably too short, when you have images in the input."
+ )
+ raise e
+
+ # Move to device
+ inputs["input_ids"] = inputs["input_ids"].to(self.model.device)
+ inputs["attention_mask"] = inputs["attention_mask"].to(self.model.device)
+
+ if "pixel_values" in inputs:
+ inputs["pixel_values"] = inputs["pixel_values"].to(self.model.device, self.model.dtype)
+
+ # Generate text using the model's generate method
+ try:
+ generated_ids = self.model.generate(
+ **inputs,
+ max_new_tokens=512,
+ do_sample=True,
+ temperature=temperature,
+ use_cache=True,
+ )
+
+ # Decode only the newly generated tokens (skip input tokens)
+ # Extract only the generated portion
+ input_length = inputs["input_ids"].shape[1]
+ generated_tokens = generated_ids[:, input_length:]
+
+ raw_txt = self.processor.tokenizer.batch_decode(
+ generated_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=True
+ )
+ return raw_txt
+ except Exception as e:
+ print(f"Error generating upsampled prompt: {e}, returning original prompt")
+ return txt
+
+ @torch.no_grad()
+ def forward(self, txt: list[str]):
+ # Format input messages
+ messages_batch = self.format_input(txt=txt)
+
+ # Process all messages at once
+ # with image processing a too short max length can throw an error in here.
+ inputs = self.processor.apply_chat_template(
+ messages_batch,
+ add_generation_prompt=False,
+ tokenize=True,
+ return_dict=True,
+ return_tensors="pt",
+ padding="max_length",
+ truncation=True,
+ max_length=self.max_length,
+ )
+
+ # Move to device
+ input_ids = inputs["input_ids"].to(self.model.device)
+ attention_mask = inputs["attention_mask"].to(self.model.device)
+
+ # Forward pass through the model
+ output = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ output_hidden_states=True,
+ use_cache=False,
+ )
+
+ out = torch.stack([output.hidden_states[k] for k in OUTPUT_LAYERS], dim=1)
+ return rearrange(out, "b c l d -> b l (c d)")
+
+ def yes_no_logit_processor(
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor
+ ) -> torch.FloatTensor:
+ """
+ Sets all tokens but yes/no to the minimum.
+ """
+ scores_yes_token = scores[:, self.yes_token].clone()
+ scores_no_token = scores[:, self.no_token].clone()
+ scores_min = scores.min()
+ scores[:, :] = scores_min - 1
+ scores[:, self.yes_token] = scores_yes_token
+ scores[:, self.no_token] = scores_no_token
+ return scores
+
+ def test_image(self, image: Image.Image | str | Path | torch.Tensor) -> bool:
+ if isinstance(image, torch.Tensor):
+ image = rearrange(image[0].clamp(-1.0, 1.0), "c h w -> h w c")
+ image = Image.fromarray((127.5 * (image + 1.0)).cpu().byte().numpy())
+ elif isinstance(image, (str, Path)):
+ image = Image.open(image)
+
+ classification = next(c for c in self.nsfw_classifier(image) if c["label"] == "nsfw")
+ if classification["score"] > NSFW_THRESHOLD:
+ return True
+
+ # 512^2 pixels are enough for checking
+ w, h = image.size
+ f = (512**2 / (w * h)) ** 0.5
+ image = image.resize((int(f * w), int(f * h)))
+
+ chat = [
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": SYSTEM_PROMPT_CONTENT_FILTER,
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": PROMPT_IMAGE_INTEGRITY,
+ },
+ {
+ "type": "image",
+ "image": image,
+ },
+ {
+ "type": "text",
+ "text": PROMPT_IMAGE_INTEGRITY_FOLLOW_UP,
+ },
+ ],
+ },
+ ]
+
+ inputs = self.processor.apply_chat_template(
+ chat,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ return_tensors="pt",
+ ).to(self.model.device)
+ inputs["pixel_values"] = inputs["pixel_values"].to(dtype=self.model.dtype)
+
+ generate_ids = self.model.generate(
+ **inputs,
+ max_new_tokens=1,
+ logits_processor=[self.yes_no_logit_processor],
+ do_sample=False,
+ )
+
+ return generate_ids[0, -1].item() == self.yes_token
+
+ def test_txt(self, txt: str) -> bool:
+ chat = [
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": SYSTEM_PROMPT_CONTENT_FILTER,
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": PROMPT_TEXT_INTEGRITY.format(prompt=txt),
+ },
+ ],
+ },
+ ]
+
+ inputs = self.processor.apply_chat_template(
+ chat,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ return_tensors="pt",
+ ).to(self.model.device)
+
+ generate_ids = self.model.generate(
+ **inputs,
+ max_new_tokens=1,
+ logits_processor=[self.yes_no_logit_processor],
+ do_sample=False,
+ )
+ return generate_ids[0, -1].item() == self.yes_token
diff --git a/models/flux/sampling.py b/models/flux/sampling.py
index 8094f5e..fa1e7c6 100644
--- a/models/flux/sampling.py
+++ b/models/flux/sampling.py
@@ -266,6 +266,35 @@ def get_lin_function(
return lambda x: m * x + b
+
+def generalized_time_snr_shift(t: Tensor, mu: float, sigma: float) -> Tensor:
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
+
+
+def get_schedule_flux2(num_steps: int, image_seq_len: int) -> list[float]:
+ mu = compute_empirical_mu(image_seq_len, num_steps)
+ timesteps = torch.linspace(1, 0, num_steps + 1)
+ timesteps = generalized_time_snr_shift(timesteps, mu, 1.0)
+ return timesteps.tolist()
+
+
+def compute_empirical_mu(image_seq_len: int, num_steps: int) -> float:
+ a1, b1 = 8.73809524e-05, 1.89833333
+ a2, b2 = 0.00016927, 0.45666666
+
+ if image_seq_len > 4300:
+ mu = a2 * image_seq_len + b2
+ return float(mu)
+
+ m_200 = a2 * image_seq_len + b2
+ m_10 = a1 * image_seq_len + b1
+
+ a = (m_200 - m_10) / 190.0
+ b = m_200 - 200.0 * a
+ mu = a * num_steps + b
+
+ return float(mu)
+
def get_schedule(
num_steps: int,
image_seq_len: int,
@@ -317,7 +346,6 @@ def denoise(
denoising_strength = 1,
masking_strength = 1,
preview_meta = None,
- radiance_cache = None,
):
kwargs = {
@@ -326,7 +354,6 @@ def denoise(
"img_len": img.shape[1],
"siglip_embedding": siglip_embedding,
"siglip_embedding_ids": siglip_embedding_ids,
- "radiance_cache": radiance_cache,
}
if callback != None:
diff --git a/models/flux/util.py b/models/flux/util.py
index d675095..2fc4b98 100644
--- a/models/flux/util.py
+++ b/models/flux/util.py
@@ -294,6 +294,42 @@ class ModelSpec:
configs = {
+ "flux2-dev": ModelSpec(
+ repo_id="",
+ repo_flow="",
+ repo_ae="ckpts/flux2_vae.safetensors",
+ params=FluxParams(
+ in_channels=128,
+ out_channels=128,
+ vec_in_dim=1,
+ context_in_dim=15360,
+ hidden_size=6144,
+ mlp_ratio=3.0,
+ single_linear1_mlp_ratio=6.0,
+ single_mlp_hidden_ratio=3.0,
+ double_mlp_ratio=3.0,
+ double_linear1_mlp_ratio=6.0,
+ num_heads=48,
+ depth=8,
+ depth_single_blocks=48,
+ axes_dim=[32, 32, 32, 32],
+ theta=2000,
+ qkv_bias=False,
+ guidance_embed=True,
+ flux2=True,
+ ),
+ ae_params=AutoEncoderParams(
+ resolution=1024,
+ in_channels=3,
+ ch=128,
+ out_ch=3,
+ ch_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ z_channels=32,
+ scale_factor=0.5,
+ shift_factor=0.0,
+ ),
+ ),
"flux-dev": ModelSpec(
repo_id="",
repo_flow="",
@@ -789,6 +825,64 @@ def print_load_warning(missing: list[str], unexpected: list[str]) -> None:
print(f"Got {len(unexpected)} unexpected keys:\n\t" + "\n\t".join(unexpected))
+def preprocess_flux2_state_dict(state_dict: dict, params: FluxParams) -> dict:
+ """
+ Remap Flux2 checkpoint keys to the shared Flux1-style module layout.
+ - Duplicate shared modulation weights to each single/double block.
+ - Drop unused guidance embeddings that are identity in Flux2.
+ """
+ sd = dict(state_dict)
+ def pop_mod(prefix: str):
+ w = sd.pop(f"{prefix}.lin.weight", None)
+ b = sd.pop(f"{prefix}.lin.bias", None)
+ if w is None:
+ w = sd.pop(f"{prefix}.linear.weight", None)
+ b = sd.pop(f"{prefix}.linear.bias", None) if b is None else b
+ return w, b
+
+ img_mod_w, img_mod_b = pop_mod("double_stream_modulation_img")
+ txt_mod_w, txt_mod_b = pop_mod("double_stream_modulation_txt")
+ single_mod_w, single_mod_b = pop_mod("single_stream_modulation")
+
+ if img_mod_w is not None:
+ for i in range(params.depth):
+ sd[f"double_blocks.{i}.img_mod.lin.weight"] = img_mod_w
+ if img_mod_b is not None:
+ sd[f"double_blocks.{i}.img_mod.lin.bias"] = img_mod_b
+ if txt_mod_w is not None:
+ for i in range(params.depth):
+ sd[f"double_blocks.{i}.txt_mod.lin.weight"] = txt_mod_w
+ if txt_mod_b is not None:
+ sd[f"double_blocks.{i}.txt_mod.lin.bias"] = txt_mod_b
+ if single_mod_w is not None:
+ for i in range(params.depth_single_blocks):
+ sd[f"single_blocks.{i}.modulation.lin.weight"] = single_mod_w
+ if single_mod_b is not None:
+ sd[f"single_blocks.{i}.modulation.lin.bias"] = single_mod_b
+
+ # Remove unused inputs from Flux2 that are identity for us.
+ for unused in (
+ "double_stream_modulation_img.lin.weight",
+ "double_stream_modulation_img.lin.bias",
+ "double_stream_modulation_txt.lin.weight",
+ "double_stream_modulation_txt.lin.bias",
+ "single_stream_modulation.lin.weight",
+ "single_stream_modulation.lin.bias",
+ "double_stream_modulation_img.linear.weight",
+ "double_stream_modulation_img.linear.bias",
+ "double_stream_modulation_txt.linear.weight",
+ "double_stream_modulation_txt.linear.bias",
+ "single_stream_modulation.linear.weight",
+ "single_stream_modulation.linear.bias",
+ "guidance_in.in_layer.weight",
+ "guidance_in.in_layer.bias",
+ "guidance_in.out_layer.weight",
+ "guidance_in.out_layer.bias",
+ ):
+ sd.pop(unused, None)
+ return sd
+
+
def load_flow_model(name: str, model_filename, device: str | torch.device = "cuda", verbose: bool = True) -> Flux:
# Loading Flux
config = configs[name]
@@ -866,3 +960,30 @@ def optionally_expand_state_dict(model: torch.nn.Module, state_dict: dict) -> di
return state_dict
+class Flux2TransformerShared:
+ """
+ Convenience wrapper to instantiate the shared Flux2 transformer with explicit defaults.
+ """
+
+ def __new__(cls, **kwargs):
+ from diffusers.models.transformers.transformer_flux2 import Flux2Transformer2DModel
+
+ defaults = dict(
+ patch_size=1,
+ in_channels=128,
+ out_channels=None,
+ num_layers=8,
+ num_single_layers=48,
+ attention_head_dim=128,
+ num_attention_heads=48,
+ joint_attention_dim=15360,
+ timestep_guidance_channels=256,
+ mlp_ratio=3.0,
+ axes_dims_rope=(32, 32, 32, 32),
+ rope_theta=2000,
+ eps=1e-6,
+ )
+ defaults.update(kwargs)
+ return Flux2Transformer2DModel(**defaults)
+
+
diff --git a/requirements.txt b/requirements.txt
index cbc9d4e..53b90d6 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -52,7 +52,7 @@ pydantic==2.10.6
# Math & modeling
torchdiffeq>=0.2.5
tensordict>=0.6.1
-mmgp==3.6.8
+mmgp==3.6.9
peft==0.15.0
matplotlib
diff --git a/shared/RGB_factors.py b/shared/RGB_factors.py
index 5cf9c34..c0db612 100644
--- a/shared/RGB_factors.py
+++ b/shared/RGB_factors.py
@@ -1,4 +1,4 @@
-# thanks Comfyui for the rgb factors (https://github.com/comfyanonymous/ComfyUI/blob/master/comfy/latent_formats.py)
+# thanks Comfyui for the rgb factors (https://github.com/comfyanonymous/ComfyUI/blob/master/comfy/latent_formats.py) (if not explictly computed by DeepBeepMeep as indicated)
def get_rgb_factors(model_family, model_type = None, sub_family = None):
if model_family in ["wan", "qwen"]:
if model_type =="ti2v_2_2":
@@ -80,27 +80,65 @@ def get_rgb_factors(model_family, model_type = None, sub_family = None):
# latent_rgb_factors_bias = [0.0259, -0.0192, -0.0761]
elif model_family =="flux":
- scale_factor = 0.3611
- shift_factor = 0.1159
- latent_rgb_factors =[
- [-0.0346, 0.0244, 0.0681],
- [ 0.0034, 0.0210, 0.0687],
- [ 0.0275, -0.0668, -0.0433],
- [-0.0174, 0.0160, 0.0617],
- [ 0.0859, 0.0721, 0.0329],
- [ 0.0004, 0.0383, 0.0115],
- [ 0.0405, 0.0861, 0.0915],
- [-0.0236, -0.0185, -0.0259],
- [-0.0245, 0.0250, 0.1180],
- [ 0.1008, 0.0755, -0.0421],
- [-0.0515, 0.0201, 0.0011],
- [ 0.0428, -0.0012, -0.0036],
- [ 0.0817, 0.0765, 0.0749],
- [-0.1264, -0.0522, -0.1103],
- [-0.0280, -0.0881, -0.0499],
- [-0.1262, -0.0982, -0.0778]
- ]
- latent_rgb_factors_bias = [-0.0329, -0.0718, -0.0851]
+ if sub_family =="flux2":
+ # computed by your very own Deep Beep Meep
+ latent_rgb_factors = [
+ [0.017027, 0.008257, 0.004624],
+ [0.026682, 0.029259, 0.060114],
+ [-0.009869, 0.020518, 0.060890],
+ [0.226466, 0.296887, 0.368866],
+ [0.015064, -0.014507, -0.028432],
+ [0.001710, -0.004815, -0.022213],
+ [-0.018906, 0.049969, -0.008771],
+ [0.010261, 0.012761, 0.017796],
+ [-0.349602, -0.272936, -0.182633],
+ [-0.031123, -0.042880, -0.043945],
+ [-0.008367, -0.001142, -0.001056],
+ [0.036070, -0.005392, -0.069563],
+ [-0.003169, 0.013091, 0.029921],
+ [-0.008074, -0.009231, -0.010962],
+ [0.008431, 0.015439, 0.015267],
+ [-0.066895, -0.005198, 0.011012],
+ [0.012917, 0.009686, 0.012514],
+ [-0.001605, -0.000442, 0.002637],
+ [0.012599, 0.011981, 0.014867],
+ [0.068052, -0.003048, -0.001778],
+ [-0.002239, 0.003910, 0.009552],
+ [0.010798, 0.000513, -0.002564],
+ [0.013768, 0.016439, 0.016339],
+ [-0.004254, 0.003370, 0.012017],
+ [-0.048989, -0.029049, -0.032899],
+ [-0.009327, -0.010332, -0.004374],
+ [0.007945, -0.008562, -0.006007],
+ [-0.002106, -0.018114, -0.029735],
+ [-0.039313, -0.046827, -0.048615],
+ [-0.005774, 0.016549, 0.031351],
+ [0.005425, 0.001212, -0.003960],
+ [-0.009495, -0.028664, -0.039440],
+ ]
+ latent_rgb_factors_bias = [-0.039388, -0.063196, -0.118529]
+ else:
+ scale_factor = 0.3611
+ shift_factor = 0.1159
+ latent_rgb_factors =[
+ [-0.0346, 0.0244, 0.0681],
+ [ 0.0034, 0.0210, 0.0687],
+ [ 0.0275, -0.0668, -0.0433],
+ [-0.0174, 0.0160, 0.0617],
+ [ 0.0859, 0.0721, 0.0329],
+ [ 0.0004, 0.0383, 0.0115],
+ [ 0.0405, 0.0861, 0.0915],
+ [-0.0236, -0.0185, -0.0259],
+ [-0.0245, 0.0250, 0.1180],
+ [ 0.1008, 0.0755, -0.0421],
+ [-0.0515, 0.0201, 0.0011],
+ [ 0.0428, -0.0012, -0.0036],
+ [ 0.0817, 0.0765, 0.0749],
+ [-0.1264, -0.0522, -0.1103],
+ [-0.0280, -0.0881, -0.0499],
+ [-0.1262, -0.0982, -0.0778]
+ ]
+ latent_rgb_factors_bias = [-0.0329, -0.0718, -0.0851]
elif model_family == "ltxv":
latent_channels = 128
diff --git a/wgp.py b/wgp.py
index 0d4487b..33ddd42 100644
--- a/wgp.py
+++ b/wgp.py
@@ -81,8 +81,8 @@ from collections import defaultdict
global_queue_ref = []
AUTOSAVE_FILENAME = "queue.zip"
PROMPT_VARS_MAX = 10
-target_mmgp_version = "3.6.8"
-WanGP_version = "9.62"
+target_mmgp_version = "3.6.9"
+WanGP_version = "9.7"
settings_version = 2.41
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None
@@ -1827,6 +1827,13 @@ def _parse_args():
help="Path to a directory that contains flux images Loras"
)
+ parser.add_argument(
+ "--lora-dir-flux2",
+ type=str,
+ default="loras_flux2",
+ help="Path to a directory that contains flux2 images Loras"
+ )
+
parser.add_argument(
"--lora-dir-qwen",
type=str,
@@ -2085,6 +2092,9 @@ def get_lora_dir(model_type):
elif model_family == "ltxv":
return args.lora_dir_ltxv
elif model_family == "flux":
+ if base_model_type in ["flux2_dev"]:
+ return args.lora_dir_flux2
+ else:
return args.lora_dir_flux
elif model_family =="hunyuan":
if i2v:
@@ -2123,7 +2133,7 @@ lock_ui_attention = False
lock_ui_transformer = False
lock_ui_compile = False
-force_profile_no = int(args.profile)
+force_profile_no = float(args.profile)
verbose_level = int(args.verbose)
check_loras = args.check_loras ==1
@@ -3173,6 +3183,10 @@ def init_pipe(pipe, kwargs, override_profile):
if "transformer2" in pipe:
if profile in [3,4]:
kwargs["pinnedMemory"] = ["transformer", "transformer2"]
+
+ if profile == 4.5:
+ profile = 4
+ kwargs["asyncTransfers"] = False
return profile
@@ -8145,6 +8159,7 @@ memory_profile_choices= [ ("Profile 1, HighRAM_HighVRAM: at least 64 GB of RAM
("Profile 2, HighRAM_LowVRAM: at least 64 GB of RAM and 12 GB of VRAM, the most versatile profile with high RAM, better suited for RTX 3070/3080/4070/4080 or for RTX 3090 / RTX 4090 with large pictures batches or long videos", 2),
("Profile 3, LowRAM_HighVRAM: at least 32 GB of RAM and 24 GB of VRAM, adapted for RTX 3090 / RTX 4090 with limited RAM for good speed short video",3),
("Profile 4, LowRAM_LowVRAM (Recommended): at least 32 GB of RAM and 12 GB of VRAM, if you have little VRAM or want to generate longer videos",4),
+ ("Profile 4+, LowRAM_LowVRAM+: at least 32 GB of RAM and 12 GB of VRAM, variant of Profile 4, slightly slower but needs less VRAM",4.5),
("Profile 5, VerylowRAM_LowVRAM (Fail safe): at least 24 GB of RAM and 10 GB of VRAM, if you don't have much it won't be fast but maybe it will work",5)]
def detect_auto_save_form(state, evt:gr.SelectData):
@@ -8815,7 +8830,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
choices=[
("Generate every combination of images and texts", 0),
("Match images and text prompts", 1),
- ], visible= test_class_i2v(model_type), label= "Multiple Images as Texts Prompts"
+ ], visible= test_class_i2v(model_type) or ltxv, label= "Multiple Images as Texts Prompts"
)
with gr.Row():