"""BFS Head v1.1 on the existing Qwen Image 2.1 pipeline. This module never constructs a model or allocates a ZeroGPU lease. The caller downloads files with ``prepare`` before GPU allocation and holds its shared pipeline lock while calling ``generate``. Image 1 is the target body/scene; Image 2 is the reference face, matching the BFS author's internal image order. """ import math import random import re from guidance import guidance_values BFS_REPO = "Alissonerdx/BFS-Best-Face-Swap" BFS_FILE = "bfs_head_v1.1_qwen_2.1.safetensors" BFS_ADAPTER = "bfs-head-v1-1" TURBO_MODE = "Turbo (6 steps)" BASE_MODE = "Base (30 steps)" MODE_DMD2 = "DMD2 v1.5 (2 steps)" DMD2_SIGMAS = (1.0, 0.5) DMD2_SCHEDULER = {"shift_terminal": None, "use_dynamic_shifting": False, "shift": 1.0} MAX_SEED = 2**31 - 1 BFS_TRIGGER = "head_swap:" FACE_SWAP_PROMPT = ( "head_swap: start with as the base image, keeping its lighting, environment, and background. " "remove the head from completely and replace it with the head from , strictly preserving " "the hair, eye color, nose structure from . copy the direction of the eye, head rotation, micro " "expressions from , high quality, sharp details, 4k" ) def is_base(data): return str(data.get("face_mode", TURBO_MODE)).strip().lower().startswith("base") def is_dmd2(data): return data.get("face_mode") == MODE_DMD2 def specialist_guidance(data, dmd2): return (None, 1.0, 1) if dmd2 else guidance_values(data) def select_speed_adapter(base, dmd2, turbo_adapter, dmd2_adapter): if dmd2: if not dmd2_adapter: raise ValueError("Load the DMD2 adapter before entering the specialist GPU worker.") return dmd2_adapter return None if base else turbo_adapter def turbo_sigmas(steps): steps = int(steps) if not 4 <= steps <= 8: raise ValueError("Face Swap Turbo supports 4–8 steps; use 6 for the validated recipe.") if steps == 4: return [1.0, 0.75, 0.5, 0.25] return [1.0 - 0.125 * i / (steps - 4) for i in range(steps - 4)] + [0.875, 0.75, 0.5, 0.25] def prompt_with_trigger(prompt): """Keep the BFS Head v1.1 workflow trigger in editable/custom prompts.""" prompt = str(prompt or "").strip() or FACE_SWAP_PROMPT if not re.search(r"(?", "").replace("", "") def resolution(data): value = int(data.get("face_resolution", data.get("resolution", 1536))) if value not in (1024, 1536, 2048): raise ValueError("Face Swap resolution must be 1024, 1536 or 2048.") return value def estimate_seconds(data): """Reservation estimate based on the original BFS Space's measured recipe.""" res = resolution(data) dmd2 = is_dmd2(data) _, _, passes = specialist_guidance(data, dmd2) steps = len(DMD2_SIGMAS) if dmd2 else int(data.get("steps", 30 if is_base(data) else 6)) dimensions = _explicit_dimensions(data) output_area = dimensions[0] * dimensions[1] if dimensions else res * res reference_area = res * res # Denoising follows the selected output canvas. Larger cached references # still increase attention work, so retain a conservative geometric allowance # instead of treating a 1K output with two 1.5K references as a pure 1K run. effective_area = max(output_area, math.sqrt(output_area * reference_area)) / 1024**2 if effective_area <= 1.0: per_step = 0.65 elif effective_area <= 2.25: per_step = 0.65 + (effective_area - 1.0) / 1.25 * (2.0 - 0.65) else: per_step = 2.0 + (effective_area - 2.25) / 1.75 * (2.6 - 2.0) fixed = {1024: 6, 1536: 11, 2048: 9}[res] active = sum(bool(data.get(f"user_lora_{slot}_file") or data.get(f"user_lora_{slot}_ref")) and float(data.get(f"user_lora_{slot}_scale") or 0) > 0 for slot in range(1, 4)) return int(min(300, max(15, math.ceil((fixed + steps * per_step * passes + active * 4) * 1.15 + 3)))) def prepare(data, token=None): """Validate and fetch the small BFS adapter on CPU, never another base model. The returned copy contains normalized RGB images, the actual seed, and the local adapter path. The caller prepares its three optional LoRA slots using the existing common downloader/validator before entering the GPU worker. """ from PIL import Image, ImageOps from huggingface_hub import hf_hub_download out = dict(data) dmd2 = is_dmd2(out) negative, cfg, _ = specialist_guidance(out, dmd2) out.update(negative_prompt_text=negative or "", guidance_scale=cfg) for key, label in (("input_image_1", "Image 1 (target body/scene)"), ("input_image_2", "Image 2 (reference face)")): alias = "image1" if key == "input_image_1" else "image2" value = out.get(key) if value is None: value = out.get(alias) if value is None: raise ValueError(f"Face Swap needs {label}.") if not isinstance(value, Image.Image): if isinstance(value, dict): value = value.get("path") or value.get("name") if not value: raise ValueError(f"Face Swap needs {label}.") with Image.open(value) as opened: value = ImageOps.exif_transpose(opened).convert("RGB") else: value = ImageOps.exif_transpose(value).convert("RGB") out[key] = out[alias] = value out["face_resolution"] = resolution(out) base = is_base(out) out["face_mode"] = MODE_DMD2 if dmd2 else BASE_MODE if base else TURBO_MODE out["steps"] = len(DMD2_SIGMAS) if dmd2 else int(out.get("steps", 30 if base else 6)) if base: if not 4 <= out["steps"] <= 50: raise ValueError("Face Swap Base supports 4–50 steps; 30 is the default.") elif not dmd2: turbo_sigmas(out["steps"]) out["face_strength"] = float(out.get("face_strength", 1.0)) if not math.isfinite(out["face_strength"]) or not 0 <= out["face_strength"] <= 1.5: raise ValueError("BFS strength must be between 0 and 1.5.") out["seed"] = random.randint(0, MAX_SEED) if out.get("randomize_seed", True) else int(out.get("seed", 0)) if not 0 <= out["seed"] <= MAX_SEED: raise ValueError(f"Seed must be between 0 and {MAX_SEED}.") out["randomize_seed"] = False out["prompt"] = normalized_prompt(out.get("prompt")) _explicit_dimensions(out) # Reject malformed canvas controls before downloading. out["_bfs_path"] = hf_hub_download(repo_id=BFS_REPO, filename=BFS_FILE, token=token) return out def _explicit_dimensions(data): width, height = data.get("width"), data.get("height") if width is None and height is None: return None if width is None or height is None: raise ValueError("Set both canvas width and height for Face Swap.") width, height = int(width), int(height) if any(value < 256 or value > 8192 or value % 32 for value in (width, height)): raise ValueError("Face Swap canvas dimensions must be multiples of 32 between 256 and 8192.") if width * height > 2048**2: raise ValueError("Face Swap supports at most 2048² output area.") return width, height def convert_bfs_state_dict(state_dict, transformer): """Convert/validate BFS Comfy weights against the actual shared transformer. A fused SwiGLU update is ``[B_gate; B_up] @ A``. Both native projections reuse A; B is split by the destination row counts. Explicit alpha is folded into B, so the result is independent of Diffusers' exporter conversion. """ pairs = {} for key, value in state_dict.items(): match = re.fullmatch(r"(.+)\.lora_([AB])(?:\.default)?\.weight", key) if match: name, side = match.groups() else: match = re.fullmatch(r"(.+)\.lora_(down|up)\.weight", key) if match: name, side = match[1], {"down": "A", "up": "B"}[match[2]] else: match = re.fullmatch(r"(.+)\.(?:alpha|lora_alpha)", key) if not match: raise ValueError(f"Unsupported BFS tensor: {key}") name, side = match[1], "alpha" for prefix in ("base_model.model.", "model.diffusion_model.", "diffusion_model.", "transformer."): if name.startswith(prefix): name = name[len(prefix):] pair = pairs.setdefault(name, {}) if side in pair: raise ValueError(f"Duplicate BFS tensor: {name}.{side}") pair[side] = value if not pairs: raise ValueError("The BFS adapter has no LoRA pairs.") out, owners = {}, set() for name, pair in pairs.items(): if "A" not in pair or "B" not in pair: raise ValueError(f"Missing BFS LoRA pair: {name}") a, b = pair["A"], pair["B"] if len(a.shape) != 2 or len(b.shape) != 2 or a.shape[0] != b.shape[1] or a.shape[0] <= 0: raise ValueError(f"Invalid BFS LoRA dimensions: {name}") names = (name,) if name.endswith(".img_mlp.gate_up"): prefix = name[:-len("gate_up")] names = (prefix + "gate_layer", prefix + "proj") targets, start = [], 0 for native in names: try: shape = tuple(transformer.get_submodule(native).weight.shape) except (AttributeError, KeyError, IndexError) as error: raise ValueError(f"BFS requires a Qwen Image 2.1 transformer: missing {native}") from error if native in owners or len(shape) != 2 or shape[1] != a.shape[1]: raise ValueError(f"Incompatible or overlapping BFS target: {native}") owners.add(native) targets.append((native, start, start + shape[0])) start += shape[0] if b.shape[0] != start: raise ValueError(f"Incorrect BFS output rows for {name}: {b.shape[0]} != {start}") if "alpha" in pair: alpha = pair["alpha"] if tuple(alpha.shape) not in ((), (1,)): raise ValueError(f"Invalid BFS alpha: {name}") factor = float(alpha.item()) / a.shape[0] if not math.isfinite(factor): raise ValueError(f"Non-finite BFS alpha: {name}") if factor != 1.0: b = b.float() * factor for native, start, stop in targets: out[f"transformer.{native}.lora_A.weight"] = a out[f"transformer.{native}.lora_B.weight"] = b[start:stop].contiguous() if len(targets) > 1 else b return out def ensure_bfs(pipe, path): """Attach the adapter once to this pipeline; caller holds the pipeline lock.""" if getattr(pipe, "_shared_bfs_v11_loaded", False): return from safetensors.torch import load_file state_dict = load_file(path, device="cpu") pipe.load_lora_weights(convert_bfs_state_dict(state_dict, pipe.transformer), adapter_name=BFS_ADAPTER) pipe._shared_bfs_v11_loaded = True def kv_cache_fits(res, budget_gb, passes=1): prefix_tokens = 2 * (int(res) // 16)**2 return prefix_tokens * 32 * 2 * 4096 * 2 * passes <= float(budget_gb) * 1e9 def decode_latents(pipe, latents, height, width, tile_decode): """Tile only output decoding; reference encoding always remains untiled.""" import torch torch.cuda.empty_cache() vae = pipe.vae latents = pipe._unpack_latents(latents, height, width, pipe.vae_scale_factor).to(vae.dtype) mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(latents) std = torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to(latents) latents = latents * std + mean if tile_decode: vae.enable_tiling(tile_sample_min_height=1024, tile_sample_min_width=1024, tile_sample_stride_height=768, tile_sample_stride_width=768) try: image = vae.decode(latents, return_dict=False)[0][:, :, 0] finally: vae.disable_tiling() return pipe.image_processor.postprocess(image, output_type="pil")[0] def generate(pipe, data, *, turbo_adapter, base_scheduler_config, user_adapters=(), user_weights=(), kv_budget_gb=30.0, tile_decode=None, dmd2_adapter=None): """Run a prepared request inside the caller's one GPU worker and lock. ``base_scheduler_config`` must be captured immediately after loading the base pipeline, before setting Turbo's ``shift_terminal=None``. Optional adapters must already be loaded by the common three-slot loader. Success and failures both restore the entry scheduler and the default Turbo-only adapter state; every request must explicitly select its own adapters. """ import torch from diffusers import FlowMatchEulerDiscreteScheduler from diffusers.pipelines.qwenimage21.pipeline_qwenimage21 import calculate_dimensions if len(user_adapters) != len(user_weights): raise ValueError("Optional adapter names and weights must have the same length.") if any(name in (BFS_ADAPTER, turbo_adapter, dmd2_adapter) for name in user_adapters): raise ValueError("Built-in Face Swap and speed adapters cannot occupy an optional slot.") if base_scheduler_config is None: raise ValueError("The original Qwen base scheduler configuration is required.") res = resolution(data) target = data.get("input_image_1") if data.get("input_image_1") is not None else data.get("image1") reference = data.get("input_image_2") if data.get("input_image_2") is not None else data.get("image2") if target is None or reference is None: raise ValueError("Face Swap needs Image 1 (target) and Image 2 (reference face).") dimensions = _explicit_dimensions(data) if dimensions is None: width, height, _ = calculate_dimensions(res * res, target.width / target.height) else: width, height = dimensions base, dmd2 = is_base(data), is_dmd2(data) speed_adapter = select_speed_adapter(base, dmd2, turbo_adapter, dmd2_adapter) steps = len(DMD2_SIGMAS) if dmd2 else int(data.get("steps", 30 if base else 6)) sigmas = list(DMD2_SIGMAS) if dmd2 else None if base else turbo_sigmas(steps) scheduler_options = DMD2_SCHEDULER if dmd2 else {} if base else {"shift_terminal": None} negative, cfg, passes = specialist_guidance(data, dmd2) if tile_decode is None: tile_decode = bool(data.get("vae_tiling", res < 2048)) original_scheduler = pipe.scheduler try: ensure_bfs(pipe, data["_bfs_path"]) names = [BFS_ADAPTER] + ([speed_adapter] if speed_adapter else []) + list(user_adapters) weights = [float(data.get("face_strength", 1.0))] + ([1.0] if speed_adapter else []) + list(user_weights) combined = {} for name, weight in zip(names, weights): weight = float(weight) if not math.isfinite(weight): raise ValueError("LoRA strengths must be finite.") combined[name] = combined.get(name, 0.0) + weight pipe.set_adapters(list(combined), adapter_weights=list(combined.values())) pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config( base_scheduler_config, **scheduler_options ) pipe.vae.disable_tiling() with torch.inference_mode(): latents = pipe( prompt=normalized_prompt(data.get("prompt")), image=[target, reference], width=width, height=height, output_resolution=res, num_inference_steps=steps, sigmas=sigmas, true_cfg_scale=cfg, negative_prompt=negative, use_kv_cache=kv_cache_fits(res, kv_budget_gb, passes), generator=torch.Generator(device="cuda").manual_seed(int(data["seed"])), output_type="latent", ).images return decode_latents(pipe, latents, height, width, bool(tile_decode)).convert("RGB") finally: pipe.scheduler = original_scheduler pipe.vae.disable_tiling() pipe.set_adapters([turbo_adapter], adapter_weights=[1.0])