Python
added radiance support'
deepbeepmeepe4eed34c7aa5
diff --git a/defaults/flux_chroma_radiance.json b/defaults/flux_chroma_radiance.jsonnew file mode 100644index 0000000..bbe2568--- /dev/null+++ b/defaults/flux_chroma_radiance.json@@ -0,0 +1,18 @@+{+ "model": {+ "name": "Flux 1 Chroma Radiance 8.9B",+ "architecture": "flux_chroma_radiance",+ "description": "FLUX.1 Chroma Radiance 20th of October 2025 version) is a 8.9 billion parameters model. As a base model, Chroma Radiance is intentionally designed to be an excellent starting point for finetuning. It provides a strong, neutral foundation for developers, researchers, and artists to create specialized models.",+ "URLs": [+ "flux1-chroma_radiance_201025_bf16.safetensors",+ "flux1-chroma_radiance_201025_quanto_bf16_int8.safetensors"+ ],+ "source": "c:/temp/chroma_radiance.pth",+ "image_outputs": true+ },+ "prompt": "draw a hat",+ "resolution": "1280x720",+ "guidance_scale": 3.0,+ "num_inference_steps": 20,+ "batch_size": 1+}\ No newline at end of filediff --git a/defaults/t2v_1.3B.json b/defaults/t2v_1.3B.jsonindex ca88bd9..fab6062 100644--- a/defaults/t2v_1.3B.json+++ b/defaults/t2v_1.3B.json@@ -1,11 +1,11 @@{- "model":- {- "name": "Wan2.1 Text2video 1.3B",- "architecture" : "t2v_1.3B",- "description": "The light version of the original Wan Text 2 Video model. Most other models have been built on top of it",- "URLs": [- "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_text2video_1.3B_mbf16.safetensors"- ]- }+ "model": {+ "name": "Wan2.1 Text2video 1.3B",+ "architecture": "t2v_1.3B",+ "description": "The light version of the original Wan Text 2 Video model. Most other models have been built on top of it",+ "URLs": [+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_text2video_1.3B_mbf16.safetensors",+ "wan2.1_text2video_1.3B_quanto_mbf16_int8.safetensors"+ ]+ }}\ No newline at end of filediff --git a/models/flux/flux_handler.py b/models/flux/flux_handler.pyindex be17d07..1e2dfd2 100644--- a/models/flux/flux_handler.py+++ b/models/flux/flux_handler.py@@ -1,4 +1,5 @@import torch+from PIL import Imagefrom shared.utils import files_locator as fldef get_ltxv_text_encoder_filename(text_encoder_quantization):@@ -10,7 +11,7 @@ def get_ltxv_text_encoder_filename(text_encoder_quantization):class family_handler():@staticmethoddef query_supported_types():- return ["flux", "flux_chroma", "flux_dev_kontext", "flux_dev_umo", "flux_dev_uso", "flux_schnell", "flux_dev_kontext_dreamomni2" ]+ return ["flux", "flux_chroma", "flux_chroma_radiance", "flux_dev_kontext", "flux_dev_umo", "flux_dev_uso", "flux_schnell", "flux_dev_kontext_dreamomni2" ]@staticmethoddef query_family_maps():@@ -21,11 +22,12 @@ class family_handler():"flux_dev_uso" : "flux","flux_schnell" : "flux","flux_chroma" : "flux",+ "flux_chroma_radiance": "flux","flux_dev_kontext_dreamomni2": "flux",}models_comp_map = {- "flux": ["flux_chroma", "flux_dev_kontext", "flux_dev_umo", "flux_dev_uso", "flux_schnell", "flux_dev_kontext_dreamomni2" ]+ "flux": ["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@@ -33,6 +35,7 @@ class family_handler():flux_model = "flux-dev" if base_model_type == "flux" else base_model_type.replace("_", "-")flux_schnell = flux_model == "flux-schnell"flux_chroma = flux_model == "flux-chroma"+ flux_chroma_radiance = flux_model == "flux-chroma-radiance"flux_uso = flux_model == "flux-dev-uso"flux_umo = flux_model == "flux-dev-umo"flux_kontext = flux_model == "flux-dev-kontext"@@ -40,12 +43,14 @@ class family_handler():extra_model_def = {"image_outputs" : True,- "no_negative_prompt" : not flux_chroma,+ "no_negative_prompt" : not (flux_chroma or flux_chroma_radiance),"flux-model": flux_model,}extra_model_def["profiles_dir"] = [] if flux_schnell else ["flux"]- if flux_chroma:+ if flux_chroma or flux_chroma_radiance:extra_model_def["guidance_max_phases"] = 1+ if flux_chroma_radiance:+ extra_model_def["radiance"] = Trueelif not flux_schnell:extra_model_def["embedded_guidance"] = Trueif flux_uso :@@ -60,7 +65,7 @@ class family_handler():}if flux_kontext or flux_kontext_dreamomni2:- extra_model_def["inpaint_support"] = True+ extra_model_def["inpaint_support"] = flux_kontextextra_model_def["image_ref_choices"] = {"choices": [("None", ""),@@ -90,10 +95,49 @@ class family_handler():@staticmethoddef get_rgb_factors(base_model_type ):+ if base_model_type == "flux_chroma_radiance":+ return None, Nonefrom shared.RGB_factors import get_rgb_factorslatent_rgb_factors, latent_rgb_factors_bias = get_rgb_factors("flux")return latent_rgb_factors, latent_rgb_factors_bias+ @staticmethod+ def preview_latents(base_model_type, latents, meta):+ if base_model_type != "flux_chroma_radiance":+ return None+ from .sampling import patches_to_image++ tensor = latents+ if not torch.is_tensor(tensor):+ return None+ tensor = tensor.detach()+ if tensor.dim() == 4:+ if tensor.shape[1] == 1 and tensor.shape[0] in (1, 3, 4):+ tensor = tensor[:, 0, ...]+ elif tensor.shape[0] == 1 and tensor.shape[1] in (3, 4):+ tensor = tensor[0, ...]+ if tensor.dim() == 3 and tensor.shape[0] in (3, 4):+ image = tensor[:3, ...].to(torch.float32)+ else:+ height = meta.get("height")+ width = meta.get("width")+ patch_size = meta.get("patch_size", 16)+ if height is None or width is None:+ return None+ tensor = tensor.to(torch.float32)+ image = patches_to_image(tensor, height, width, patch_size)[0]+ image = image.clamp(-1, 1).cpu()+ image = image.add(1).mul(127.5).clamp(0, 255).to(torch.uint8)+ image = image.permute(1, 2, 0).numpy()+ preview = Image.fromarray(image)+ if preview.height > 0:+ scale = 200 / preview.height+ width_px = max(1, int(round(preview.width * scale)))+ resampling_module = getattr(Image, "Resampling", Image)+ resample_filter = getattr(resampling_module, "BILINEAR", Image.BILINEAR)+ preview = preview.resize((width_px, 200), resample=resample_filter)+ return preview+@staticmethoddef query_model_family():diff --git a/models/flux/flux_main.py b/models/flux/flux_main.pyindex 5a4c7ee..509836c 100644--- a/models/flux/flux_main.py+++ b/models/flux/flux_main.py@@ -6,7 +6,7 @@ from glob import iglobfrom mmgp import offload as offloadimport torchfrom shared.utils.utils import calculate_new_dimensions-from .sampling import denoise, get_schedule, prepare_kontext, prepare_prompt, prepare_multi_ip, unpack, resizeinput+from .sampling import denoise, get_schedule, prepare_kontext, prepare_prompt, prepare_multi_ip, unpack, resizeinput, patches_to_imagefrom .modules.layers import get_linear_split_mapfrom transformers import SiglipVisionModel, SiglipImageProcessorimport torchvision.transforms.functional as TVF@@ -99,7 +99,7 @@ class model_factory: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 = load_ae(self.name, device=torch_device)+ self.vae = None if getattr(self.model, "radiance", False) else load_ae(self.name, device=torch_device)siglip_processor = siglip_model = feature_embedder = Noneif self.name == 'flux-dev-uso':@@ -180,6 +180,13 @@ class model_factory:)return output_text[0]+ def prepare_preview_payload(self, latent, meta=None):+ if getattr(self.model, "radiance", False) and isinstance(meta, dict):+ data = dict(meta)+ data["latents"] = latent+ return data+ return latent+def generate(self,@@ -204,6 +211,7 @@ class model_factory:denoising_strength = 1.,**bbargs):+ radiance = getattr(self.model, "radiance", False)if self._interrupt:return Noneif self.guidance_max_phases < 1: guide_scale = 1@@ -213,6 +221,11 @@ class model_factory:flux_dev_umo = self.name in ['flux-dev-umo']flux_kontext_dreamomni2 = self.name in ['flux-dev-kontext-dreamomni2']latent_stiching = flux_dev_uso or flux_dev_umo or flux_kontext_dreamomni2+ if radiance and latent_stiching:+ raise ValueError("Multi image latent stitching is not supported for Chroma Radiance.")++ if radiance and (input_ref_images or input_frames is not None or input_masks is not None):+ raise ValueError("Image conditioning and masking are not supported for Chroma Radiance yet.")lock_dimensions= False@@ -259,6 +272,8 @@ class model_factory:input_ref_images = Noneimage_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 16if latent_stiching :inp, height, width = prepare_multi_ip(@@ -284,8 +299,18 @@ class model_factory:seed=seed,device=device,img_mask=image_mask,+ patch_size=noise_patch_size,+ noise_channels=noise_channels,)+ preview_meta = {+ "height": height,+ "width": width,+ "patch_size": noise_patch_size,+ "radiance": radiance,+ }+ 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))@@ -301,16 +326,35 @@ class model_factory:inp["siglip_embedding"] = siglip_embeddinginp["siglip_embedding_ids"] = siglip_embedding_ids- def unpack_latent(x):- return unpack(x.float(), height, width)+ 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(self.model, **inp, timesteps=timesteps, guidance=embedded_guidance_scale, real_guidance_scale =guide_scale, callback=callback, pipeline=self, loras_slists= loras_slists, unpack_latent = unpack_latent, joint_pass = joint_pass, denoising_strength = denoising_strength)+ x = denoise(+ self.model,+ **inp,+ timesteps=timesteps,+ guidance=embedded_guidance_scale,+ real_guidance_scale=guide_scale,+ callback=callback,+ pipeline=self,+ loras_slists=loras_slists,+ unpack_latent=unpack_latent,+ joint_pass=joint_pass,+ denoising_strength=denoising_strength,+ preview_meta=preview_meta,+ radiance_cache=radiance_cache,+ )if x==None: return None# decode latents to pixel spacex = unpack_latent(x)- with torch.autocast(device_type=device, dtype=torch.bfloat16):- x = self.vae.decode(x)+ if self.vae is not None:+ with torch.autocast(device_type=device, dtype=torch.bfloat16):+ x = self.vae.decode(x)if image_mask is not None:img_msk_rebuilt = inp["img_msk_rebuilt"]diff --git a/models/flux/model.py b/models/flux/model.pyindex c5f7a24..0cc86fd 100644--- a/models/flux/model.py+++ b/models/flux/model.py@@ -2,6 +2,7 @@ from dataclasses import dataclassimport torchfrom torch import Tensor, nn+import torch.nn.functional as Ffrom .modules.layers import (DoubleStreamBlock,@@ -15,6 +16,7 @@ from .modules.layers import (SigLIPMultiFeatProjModel,)from .modules.lora import LinearLora, replace_linear_with_lora+from .radiance import apply_radiance_head, inject_radiance_modules@dataclass@@ -34,6 +36,14 @@ class FluxParams:guidance_embed: boolchroma: bool = Falseeso: bool = False+ radiance: bool = False+ radiance_patch_size: int = 16+ radiance_hidden_size: int = 64+ radiance_mlp_ratio: int = 4+ radiance_depth: int = 4+ radiance_max_freqs: int = 8+ radiance_tile_size: int = 0+ radiance_final_head_type: str = "conv"class Flux(nn.Module):"""@@ -73,6 +83,7 @@ class Flux(nn.Module):self.in_channels = params.in_channelsself.out_channels = params.out_channelsself.chroma = params.chroma+ self.radiance = getattr(params, "radiance", False)if params.hidden_size % params.num_heads != 0:raise ValueError(f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"@@ -83,7 +94,11 @@ class Flux(nn.Module):self.hidden_size = params.hidden_sizeself.num_heads = params.num_headsself.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)- self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)+ self.img_in = (+ nn.Identity()+ if self.radiance+ else nn.Linear(self.in_channels, self.hidden_size, bias=True)+ )self.guidance_in = (MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if params.guidance_embed else nn.Identity()@@ -120,7 +135,32 @@ class Flux(nn.Module):])- self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels, chroma_modulation = self.chroma)+ if self.radiance:+ inject_radiance_modules(self, params)+ self.final_layer = None+ else:+ self.final_layer = LastLayer(+ self.hidden_size,+ 1,+ self.out_channels,+ chroma_modulation=self.chroma,+ use_linear=True,+ )++ def _apply_final_layer(self, tokens: Tensor, vec):+ final_layer = self.final_layer+ normed = final_layer.norm_final(tokens)+ if self.chroma:+ shift, scale = vec+ shift = shift.squeeze(1)+ scale = scale.squeeze(1)+ else:+ shift, scale = final_layer.adaLN_modulation(vec).chunk(2, dim=1)+ modulated = torch.addcmul(shift[:, None, :], 1 + scale[:, None, :], normed)+ if final_layer.linear is None:+ raise RuntimeError("Final layer projection is not available.")+ base_tokens = final_layer.linear(modulated)+ return modulated, base_tokensdef preprocess_loras(self, model_type, sd):new_sd = {}@@ -223,12 +263,33 @@ class Flux(nn.Module):pipeline =None,siglip_embedding = None,siglip_embedding_ids = None,+ radiance_cache: dict | None = None,) -> Tensor:- sz = len(txt_list)- # running on sequences img- img = self.img_in(img)- img_list = [img] if sz==1 else [img, img.clone()]+ sz = len(txt_list)+ height = width = None+ base_image_list = None+ if self.radiance:+ patch_size = self.patch_size+ # Determine spatial dimensions from image ids.+ base_ids = img_ids[:, :img_len, :]+ height = int(base_ids[..., 1].max().item() + 1) * patch_size+ width = int(base_ids[..., 2].max().item() + 1) * patch_size+ # Convert tokens back to image space.+ tokens = img[:, :img_len, :].transpose(1, 2)+ image = F.fold(+ tokens,+ output_size=(height, width),+ kernel_size=patch_size,+ stride=patch_size,+ )+ # Project image patches into hidden space.+ hidden = self.img_in_patch(image).flatten(2).transpose(1, 2)+ img = hidden+ base_image_list = [image] if sz == 1 else [image, image.clone()]+ else:+ img = self.img_in(img)+ img_list = [img] if sz == 1 else [img, img.clone()]if self.chroma:mod_index_length = 344@@ -277,13 +338,33 @@ class Flux(nn.Module):for img, pe, vec in zip(img_list, pe_list, vec_list):img[...]= block(x=img, vec=vec, pe=pe)img = pe = vec = None- img_list = [ img[:, txt.shape[1] : txt.shape[1] + img_len, ...] for img, txt in zip(img_list, txt_list)]+ img_list = [img[:, txt.shape[1] : txt.shape[1] + img_len, ...] for img, txt in zip(img_list, txt_list)]- if self.chroma: vec_list = [self.get_modulations(mod_vectors, "final")] * sz+ if self.radiance:+ final_vecs = None+ elif self.chroma:+ final_vecs = [self.get_modulations(mod_vectors, "final")] * sz+ else:+ final_vecs = vec_listout_list = []- for i, (img, vec) in enumerate(zip(img_list, vec_list)):- out_list.append( self.final_layer(img, vec)) # (N, T, patch_size ** 2 * out_channels)- img_list[i] = img = vec = None+ for i in range(sz):+ hidden_seq = img_list[i]+ if self.radiance:+ base_image = base_image_list[i]+ pred_tokens = apply_radiance_head(+ module=self,+ hidden_seq=hidden_seq,+ base_image=base_image,+ height=height,+ width=width,+ )+ base_image_list[i] = base_image = None+ img_list[i] = hidden_seq = None+ else:+ vec = final_vecs[i]+ modulated, pred_tokens = self._apply_final_layer(hidden_seq, vec)+ img_list[i] = hidden_seq = vec = modulated = None+ out_list.append(pred_tokens)return out_listdiff --git a/models/flux/modules/layers.py b/models/flux/modules/layers.pyindex 8cd981d..1af382c 100644--- a/models/flux/modules/layers.py+++ b/models/flux/modules/layers.py@@ -338,11 +338,23 @@ class SingleStreamBlock(nn.Module):class LastLayer(nn.Module):- def __init__(self, hidden_size: int, patch_size: int, out_channels: int, chroma_modulation = False):+ def __init__(+ self,+ hidden_size: int,+ patch_size: int,+ out_channels: int,+ chroma_modulation: bool = False,+ use_linear: bool = True,+ ):super().__init__()self.chroma_modulation = chroma_modulation+ self.use_linear = use_linearself.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)+ self.linear = (+ nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)+ 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))@@ -355,6 +367,8 @@ 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@@ -377,7 +391,7 @@ class DistilledGuidance(nn.Module):x = self.out_proj(x)return x-+class SigLIPMultiFeatProjModel(torch.nn.Module):"""diff --git a/models/flux/radiance.py b/models/flux/radiance.pynew file mode 100644index 0000000..bb74da9--- /dev/null+++ b/models/flux/radiance.py@@ -0,0 +1,223 @@+from dataclasses import dataclass+from functools import lru_cache++import torch+import torch.nn.functional as F+from torch import nn++from .modules.layers import RMSNorm+++class RadianceEmbedder(nn.Module):+ def __init__(self, in_channels: int, hidden_size_input: int, max_freqs: int, *, dtype: torch.dtype | None = torch.float32):+ super().__init__()+ self.in_channels = in_channels+ self.hidden_size_input = hidden_size_input+ self.max_freqs = max_freqs+ self.embedder_dtype = dtype+ self.embedder = nn.Sequential(nn.Linear(in_channels + max_freqs**2, hidden_size_input, bias=True))+ if dtype is not None:+ self.embedder.to(dtype=dtype)++ @lru_cache(maxsize=4)+ def _fetch_pos(self, patch_size: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:+ pos_x = torch.linspace(0, 1, patch_size, device=device, dtype=dtype)+ pos_y = torch.linspace(0, 1, patch_size, device=device, dtype=dtype)+ pos_y, pos_x = torch.meshgrid(pos_y, pos_x, indexing="ij")+ pos_x = pos_x.reshape(-1, 1, 1)+ pos_y = pos_y.reshape(-1, 1, 1)++ freqs = torch.linspace(0, self.max_freqs - 1, self.max_freqs, device=device, dtype=dtype)+ freqs_x = freqs[None, :, None]+ freqs_y = freqs[None, None, :]+ coeffs = (1 + freqs_x * freqs_y) ** -1++ dct = (torch.cos(pos_x * freqs_x * torch.pi) * torch.cos(pos_y * freqs_y * torch.pi) * coeffs).view(+ 1, -1, self.max_freqs**2+ )+ return dct++ def forward(self, inputs: torch.Tensor) -> torch.Tensor:+ batch, pixels, _ = inputs.shape+ patch_size = int(pixels**0.5)+ original_dtype = inputs.dtype+ target_dtype = self.embedder[0].weight.dtype++ inputs_cast = inputs.to(target_dtype)+ pos = self._fetch_pos(patch_size, inputs.device, target_dtype).repeat(batch, 1, 1)+ combined = torch.cat((inputs_cast, pos), dim=-1)+ embedded = self.embedder(combined)+ return embedded.to(original_dtype)+++class RadianceGLUBlock(nn.Module):+ def __init__(self, hidden_size_s: int, hidden_size_x: int, mlp_ratio: int):+ super().__init__()+ total_params = 3 * hidden_size_x**2 * mlp_ratio+ self.param_generator = nn.Linear(hidden_size_s, total_params)+ self.norm = RMSNorm(hidden_size_x)+ self.mlp_ratio = mlp_ratio++ def forward(self, x: torch.Tensor, s: torch.Tensor) -> torch.Tensor:+ batch, pixels, hidden = x.shape+ params = self.param_generator(s)+ gate, value, proj = params.chunk(3, dim=-1)++ gate = torch.nn.functional.normalize(gate.view(batch, hidden, hidden * self.mlp_ratio), dim=-2)+ value = torch.nn.functional.normalize(value.view(batch, hidden, hidden * self.mlp_ratio), dim=-2)+ proj = torch.nn.functional.normalize(proj.view(batch, hidden * self.mlp_ratio, hidden), dim=-2)++ residual = x+ x = self.norm(x)+ activated = torch.nn.functional.silu(torch.bmm(x, gate))+ gated = activated * torch.bmm(x, value)+ x = torch.bmm(gated, proj)+ return x + residual+++class RadianceFinalLayer(nn.Module):+ def __init__(self, hidden_size: int, out_channels: int):+ super().__init__()+ self.norm = RMSNorm(hidden_size)+ self.linear = nn.Linear(hidden_size, out_channels)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return self.linear(self.norm(x.movedim(1, -1))).movedim(-1, 1)+++class RadianceFinalLayerConv(nn.Module):+ def __init__(self, hidden_size: int, out_channels: int):+ super().__init__()+ self.norm = RMSNorm(hidden_size)+ self.conv = nn.Conv2d(hidden_size, out_channels, kernel_size=3, padding=1)+ nn.init.zeros_(self.conv.weight)+ nn.init.zeros_(self.conv.bias)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return self.conv(self.norm(x.movedim(1, -1)).movedim(-1, 1))+++@dataclass+class RadianceHead:+ patch_size: int+ img_in_patch: nn.Conv2d+ nerf_image_embedder: RadianceEmbedder+ nerf_blocks: nn.ModuleList+ nerf_final_layer: nn.Module | None+ nerf_final_layer_conv: nn.Module | None+++def inject_radiance_modules(module: nn.Module, params) -> RadianceHead:+ patch_size = params.radiance_patch_size+ img_in_patch = nn.Conv2d(+ params.out_channels,+ params.hidden_size,+ kernel_size=patch_size,+ stride=patch_size,+ bias=True,+ )+ nn.init.zeros_(img_in_patch.weight)+ nn.init.zeros_(img_in_patch.bias)++ nerf_image_embedder = RadianceEmbedder(+ params.out_channels,+ params.radiance_hidden_size,+ params.radiance_max_freqs,+ dtype=torch.float32,+ )+ nerf_blocks = nn.ModuleList(+ [+ RadianceGLUBlock(+ hidden_size_s=params.hidden_size,+ hidden_size_x=params.radiance_hidden_size,+ mlp_ratio=params.radiance_mlp_ratio,+ )+ for _ in range(params.radiance_depth)+ ]+ )++ final_layer = None+ final_layer_conv = None+ if params.radiance_final_head_type == "linear":+ final_layer = RadianceFinalLayer(+ params.radiance_hidden_size,+ out_channels=params.out_channels,+ )+ elif params.radiance_final_head_type == "conv":+ final_layer_conv = RadianceFinalLayerConv(+ params.radiance_hidden_size,+ out_channels=params.out_channels,+ )+ else:+ raise ValueError(f"Unsupported radiance_final_head_type: {params.radiance_final_head_type}")++ head = RadianceHead(+ patch_size=patch_size,+ img_in_patch=img_in_patch,+ nerf_image_embedder=nerf_image_embedder,+ nerf_blocks=nerf_blocks,+ nerf_final_layer=final_layer,+ nerf_final_layer_conv=final_layer_conv,+ )++ module.patch_size = head.patch_size+ module.img_in_patch = head.img_in_patch+ module.nerf_image_embedder = head.nerf_image_embedder+ module.nerf_blocks = head.nerf_blocks+ module.nerf_final_layer = head.nerf_final_layer+ module.nerf_final_layer_conv = head.nerf_final_layer_conv++ return head+++def _apply_nerf_blocks(+ module: nn.Module,+ hidden_seq: torch.Tensor,+ nerf_pixels: torch.Tensor,+) -> torch.Tensor:+ embed = module.nerf_image_embedder(nerf_pixels)+ for block in module.nerf_blocks:+ embed = block(embed, hidden_seq)+ return embed+++def apply_radiance_head(+ module: nn.Module,+ hidden_seq: torch.Tensor,+ base_image: torch.Tensor,+ *,+ height: int,+ width: int,+) -> torch.Tensor:+ patch_size = module.patch_size+ out_channels = module.out_channels+ batch, num_patches, hidden = hidden_seq.shape++ nerf_hidden = hidden_seq.reshape(batch * num_patches, hidden)+ nerf_pixels = F.unfold(base_image, kernel_size=patch_size, stride=patch_size)+ nerf_pixels = nerf_pixels.transpose(1, 2) # (B, NumPatches, C * P * P)+ nerf_pixels = nerf_pixels.reshape(batch * num_patches, out_channels, patch_size**2).transpose(1, 2)++ tile_size = getattr(module.params, "radiance_tile_size", 0)+ if tile_size > 0 and num_patches > tile_size:+ outputs = []+ for start in range(0, num_patches, tile_size):+ end = min(start + tile_size, num_patches)+ hidden_tile = nerf_hidden[start * batch : end * batch]+ pixel_tile = nerf_pixels[start * batch : end * batch]+ outputs.append(_apply_nerf_blocks(module, hidden_tile, pixel_tile))+ embed = torch.cat(outputs, dim=0)+ else:+ embed = _apply_nerf_blocks(module, nerf_hidden, nerf_pixels)++ embed = embed.transpose(1, 2) # (B*num_patches, hidden_size_x, patch_size^2)+ embed = embed.reshape(batch, num_patches, -1).transpose(1, 2) # (B, hidden_size_x*patch_size^2, NumPatches)+ image = F.fold(embed, output_size=(height, width), kernel_size=patch_size, stride=patch_size)++ final_layer = module.nerf_final_layer_conv or module.nerf_final_layer+ if final_layer is None:+ raise RuntimeError("Radiance head is missing a final projection layer.")+ image = final_layer(image)++ tokens = F.unfold(image, kernel_size=patch_size, stride=patch_size).transpose(1, 2)+ return tokensdiff --git a/models/flux/sampling.py b/models/flux/sampling.pyindex f9e1bb6..d0f3058 100644--- a/models/flux/sampling.py+++ b/models/flux/sampling.py@@ -1,8 +1,9 @@import math-from typing import Callable+from typing import Callable, Literalimport numpy as npimport torch+import torch.nn.functional as Ffrom einops import rearrange, repeatfrom PIL import Imagefrom torch import Tensor@@ -12,8 +13,6 @@ from .modules.autoencoder import AutoEncoderfrom .modules.conditioner import HFEmbedderfrom .modules.image_embedders import CannyImageEncoder, DepthImageEncoder, ReduxImageEncoderfrom .util import PREFERED_KONTEXT_RESOLUTIONS-from einops import rearrange, repeat-from typing import Literalimport torchvision.transforms.functional as TVF@@ -24,16 +23,31 @@ def get_noise(device: torch.device,dtype: torch.dtype,seed: int,+ *,+ channels: int = 16,+ patch_size: int = 2,):+ generator = torch.Generator(device=device).manual_seed(seed)+ if channels == 16 and patch_size == 2:+ return torch.randn(+ num_samples,+ channels,+ # allow for packing+ 2 * math.ceil(height / 16),+ 2 * math.ceil(width / 16),+ dtype=dtype,+ device=device,+ generator=generator,+ )+return torch.randn(num_samples,- 16,- # allow for packing- 2 * math.ceil(height / 16),- 2 * math.ceil(width / 16),+ channels,+ height,+ width,dtype=dtype,device=device,- generator=torch.Generator(device=device).manual_seed(seed),+ generator=generator,)@@ -59,16 +73,16 @@ def prepare_prompt(t5: HFEmbedder, clip: HFEmbedder, bs: int, prompt: str | list}-def prepare_img( img: Tensor) -> dict[str, Tensor]:+def prepare_img(img: Tensor, patch_size: int = 2) -> dict[str, Tensor]:bs, c, h, w = img.shape- img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)+ img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch_size, pw=patch_size)if img.shape[0] == 1 and bs > 1:img = repeat(img, "1 ... -> bs ...", bs=bs)- img_ids = torch.zeros(h // 2, w // 2, 3)- img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]- img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]+ img_ids = torch.zeros(h // patch_size, w // patch_size, 3)+ img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // patch_size)[:, None]+ img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // patch_size)[None, :]img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)return {@@ -144,7 +158,7 @@ def resizeinput(img):def prepare_kontext(- ae: AutoEncoder,+ ae: AutoEncoder | None,img_cond_list: list,seed: int,device: torch.device,@@ -152,6 +166,9 @@ def prepare_kontext(target_height: int | None = None,bs: int = 1,img_mask = None,+ *,+ patch_size: int = 2,+ noise_channels: int = 16,) -> tuple[dict[str, Tensor], int, int]:# load and encode the conditioning image@@ -174,6 +191,8 @@ def prepare_kontext(img_cond = np.array(img_cond)img_cond = torch.from_numpy(img_cond).float() / 127.5 - 1.0img_cond = rearrange(img_cond, "h w c -> 1 c h w")+ if ae is None:+ raise ValueError("Image conditioning is not supported for this model.")with torch.no_grad():img_cond_latents = ae.encode(img_cond.to(device))@@ -227,8 +246,10 @@ def prepare_kontext(device=device,dtype=torch.bfloat16,seed=seed,+ channels=noise_channels,+ patch_size=patch_size,)- return_dict.update(prepare_img(img))+ return_dict.update(prepare_img(img, patch_size=patch_size))return return_dict, target_height, target_width@@ -294,9 +315,18 @@ def denoise(img_msk_latents = None,img_msk_rebuilt = None,denoising_strength = 1,+ preview_meta = None,+ radiance_cache = None,):- kwargs = {'pipeline': pipeline, 'callback': callback, "img_len" : img.shape[1], "siglip_embedding": siglip_embedding, "siglip_embedding_ids": siglip_embedding_ids}+ kwargs = {+ 'pipeline': pipeline,+ 'callback': callback,+ "img_len": img.shape[1],+ "siglip_embedding": siglip_embedding,+ "siglip_embedding_ids": siglip_embedding_ids,+ "radiance_cache": radiance_cache,+ }if callback != None:callback(-1, None, True)@@ -392,7 +422,7 @@ def denoise(if callback is not None:preview = unpack_latent(img).transpose(0,1)- callback(i, preview, False)+ callback(i, preview, False, preview_meta=preview_meta)return img@@ -432,19 +462,19 @@ def prepare_multi_ip(img = get_noise( bs, target_height, target_width, device=device, dtype=torch.bfloat16, seed=seed)bs, c, h, w = img.shape# tgt img- img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)+ img = rearrange(img, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch_size, pw=patch_size)if img.shape[0] == 1 and bs > 1:img = repeat(img, "1 ... -> bs ...", bs=bs)- img_ids = torch.zeros(h // 2, w // 2, 3)- img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[:, None]- img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, :]+ img_ids = torch.zeros(h // patch_size, w // patch_size, 3)+ img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // patch_size)[:, None]+ img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // patch_size)[None, :]img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)img_cond_seq = img_cond_seq_ids = Noneif conditions_zero_start:pe_shift_w = pe_shift_h = 0else:- pe_shift_w, pe_shift_h = w // 2, h // 2+ pe_shift_w, pe_shift_h = w // patch_size, h // patch_sizefor cond_no, ref_img in enumerate(ref_imgs):_, _, ref_h1, ref_w1 = ref_img.shaperef_img = rearrange(@@ -497,3 +527,13 @@ def unpack(x: Tensor, height: int, width: int) -> Tensor:ph=2,pw=2,)+++def patches_to_image(x: Tensor, height: int, width: int, patch_size: int) -> Tensor:+ tokens = x.transpose(1, 2)+ return F.fold(+ tokens,+ output_size=(height, width),+ kernel_size=patch_size,+ stride=patch_size,+ )diff --git a/models/flux/util.py b/models/flux/util.pyindex 132e94f..d675095 100644--- a/models/flux/util.py+++ b/models/flux/util.py@@ -387,7 +387,47 @@ configs = {scale_factor=0.3611,shift_factor=0.1159,),- ),+ ),+ "flux-chroma-radiance": ModelSpec(+ repo_id="lodestones/Chroma1-Radiance",+ repo_flow="",+ repo_ae="ckpts/flux_vae.safetensors",+ params=FluxParams(+ in_channels=64,+ out_channels=3,+ vec_in_dim=768,+ context_in_dim=4096,+ hidden_size=3072,+ mlp_ratio=4.0,+ num_heads=24,+ depth=19,+ depth_single_blocks=38,+ axes_dim=[16, 56, 56],+ theta=10_000,+ qkv_bias=True,+ guidance_embed=False,+ chroma=True,+ radiance=True,+ radiance_patch_size=16,+ radiance_hidden_size=64,+ radiance_mlp_ratio=4,+ radiance_depth=4,+ radiance_max_freqs=8,+ radiance_tile_size=0,+ radiance_final_head_type="conv",+ ),+ ae_params=AutoEncoderParams(+ resolution=256,+ in_channels=3,+ ch=128,+ out_ch=3,+ ch_mult=[1, 2, 4, 4],+ num_res_blocks=2,+ z_channels=16,+ scale_factor=0.3611,+ shift_factor=0.1159,+ ),+ ),"flux-dev-canny": ModelSpec(repo_id="black-forest-labs/FLUX.1-Canny-dev",repo_flow="",diff --git a/shared/utils/plugins.py b/shared/utils/plugins.pyindex eab09fd..177d7fa 100644--- a/shared/utils/plugins.py+++ b/shared/utils/plugins.py@@ -3,7 +3,7 @@ import sysimport importlibimport importlib.utilimport inspect-from typing import Dict, Any, Optional, List, Union+from typing import Dict, Any, Optional, List, Union, Setfrom dataclasses import dataclassimport gradio as grimport traceback@@ -146,6 +146,7 @@ class PluginManager:if self.plugins_dir not in sys.path:sys.path.insert(0, self.plugins_dir)self.data_hooks: Dict[str, List[callable]] = {}+ self.restricted_globals: Set[str] = set()def get_plugins_info(self) -> List[Dict[str, str]]:plugins_info = []@@ -372,11 +373,22 @@ class PluginManager:if 'set_wgp_global' in global_references:plugin._set_wgp_global_func = global_references['set_wgp_global']for global_name in plugin.global_requests:- if global_name in global_references:+ if global_name in self.restricted_globals:+ setattr(plugin, global_name, None)+ elif global_name in global_references:setattr(plugin, global_name, global_references[global_name])except Exception as e:print(f" [!] ERROR injecting globals for {plugin_id}: {str(e)}")+ def update_global_reference(self, global_name: str, new_value: Any) -> None:+ safe_value = None if global_name in self.restricted_globals else new_value+ for plugin_id, plugin in self.plugins.items():+ try:+ if hasattr(plugin, '_global_requests') and global_name in plugin._global_requests:+ setattr(plugin, global_name, safe_value)+ except Exception as e:+ print(f" [!] ERROR updating global '{global_name}' for plugin {plugin_id}: {str(e)}")+def setup_ui(self) -> Dict[str, Dict[str, Any]]:tabs = {}for plugin_id, plugin in self.plugins.items():diff --git a/wgp.py b/wgp.pyindex d973288..c56ff75 100644--- a/wgp.py+++ b/wgp.py@@ -2796,11 +2796,12 @@ def save_quantized_model(model, model_type, model_filename, dtype, config_file,if not "quanto" in model_filename:pos = model_filename.rfind(".")model_filename = model_filename[:pos] + "_quanto_int8" + model_filename[pos+1:]-- if fl.locate_file(model_filename) is not None:++ model_filename = os.path.basename(model_filename)+ if fl.locate_file(model_filename, error_if_none= False) is not None:print(f"There isn't any model to quantize as quantized model '{model_filename}' aready exists")else:- model_filename_path = os.path.join(fl.get_download_folder(), model_filename)+ model_filename_path = os.path.join(fl.get_download_location(), model_filename)offload.save_model(model, model_filename_path, do_quantize= True, config_file_path=config_file)print(f"New quantized file '{model_filename}' had been created for finetune Id '{model_type}'.")if not model_filename in URLs:@@ -3353,11 +3354,11 @@ def get_gen_info(state):state["gen"] = cachereturn cache-def build_callback(state, pipe, send_cmd, status, num_inference_steps):+def build_callback(state, pipe, send_cmd, status, num_inference_steps, preview_meta=None):gen = get_gen_info(state)gen["num_inference_steps"] = num_inference_stepsstart_time = time.time()- def callback(step_idx = -1, latent = None, force_refresh = True, read_state = False, override_num_inference_steps = -1, pass_no = -1, denoising_extra =""):+ def callback(step_idx = -1, latent = None, force_refresh = True, read_state = False, override_num_inference_steps = -1, pass_no = -1, preview_meta=preview_meta, denoising_extra =""):in_pause = Falsewith gen_lock:process_status = gen.get("process_status", None)@@ -3427,9 +3428,18 @@ def build_callback(state, pipe, send_cmd, status, num_inference_steps):# progress(*progress_args)send_cmd("progress", progress_args)- if latent != None:- latent = latent.to("cpu", non_blocking=True)- send_cmd("preview", latent)+ if latent is not None:+ payload = pipe.prepare_preview_payload(latent, preview_meta) if hasattr(pipe, "prepare_preview_payload") else latent+ if isinstance(payload, dict):+ data = payload.copy()+ lat = data.get("latents")+ if torch.is_tensor(lat):+ data["latents"] = lat.to("cpu", non_blocking=True)+ payload = data+ elif torch.is_tensor(payload):+ payload = payload.to("cpu", non_blocking=True)+ if payload is not None:+ send_cmd("preview", payload)# gen["progress_args"] = progress_args@@ -5754,7 +5764,7 @@ def generate_video(if audio_only:import soundfile as sfaudio_path = os.path.join(image_save_path, file_name)- sf.write(audio_path, sample.squeeze(0), wan_model.sr)+ sf.write(audio_path, sample.squeeze(0), audio_sample_rate)video_path= audio_pathelif is_image:image_path = os.path.join(image_save_path, file_name)@@ -5890,11 +5900,27 @@ def prepare_generate_video(state):return gr.Button(visible= False), gr.Button(visible= True), gr.Column(visible= True), gr.update(visible= False)-def generate_preview(model_type, latents):+def generate_preview(model_type, payload):import einops- if latents is None: return None+ if payload is None:+ return None+ if isinstance(payload, dict):+ meta = {k: v for k, v in payload.items() if k != "latents"}+ latents = payload.get("latents")+ else:+ meta = {}+ latents = payload+ if latents is None:+ return None+ if not torch.is_tensor(latents):+ return Nonemodel_handler = get_model_handler(model_type)base_model_type = get_base_model_type(model_type)+ custom_preview = getattr(model_handler, "preview_latents", None)+ if callable(custom_preview):+ preview = custom_preview(base_model_type, latents, meta)+ if preview is not None:+ return previewif hasattr(model_handler, "get_rgb_factors"):latent_rgb_factors, latent_rgb_factors_bias = model_handler.get_rgb_factors(base_model_type )else: