"""Read and write MiniMax H3 RefMods, and turn one into a DiT reference block. The file format is Luisa's (ComfyUI-MiniMaxH3Mod, format version 4 standalone, version 5 bundle read-only). This module does not import that pack. A file written here is a file her loader can open, and a file she wrote is a file the rail can read. The stored tensor is the VAE latent. Decoding it and encoding it again is a different reference: the pooled latent would be gone. Callers hand the DiT `visual_block()`, and show Qwen the pictures the builder encoded when the file keeps them (`looks`), or a decode of the latent when it does not. """ from __future__ import annotations import hashlib import json import math import os import re import tempfile import threading from collections import OrderedDict import torch import torch.nn.functional as F TAG = "HandTieClips" META_KEY = "refmod_meta" AUDIO_META_KEY = "audio_refmod_meta" REFLORA_META_KEYS = ("h3_refmod_meta", "minimax_h3_refmod_meta") FORMAT_VERSION = 4 BUNDLE_VERSION = 5 # The pictures the builder encoded, uint8 [N,H,W,3] beside `latent`. Luisa's # loader reads `latent` by key and her bundle writer carries unknown tensors # through, so the extra key does not cost the file its portability. LOOKS_KEY = "looks" SKIP_DIRS = {".git", "__pycache__", "graph_presets"} CONCEPT_ROLES = ( "generic", "identity", "wardrobe", "bodyshape", "helper", "pose_motion", "background", "style", ) STEP_CURVES = ("full", "early_lock", "late_detail", "fade", "mid_peak") MAX_COPIES = 3 MAX_STRENGTH = 3.0 def _fail(msg): raise ValueError(f"{TAG}: {msg}") def source_problem(name, kinds=("image", "video")): """Why a mod_plan source cannot be used, as a sentence, or None. None means nothing is detectably wrong -- present, and a kind this slot takes. It does NOT mean a loader will succeed, so a caller that already watched one fail supplies its own `or "... could not be read"`. Having this return that sentence unconditionally made a perfectly good voice fail the build. A loader returning None means absent, wrong kind, or unreadable, and reporting all three as "not in h3_refs" sent someone looking for a file that was sitting right there. A RefMod is visual, so an audio pick is the likely mistake and gets told where a voice actually goes. """ try: # the offline checkers import this module without its package from . import media as _media except ImportError: import media as _media if not str(name or "").strip(): return None if _media.resolve(name) is None: return f"{name} is not in h3_refs" kind = _media.kind_of(name) if kind not in kinds: if kind == "audio": return (f"{name} is a sound file. A RefMod's pictures are " f"encoded; its voice goes in the voice slot.") want = " or ".join("picture" if k == "image" else k for k in kinds) return f"{name} is a {kind or 'unknown'} file, not a {want}" return None def _ext_kind(name): """'image' | 'video' | 'audio' | None. `media.kind_of`, reached without importing it, so the parser stays free of the loaders.""" try: from . import media as _media except ImportError: import media as _media return _media.kind_of(name) def parse_mod_plan(text): """`(stills, clip, voice)` from the builder's `mod_plan` widget. `stills` is a list of reference filenames in the order they will occupy latent frames. `clip` is `{"file", "start", "end", "frames"}` or None. An empty widget is `([], None, "")`, which leaves the wired inputs in charge. `voice` is a sound file in h3_refs, and is the one field here that is not encoded into the latent -- a RefMod holds pictures. It is recorded so a reference row citing this mod inherits the voice instead of the author having to name it twice, which is what makes the file a character rather than a face. It may be written as `{"file", "start", "end"}` to trim it; `voice_window` reads that window, and this returns the name alone so every caller that only needs the file is unchanged. A still may be written as a bare string or as `{"file": ...}`; the panel writes the object form, a hand-typed plan is allowed either. """ if isinstance(text, (dict, list)): data = text else: raw = (text or "").strip() if not raw: return [], None, "" try: data = json.loads(raw) except ValueError as exc: _fail(f"mod_plan is not valid JSON: {exc}") if isinstance(data, list): data = {"stills": data} if not isinstance(data, dict): _fail("mod_plan must be a JSON object or a list of stills") def _name(entry, where): if isinstance(entry, str): name = entry elif isinstance(entry, dict): name = entry.get("file") or entry.get("name") or "" else: _fail(f"{where} must be a filename or an object with file") name = str(name).strip() if not name: _fail(f"{where} has no file") if "\\" in name or "/" in name or name in (".", ".."): _fail(f"{where}: {name!r} must be a plain filename in h3_refs") return name stills_raw = data.get("stills") or [] if not isinstance(stills_raw, list): _fail("mod_plan stills must be a list") stills, seen = [], set() for i, entry in enumerate(stills_raw): name = _name(entry, f"mod_plan still {i + 1}") if name in seen: _fail(f"mod_plan lists {name} twice. Each still is one latent frame.") seen.add(name) stills.append(name) clip_raw = data.get("clip") clip = None if clip_raw not in (None, "", {}, []): if isinstance(clip_raw, str): clip_raw = {"file": clip_raw} if not isinstance(clip_raw, dict): _fail("mod_plan clip must be a filename or an object") clip = { "file": _name(clip_raw, "mod_plan clip"), "start": max(0.0, float(clip_raw.get("start") or 0.0)), "end": max(0.0, float(clip_raw.get("end") or 0.0)), "frames": max(0, int(clip_raw.get("frames") or 0)), } if clip["end"] and clip["end"] <= clip["start"]: _fail(f"mod_plan clip window ends at {clip['end']}s, which is not " f"after its {clip['start']}s start") if _ext_kind(clip["file"]) == "audio": _fail(f"mod_plan clip {clip['file']} is a sound file. A voice goes " f"in the RefMod's voice slot, not in the clip slot.") voice = data.get("voice") or "" if voice not in (None, "", {}, []): voice = _name(voice, "mod_plan voice") if _ext_kind(voice) != "audio": _fail(f"mod_plan voice {voice} is not a sound file") voice_window(data) # a reversed window fails here, before any encode else: voice = "" return stills, clip, voice def tensor_digest(t): """Same bytes as store.tensor_digest. Kept here so a file read does not import the hop store.""" a = t.detach().cpu().contiguous().numpy() h = hashlib.sha256() h.update(str(a.shape).encode()) h.update(str(a.dtype).encode()) h.update(a.tobytes()) return h.hexdigest()[:16] def register_folder(): """Make `models/refmods` a folder_paths root. Safe to call more than once.""" import folder_paths base = os.path.join(folder_paths.models_dir, "refmods") os.makedirs(base, exist_ok=True) try: known = [os.path.normcase(os.path.normpath(p)) for p in folder_paths.get_folder_paths("refmods")] except Exception: known = [] if os.path.normcase(os.path.normpath(base)) not in known: folder_paths.add_model_folder_path("refmods", base) return base def roots(): """Every directory a RefMod may live in, the registered root first.""" import folder_paths try: found = list(folder_paths.get_folder_paths("refmods")) except Exception: found = [] base = os.path.join(folder_paths.models_dir, "refmods") if not found: found = [base] elif os.path.normcase(os.path.normpath(base)) not in { os.path.normcase(os.path.normpath(p)) for p in found}: found.insert(0, base) return found def _lora_roots(): """Registered LoRA folders for unified RefLoRA discovery.""" import folder_paths try: return list(folder_paths.get_folder_paths("loras")) except Exception: base = os.path.join(folder_paths.models_dir, "loras") return [base] if os.path.isdir(base) else [] def _clean_name(name): """A relative safetensors stem. `..` and an absolute path are refused.""" raw = str(name or "").strip().replace("\\", "/") prefix = "" if raw.lower().startswith("lora:"): prefix = "lora:" raw = raw[5:] if raw.lower().endswith(".safetensors"): raw = raw[: -len(".safetensors")] raw = raw.strip("/") if not raw: return "" parts = raw.split("/") if any(p in ("", ".", "..") for p in parts): _fail(f"refmod name {name!r} is not a file under the refmods folder") return prefix + "/".join(parts) def resolve(name): """Absolute `.safetensors` path for a refmod (or `lora:` RefLoRA) name, or None.""" stem = _clean_name(name) if not stem: return None is_lora = stem.lower().startswith("lora:") inner = stem[5:] if is_lora else stem rel = inner.replace("/", os.sep) + ".safetensors" search_roots = _lora_roots() if is_lora else roots() for root in search_roots: base = os.path.normpath(root) full = os.path.normpath(os.path.join(base, rel)) if full != base and not full.startswith(base + os.sep): continue if os.path.isfile(full): return full return None def _clean_desc_text(text): s = str(text or "").strip() # Clean legacy widget-migration artifact ("0") or empty sentinels. if s in ("0", "none", "None", "null"): return "" return s def _member_tokens(member): if not isinstance(member, dict): return 0 if member.get("kind") == "audio": t = int(member.get("ref_audio_t") or member.get("latent_t") or 0) return 2 * t t = int(member.get("latent_t") or 1) h = int(member.get("latent_h") or 0) w = int(member.get("latent_w") or 0) return max(0, t * (h // 2) * (w // 2)) # LRU keyed by (path, mtime_ns, size). It used to clear() when full, which with # more than 512 LoRAs emptied it partway through every listing() walk, so each # walk reopened every header (issue #1). Entries are small; evict oldest only. _HEADER_CACHE = OrderedDict() _HEADER_CACHE_LOCK = threading.Lock() _HEADER_CACHE_MAX = 8192 def _stat_sig(path): try: st = os.stat(path) return (os.path.normcase(os.path.normpath(path)), int(st.st_mtime_ns), int(st.st_size)) except OSError: return None def _invalidate_header_cache(path=None): with _HEADER_CACHE_LOCK: if path is None: _HEADER_CACHE.clear() return norm = os.path.normcase(os.path.normpath(path)) for k in [k for k in _HEADER_CACHE if k[0] == norm]: _HEADER_CACHE.pop(k, None) def _scan_safetensors_header(path): """Single safe_open inspection returning (is_reflora, meta, has_looks_key, has_audio_key).""" sig = _stat_sig(path) if sig is None: return (False, None, False, False) with _HEADER_CACHE_LOCK: hit = _HEADER_CACHE.get(sig) if hit is not None: _HEADER_CACHE.move_to_end(sig) if hit is not None: return hit from safetensors import safe_open is_reflora = False meta = None has_looks_key = False has_audio_key = False try: with safe_open(path, framework="pt") as handle: hdr_meta = handle.metadata() or {} keys = list(handle.keys()) key_set = set(keys) is_reflora = any( k == "refmod.latent" or k == "refmod.samples" or k.startswith("refmod.ref_") for k in key_set ) has_looks_key = any( k == LOOKS_KEY or k.startswith("looks_") or k.startswith("enc_") or k.startswith("refmod.looks") for k in key_set ) has_audio_key = any("audio_latent" in k for k in key_set) raw = hdr_meta.get(META_KEY) or hdr_meta.get(AUDIO_META_KEY) if raw: parsed = json.loads(raw) meta = parsed if isinstance(parsed, dict) else None else: for rk in REFLORA_META_KEYS: if hdr_meta.get(rk): parsed = json.loads(hdr_meta[rk]) if isinstance(parsed, dict): data = dict(parsed) data["_reflora"] = True if "kind" not in data: if "refmod.latent" in key_set: shape = handle.get_slice("refmod.latent").get_shape() data["kind"] = "video" if (len(shape) >= 3 and shape[2] > 1) else "image" if len(shape) == 5: data.setdefault("latent_t", int(shape[2])) data.setdefault("latent_h", int(shape[3])) data.setdefault("latent_w", int(shape[4])) else: data["kind"] = "image" meta = data break if meta is None and "refmod.latent" in key_set: shape = handle.get_slice("refmod.latent").get_shape() meta = { "name": os.path.splitext(os.path.basename(path))[0], "kind": "video" if (len(shape) >= 3 and shape[2] > 1) else "image", "latent_t": int(shape[2]) if len(shape) == 5 else 1, "latent_h": int(shape[3]) if len(shape) == 5 else 0, "latent_w": int(shape[4]) if len(shape) == 5 else 0, "_reflora": True, "_format_version": 4, } except Exception: return (False, None, False, False) res = (is_reflora, meta, has_looks_key, has_audio_key) with _HEADER_CACHE_LOCK: _HEADER_CACHE[sig] = res _HEADER_CACHE.move_to_end(sig) while len(_HEADER_CACHE) > _HEADER_CACHE_MAX: _HEADER_CACHE.popitem(last=False) return res def _meta_summary(meta, full=None, _scanned=None): kind = str((meta or {}).get("kind") or "refmod") role = str((meta or {}).get("concept_type") or (meta or {}).get("role") or "generic").strip() if role not in CONCEPT_ROLES: role = "generic" step_curve = str((meta or {}).get("default_step_curve") or "full").strip() if step_curve not in STEP_CURVES: step_curve = "full" ver = int((meta or {}).get("_format_version") or 4) fmt = "reflora" if (meta or {}).get("_reflora") else (f"v{ver}" if ver >= 4 else "v4") has_audio_latent = False members_count = 1 tokens = 0 has_looks = bool(int((meta or {}).get("looks") or 0)) if kind == "bundle": mem = [m for m in ((meta or {}).get("members") or []) if isinstance(m, dict)] members_count = len(mem) vis_mem = [m for m in mem if m.get("kind") in ("image", "video")] has_audio_latent = any(m.get("kind") == "audio" for m in mem) tokens = sum(_member_tokens(m) for m in vis_mem) if any(int(m.get("looks") or 0) > 0 for m in vis_mem): has_looks = True elif kind == "audio": has_audio_latent = True tokens = _member_tokens(meta) else: tokens = _member_tokens(meta) if full and not has_looks: sc = _scanned if _scanned is not None else _scan_safetensors_header(full) has_looks = bool(sc[2]) if not has_audio_latent: has_audio_latent = bool(sc[3]) return { "kind": kind, "role": role, "default_step_curve": step_curve, "format": fmt, "tokens": tokens, "members_count": members_count, "has_audio_latent": has_audio_latent, "has_looks": has_looks, } def listing(): """`[{name, kind, role, tokens, ...}]` for the editor. `name` has no extension.""" rows = [] seen = set() for root in roots(): if not os.path.isdir(root): continue for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".")] for filename in filenames: if not filename.endswith(".safetensors"): continue full = os.path.join(dirpath, filename) rel = os.path.relpath(full, root).replace("\\", "/") stem = rel[: -len(".safetensors")] if stem in seen: continue seen.add(stem) try: mtime = os.path.getmtime(full) except OSError: continue sc = _scan_safetensors_header(full) meta = sc[1] info = _meta_summary(meta, full=full, _scanned=sc) rows.append((mtime, stem, info, description_of(meta), _listed_voice(meta))) # Also surface unified RefLoRAs from models/loras/ that actually embed `refmod.*` latents. for root in _lora_roots(): if not os.path.isdir(root): continue for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".")] for filename in filenames: if not filename.endswith(".safetensors"): continue full = os.path.join(dirpath, filename) sc = _scan_safetensors_header(full) if not sc[0]: continue rel = os.path.relpath(full, root).replace("\\", "/") stem = "lora:" + rel[: -len(".safetensors")] if stem in seen: continue seen.add(stem) try: mtime = os.path.getmtime(full) except OSError: continue meta = sc[1] info = _meta_summary(meta, full=full, _scanned=sc) rows.append((mtime, stem, info, description_of(meta), _listed_voice(meta))) rows.sort(reverse=True) # `voice` is what a row citing this mod inherits, so the rail can show # and trim the recording that will actually ride. return [{ "name": n, "kind": info["kind"], "role": info["role"], "default_step_curve": info["default_step_curve"], "format": info["format"], "tokens": info["tokens"], "members_count": info["members_count"], "has_audio_latent": info["has_audio_latent"], "has_looks": info["has_looks"], "description": d, "voice": v, } for _m, n, info, d, v in rows] def _listed_voice(meta): """The header's voice as `{"file", "start", "end"}`, or None.""" plan = (meta or {}).get("mod_plan") if isinstance(meta, dict) else None if not isinstance(plan, dict): return None try: _stills, _clip, voice = parse_mod_plan(plan) start, end = voice_window(plan) except ValueError: return None if not voice: return None return {"file": voice, "start": start, "end": end} def description_of(meta): """The caption a RefMod carries in its header, or "". Luisa's layout has had a `description` field all along; this pack wrote it empty until the builder grew one, and other builders fill it. The editor offers it as the row's `desc` -- it is never read on the render path, so a caption the person has not accepted reaches no prompt. A bundle's own field wins, then the member `load_visual` would pick. """ if not isinstance(meta, dict): return "" text = _clean_desc_text(meta.get("description")) if text or meta.get("kind") != "bundle": return text for member in meta.get("members") or []: if isinstance(member, dict) and member.get("kind") in ("image", "video"): cand = _clean_desc_text(member.get("description")) if cand: return cand return "" def stamp(names): """`name:mtime` for IS_CHANGED. A missing file stays a stable token.""" bits = [] for name in names: if not name: continue path = resolve(name) try: bits.append(f"{name}:{os.path.getmtime(path)}" if path else f"{name}:missing") except OSError: bits.append(f"{name}:missing") return "|".join(bits) def _is_reflora_file(path): """Fast header check for unified LoRA + RefMod `.safetensors` containers.""" return bool(_scan_safetensors_header(path)[0]) def read_meta(path): """Header JSON, or None. Supports v4/v5 `refmod_meta`, `audio_refmod_meta`, and RefLoRA metadata.""" meta = _scan_safetensors_header(path)[1] return dict(meta) if isinstance(meta, dict) else None def voice_window(plan): """`(start, end)` seconds of the mod_plan's voice. `(0, 0)` is the whole file. Same sentinel as `media.clip_window`: an end of 0 is the end of the file. Only the object form of `voice` carries a window. """ if not isinstance(plan, dict): try: plan = json.loads(plan) if str(plan or "").strip() else {} except ValueError: return 0.0, 0.0 entry = plan.get("voice") if isinstance(plan, dict) else None if not isinstance(entry, dict): return 0.0, 0.0 try: start = max(0.0, float(entry.get("start") or 0.0)) end = max(0.0, float(entry.get("end") or 0.0)) except (TypeError, ValueError): _fail("mod_plan voice window must be numbers of seconds") if end and end <= start: _fail(f"mod_plan voice window ends at {end:g}s, which is not after " f"its {start:g}s start") return start, end def stored_plan(name): """The `mod_plan` a saved RefMod was built from, or `{}`. Empty for a mod built through the sockets, for one written before this field existed, or for a file that is not a RefMod at all -- all three mean the same thing to a caller: nothing to reload. """ path = resolve(name) if path is None: return {} meta = read_meta(path) or {} plan = meta.get("mod_plan") if not isinstance(plan, dict): return {} try: stills, clip, voice = parse_mod_plan(plan) except ValueError: # A header that no longer parses is not worth failing a panel over. return {} if not (stills or clip or voice): return {} out = {"stills": stills, "clip": clip, "voice": voice} if voice: try: start, end = voice_window(plan) except ValueError: start, end = 0.0, 0.0 if start or end: out["voice_start"], out["voice_end"] = start, end return out def stored_voice(name): """`{"file", "start", "end"}` for the voice a saved RefMod names, or `{}`. A reference row that cites the mod and leaves its own voice empty inherits this, window and all, so the character is assembled once in the builder and the rail only has to point at it. """ plan = stored_plan(name) if not plan.get("voice"): return {} return {"file": str(plan["voice"]), "start": float(plan.get("voice_start") or 0.0), "end": float(plan.get("voice_end") or 0.0)} def _load_tensor(path, key): from safetensors.torch import load_file # Clone releases the file mapping so Windows can overwrite the file later. return load_file(path, device="cpu")[key].clone() def _load_looks(path, key=LOOKS_KEY): """The kept pictures (`[N,H,W,3]` uint8), or None when absent.""" from safetensors import safe_open try: with safe_open(path, framework="pt", device="cpu") as handle: keys = set(handle.keys()) if key not in keys: return None looks = handle.get_tensor(key).clone() except Exception: return None if looks.ndim == 3 and looks.shape[-1] == 3: looks = looks.unsqueeze(0) if looks.ndim != 4 or looks.shape[-1] != 3 or looks.shape[0] < 1: print(f"[{TAG}] {os.path.basename(path)}: {key} tensor is " f"{tuple(looks.shape)}, not [N,H,W,3]. Showing Qwen a decode.", flush=True) return None return looks def _load_enc_jpegs(path, member_indices=None): """Decode Fantastic/H3RefModPicker `enc_N` JPEG byte tensors if present.""" from safetensors import safe_open try: with safe_open(path, framework="pt", device="cpu") as handle: keys = [k for k in handle.keys() if k.startswith("enc_")] if not keys: return None keys.sort(key=lambda s: int(s.split("_", 1)[1]) if s.split("_", 1)[1].isdigit() else 9999) if member_indices is not None: want = {f"enc_{i}" for i in member_indices} # Strict: a member without its own enc_N has none. Falling back to # every enc_ key showed Qwen the other members' photos as this one. keys = [k for k in keys if k in want] if not keys: return None from PIL import Image # noqa: PLC0415 import io # noqa: PLC0415 import numpy as np # noqa: PLC0415 frames = [] for k in keys: raw = handle.get_tensor(k).numpy().tobytes() with Image.open(io.BytesIO(raw)) as im: arr = np.array(im.convert("RGB"), dtype=np.uint8, copy=True) frames.append(torch.from_numpy(arr)) if not frames: return None # Only stack if dimensions match; otherwise return list or first frame. h0, w0 = frames[0].shape[:2] if all(f.shape[:2] == (h0, w0) for f in frames): return torch.stack(frames, dim=0) return frames[0].unsqueeze(0) except Exception: return None def _as_visual(meta, latent, where): kind = str(meta.get("kind") or "") if kind not in ("image", "video"): _fail(f"{where} is a '{kind or 'unknown'}' RefMod. This pass reads " f"image and video mods.") if latent.ndim != 5 or latent.shape[0] != 1 or latent.shape[1] != 24: _fail(f"{where} latent must be [1,24,T,H,W], got {tuple(latent.shape)}") _b, _c, t, h, w = latent.shape if t < 1 or h < 2 or w < 2 or h % 2 or w % 2: _fail(f"{where} latent grid {t}x{h}x{w} is not a usable visual ref") if kind == "image": latent = latent[:, :, :1] t = 1 latent = latent.contiguous() return { "kind": "image" if t == 1 else "video", "latent": latent, "latent_t": int(t), "latent_h": int(h), "latent_w": int(w), "name": str(meta.get("name") or where), "mode": str(meta.get("mode") or ""), "role": str(meta.get("concept_type") or meta.get("role") or "generic"), "default_step_curve": (norm_step_curve(meta.get("default_step_curve")) if meta.get("default_step_curve") else (third_party_step_curve(meta) or "full")), "digest": tensor_digest(latent), "tokens": int(t) * (int(h) // 2) * (int(w) // 2), } def _first_tensor(*cands): for t in cands: if t is not None: return t return None def _extract_looks_from_handle(handle, keys, key=LOOKS_KEY): if key not in keys: return None looks = handle.get_tensor(key).clone() if looks.ndim == 3 and looks.shape[-1] == 3: looks = looks.unsqueeze(0) if looks.ndim != 4 or looks.shape[-1] != 3 or looks.shape[0] < 1: return None return looks def _extract_enc_jpegs_from_handle(handle, keys, member_indices=None): enc_keys = [k for k in keys if k.startswith("enc_")] if not enc_keys: return None enc_keys.sort(key=lambda s: int(s.split("_", 1)[1]) if s.split("_", 1)[1].isdigit() else 9999) if member_indices is not None: want = {f"enc_{i}" for i in member_indices} # Strict, as in _load_enc_jpegs: never another member's photos. enc_keys = [k for k in enc_keys if k in want] if not enc_keys: return None try: from PIL import Image # noqa: PLC0415 import io # noqa: PLC0415 import numpy as np # noqa: PLC0415 frames = [] for k in enc_keys: raw = handle.get_tensor(k).numpy().tobytes() with Image.open(io.BytesIO(raw)) as im: arr = np.array(im.convert("RGB"), dtype=np.uint8, copy=True) frames.append(torch.from_numpy(arr)) if not frames: return None h0, w0 = frames[0].shape[:2] if all(f.shape[:2] == (h0, w0) for f in frames): return torch.stack(frames, dim=0) return frames[0].unsqueeze(0) except Exception: return None def load_bundle_visuals(name, members_filter=None): """All visual blocks inside `name` (v4 standalone, v5 bundle, or RefLoRA). Returns a list of visual dicts. `members_filter` (optional list of 0-based indices) restricts a v5 bundle to only those visual members without rebuilding. """ path = resolve(name) if path is None: return [] meta = read_meta(path) if not isinstance(meta, dict): _fail(f"{name} has no {META_KEY} header. It is not a RefMod.") from safetensors import safe_open # RefLoRA container (`refmod.latent` / `refmod.samples` / `refmod.ref_*`) if meta.get("_reflora"): out = [] with safe_open(path, framework="pt", device="cpu") as fh: keys = set(fh.keys()) if "refmod.latent" in keys: lat = fh.get_tensor("refmod.latent").clone() item = _as_visual(meta, lat, name) looks = _first_tensor( _extract_looks_from_handle(fh, keys, "refmod.looks"), _extract_looks_from_handle(fh, keys, LOOKS_KEY), ) item["looks"] = looks item["looks_digest"] = tensor_digest(looks) if looks is not None else None item["member_index"] = 0 out.append(item) else: ref_keys = sorted( [k for k in keys if k.startswith("refmod.ref_")], key=lambda s: int(s.split("_")[-1]) if s.split("_")[-1].isdigit() else 9999, ) for idx, rk in enumerate(ref_keys): lat = fh.get_tensor(rk).clone() if lat.ndim != 5 or lat.shape[1] != 24: continue k_meta = {"name": f"{name}#{idx}", "kind": "video" if lat.shape[2] > 1 else "image"} item = _as_visual(k_meta, lat, name) looks = _extract_looks_from_handle(fh, keys, f"refmod.looks_{idx}") item["looks"] = looks item["looks_digest"] = tensor_digest(looks) if looks is not None else None item["member_index"] = idx out.append(item) if not out: _fail(f"{name} RefLoRA has no MiniMax-H3 [1,24,T,H,W] visual latent.") return out if meta.get("kind") == "bundle": members = meta.get("members") or [] if not isinstance(members, list): _fail(f"{name} bundle has no members list") wanted = None if members_filter: wanted = {int(x) for x in members_filter} out = [] vis_indices = [i for i, m in enumerate(members) if isinstance(m, dict) and m.get("kind") in ("image", "video")] if not vis_indices: _fail(f"{name} has no visual member. Audio RefMods are not applied " f"by this node.") with safe_open(path, framework="pt", device="cpu") as fh: keys = set(fh.keys()) for i in vis_indices: if wanted is not None and i not in wanted: continue member = members[i] latent = fh.get_tensor(f"ref_{i}").clone() loaded = _as_visual(member, latent, name) looks = _first_tensor( _extract_looks_from_handle(fh, keys, f"looks_{i}"), _extract_looks_from_handle(fh, keys, LOOKS_KEY) if len(vis_indices) == 1 else None, # one visual member: its photos may be stored unnumbered-to-it _extract_enc_jpegs_from_handle(fh, keys, [i] if len(vis_indices) > 1 else None), ) loaded["looks"] = looks loaded["looks_digest"] = tensor_digest(looks) if looks is not None else None loaded["member_index"] = i if member.get("yaw") is not None: loaded["yaw"] = float(member["yaw"]) if loaded.get("role") == "generic" and meta.get("concept_type"): loaded["role"] = str(meta.get("concept_type")) if loaded.get("default_step_curve") == "full" and meta.get("default_step_curve"): loaded["default_step_curve"] = norm_step_curve(meta.get("default_step_curve")) if loaded.get("default_step_curve") == "full": loaded["default_step_curve"] = third_party_step_curve(meta) or "full" out.append(loaded) if not out and wanted is not None: _fail(f"{name}: selected member indices {sorted(wanted)} matched no visual member.") return out if meta.get("kind") == "audio": _fail(f"{name} is an audio-only RefMod. Visual references require an image or video RefMod.") with safe_open(path, framework="pt", device="cpu") as fh: keys = set(fh.keys()) latent = fh.get_tensor("latent").clone() loaded = _as_visual(meta, latent, name) looks = _first_tensor( _extract_looks_from_handle(fh, keys, LOOKS_KEY), _extract_enc_jpegs_from_handle(fh, keys), ) loaded["looks"] = looks loaded["looks_digest"] = tensor_digest(looks) if looks is not None else None loaded["member_index"] = 0 return [loaded] def load_visual(name): """The first visual latent behind `name`, or None when the file is absent.""" items = load_bundle_visuals(name) if not items: return None if len(items) > 1: print(f"[{TAG}] {name}: loaded primary visual member ({len(items)} total in bundle)", flush=True) return items[0] def load_audio_latent(name): """Pre-encoded `[1,32,2,T]` audio latent inside `name`, or None.""" path = resolve(name) if path is None: return None meta = read_meta(path) if not isinstance(meta, dict): return None from safetensors import safe_open try: with safe_open(path, framework="pt", device="cpu") as fh: keys = set(fh.keys()) tensor = None src_name = "" sr = int(meta.get("sample_rate") or 32000) if meta.get("_reflora") and "refmod.audio_latent" in keys: tensor = fh.get_tensor("refmod.audio_latent").clone() elif meta.get("kind") == "bundle": for i, member in enumerate(meta.get("members") or []): if isinstance(member, dict) and member.get("kind") == "audio" and f"ref_{i}" in keys: tensor = fh.get_tensor(f"ref_{i}").clone() sr = int(member.get("sample_rate") or sr) src_name = os.path.basename(str(member.get("name") or "").strip()) break elif meta.get("kind") == "audio" and "latent" in keys: tensor = fh.get_tensor("latent").clone() if tensor is None or tensor.ndim != 4 or tensor.shape[1] != 32 or tensor.shape[2] != 2: return None return { "audio_latent": tensor.contiguous(), "ref_audio_t": int(tensor.shape[-1]), "sample_rate": sr, "digest": tensor_digest(tensor), "name": src_name, } except Exception: return None def _blur_latent(z, factor=8): """Luisa's weakening target: a spatial/temporal low-pass, not noise and not zero.""" if z.dim() == 4: b, c, stereo, t = z.shape if t <= 1: return z flat = z.reshape(b * c * stereo, 1, t).float() down = F.adaptive_avg_pool1d(flat, max(1, t // factor)) return F.interpolate(down, size=t, mode="linear", align_corners=False).reshape_as(z).to(dtype=z.dtype) if z.dim() != 5: _fail(f"cannot blur a RefMod latent of shape {tuple(z.shape)}") t, h, w = z.shape[2], z.shape[3], z.shape[4] down = F.adaptive_avg_pool3d(z.float(), (t, max(1, h // factor), max(1, w // factor))) up = F.interpolate(down, size=(t, h, w), mode="trilinear", align_corners=False) return up.to(dtype=z.dtype) def refine_cutout(mask, frames, low=0.1, pocket=0.005): """A matting model's soft mask, made solid inside and clean at the edge. The two halves of a cutout fail differently, so they are treated apart. Inside, a matting model is unsure as well as at the edge -- on a character sheet the robes came back as grey patches, and every grey pixel is subject half-lost. So the question is turned round: backdrop is what is confidently empty (`< low`) AND touches the frame's border or is a pocket larger than `pocket` of it. Everything else, shrunk back from its outline, is a core held at full weight. At the edge, the model's own soft alpha is kept -- that is what it is good at -- except that on a plain sheet an edge pixel the colour of the sheet is let go. That removes the white rim a cutout leaves round a figure, the thin panel dividers a sheet grid is drawn with, and the wedges of sheet caught between hair and shoulder. What the model was sure of inside the figure is never keyed, so a white collar stays. """ import numpy as np # noqa: PLC0415 from scipy import ndimage # noqa: PLC0415 out = [] for raw_t, px_t in zip(mask, frames): raw = raw_t.float().cpu().numpy() px = px_t[..., :3].float().cpu().numpy() labels, count = ndimage.label(raw < low) if count: edge = np.unique(np.concatenate( [labels[0], labels[-1], labels[:, 0], labels[:, -1]])) sizes = np.bincount(labels.ravel(), minlength=count + 1) backdrop_ids = set(int(i) for i in edge if i) | set( int(i) for i in np.nonzero(sizes >= pocket * raw.size)[0] if i) backdrop = np.isin(labels, sorted(backdrop_ids)) else: backdrop = np.zeros_like(raw, dtype=bool) inset = max(1, round(min(raw.shape) / 100)) core = ndimage.binary_erosion(~backdrop, iterations=inset) m = np.maximum(raw, core.astype(np.float32)) sure = backdrop & (raw < 0.02) if sure.sum() > 0.01 * raw.size: sheet = np.median(px[sure], axis=0) spread = float(np.abs(px[sure] - sheet).mean()) if spread < 0.06: # a plain sheet, not a photographed room near = np.abs(px - sheet).max(axis=-1) key = np.clip((near - 0.04) / 0.12, 0.0, 1.0) m = np.where(core & (raw >= 0.9), m, m * key) out.append(torch.from_numpy(m.astype(np.float32))) return torch.stack(out) def pull_push_fill(frames, mask): """Every pixel coloured from the subject nearest it, smoothly. The standard pull-push hole fill: pool colour-times-weight and weight down to one pixel, then walk back up, keeping a level's own colour in proportion to how much subject it holds and taking the coarser guess for the rest. The backdrop ends up a soft extension of the subject's own edge colours -- no structure of its own, and none of its tone. """ c = frames[..., :3].float().movedim(-1, 1) # [T, 3, H, W] w = mask.float().to(c.device).unsqueeze(1) # [T, 1, H, W] colours, weights = [c * w], [w] while max(colours[-1].shape[-2:]) > 1: colours.append(F.avg_pool2d(colours[-1], 2, ceil_mode=True)) weights.append(F.avg_pool2d(weights[-1], 2, ceil_mode=True)) fill = colours[-1] / weights[-1].clamp_min(1e-6) for cl, wl in zip(reversed(colours[:-1]), reversed(weights[:-1])): coarse = F.interpolate(fill, size=cl.shape[-2:], mode="bilinear", align_corners=False) own = cl / wl.clamp_min(1e-6) fill = wl * own + (1.0 - wl) * coarse return fill.movedim(1, -1).clamp(0.0, 1.0) def _blur_bg_pixels(px, mask): """Smooth heavy spatial blur of background pixels (Fantastic-style) for zero edge halos.""" c = px[..., :3].float().movedim(-1, 1) # [T, 3, H, W] _, _, h, w = c.shape scale = max(8, round(min(h, w) / 24)) bh, bw = max(2, h // scale), max(2, w // scale) down = F.adaptive_avg_pool2d(c, (bh, bw)) blurred = F.interpolate(down, size=(h, w), mode="bicubic", align_corners=False).movedim(1, -1).clamp(0.0, 1.0) # Softly expand mask perimeter so hairline edges don't glow against dark backgrounds m_dil = F.max_pool2d(mask.float().to(c.device).unsqueeze(1), kernel_size=7, stride=1, padding=3).squeeze(1) edge_soft = F.avg_pool2d(m_dil.unsqueeze(1), kernel_size=9, stride=1, padding=4).squeeze(1) return blurred, edge_soft def isolate_subject(frames, mask, retention=0.0, mode="pull_push"): """`[T,H,W,C]` canvas frames with the backdrop replaced, before encode. `mode`: * `pull_push` (default legacy): edge-color pull-push fill * `blur_bg`: blurred background (keeps natural lighting balance with zero pull-push color streaks) * `neutral_gray`: 50% studio neutral backdrop """ m = mask.float().to(frames.device) if m.shape[0] == 1 and frames.shape[0] > 1: m = m.expand(frames.shape[0], -1, -1) if tuple(m.shape) != tuple(frames.shape[:3]): _fail(f"subject mask {tuple(m.shape)} does not cover frames " f"{tuple(frames.shape[:3])}") r = min(1.0, max(0.0, float(retention))) if r >= 1.0 or float(m.amax()) <= 0.0: return frames px = frames[..., :3].float() bg_mode = str(mode or "pull_push").strip().lower() if bg_mode == "blur_bg": bg, soft_m = _blur_bg_pixels(px, m) keep = (r + (1.0 - r) * torch.maximum(m, soft_m * 0.65)).unsqueeze(-1) elif bg_mode == "neutral_gray": bg = torch.full_like(px, 0.5) keep = (r + (1.0 - r) * m).unsqueeze(-1) else: bg = pull_push_fill(px, m) keep = (r + (1.0 - r) * m).unsqueeze(-1) out = keep * px + (1.0 - keep) * bg return out.to(frames.dtype) CROP_MIN_EDGE = 320 def ensure_min_size(frames, mask, min_edge=CROP_MIN_EDGE): """Upscale `frames` `[N,H,W,C]` (and `mask` `[N,H,W]`) so the short edge is at least `min_edge`: a crop of a small subject came out 64-px wide, and the H3 VAE tiler cut a zero-size edge tile from it.""" import torch.nn.functional as _F # noqa: PLC0415 h, w = int(frames.shape[1]), int(frames.shape[2]) if min(h, w) >= int(min_edge): return frames, mask s = float(min_edge) / float(min(h, w)) th, tw = max(int(min_edge), int(round(h * s))), max(int(min_edge), int(round(w * s))) f = _F.interpolate(frames.movedim(-1, 1).float(), size=(th, tw), mode="bicubic", align_corners=False).movedim(1, -1).clamp(0, 1).to(frames.dtype) m = mask if mask is not None: m = _F.interpolate(mask.float().unsqueeze(1), size=(th, tw), mode="bilinear", align_corners=False).squeeze(1).clamp(0, 1).to(mask.dtype) return f, m def crop_to_subject(frames, mask, margin=1.6, min_edge=CROP_MIN_EDGE): """Subject-centered bounding-box crop with margin (1.4-2.0x), rounded to 32px grid, never narrower or shorter than `min_edge` (or the frame).""" import numpy as np # noqa: PLC0415 m_f = mask.float().to(frames.device) if m_f.shape[0] == 1 and frames.shape[0] > 1: m_f = m_f.expand(frames.shape[0], -1, -1) union = (m_f > 0.25).any(dim=0).cpu().numpy() ys, xs = np.nonzero(union) if len(ys) < 16: return frames, mask h, w = int(frames.shape[1]), int(frames.shape[2]) y0, y1 = int(ys.min()), int(ys.max()) + 1 x0, x1 = int(xs.min()), int(xs.max()) + 1 bw = max(64, x1 - x0) bh = max(64, y1 - y0) marg = max(1.1, float(margin or 1.6)) floor = max(64, int(min_edge or 0)) cw = min(w, max(floor, int(round(bw * marg / 32.0)) * 32)) ch = min(h, max(floor, int(round(bh * marg / 32.0)) * 32)) if cw >= w and ch >= h: return frames, mask cx = (x0 + x1) // 2 cy = (y0 + y1) // 2 lx = max(0, min(w - cw, cx - cw // 2)) ty = max(0, min(h - ch, cy - ch // 2)) return frames[:, ty:ty + ch, lx:lx + cw], mask[:, ty:ty + ch, lx:lx + cw] def mask_to_canvas(mask, tw, th, fit_mode="crop"): """`[T,H,W]` MASK fit onto the canvas the way `to_canvas` fits pixels.""" import comfy.utils if mask.dim() == 2: mask = mask.unsqueeze(0) if mask.dim() != 3: _fail(f"a subject mask must be [T,H,W], got {tuple(mask.shape)}") crop = "center" if fit_mode == "crop" else "disabled" m = comfy.utils.common_upscale(mask.float().unsqueeze(1), int(tw), int(th), "bilinear", crop) return m.squeeze(1).clamp(0.0, 1.0) CUTOUT_MODEL = "isnet-general-use" _cutout_session = None _sam_predictor = None _sam_path_loaded = "" def _find_sam_checkpoint(): import folder_paths cands = [] try: for p in folder_paths.get_folder_paths("sams"): cands.append(p) except Exception: pass cands.append(os.path.join(folder_paths.models_dir, "sams")) for root in cands: if not os.path.isdir(root): continue for fn in sorted(os.listdir(root)): if fn.lower().endswith((".pth", ".pt", ".safetensors")): return os.path.join(root, fn) return "" def _cutout_sam(frames): """Subject mask via ComfyUI's installed SAM (`models/sams/`).""" global _sam_predictor, _sam_path_loaded import numpy as np # noqa: PLC0415 from segment_anything import SamPredictor, sam_model_registry # noqa: PLC0415 ckpt = _find_sam_checkpoint() if not ckpt: raise FileNotFoundError("No SAM checkpoint in models/sams/") if _sam_predictor is None or _sam_path_loaded != ckpt: low = os.path.basename(ckpt).lower() arch = "vit_h" if "vit_h" in low else ("vit_l" if "vit_l" in low else "vit_b") sam = sam_model_registry[arch](checkpoint=ckpt) dev = "cuda" if torch.cuda.is_available() else "cpu" sam.to(device=dev) _sam_predictor = SamPredictor(sam) _sam_path_loaded = ckpt out = [] for frame in frames: rgb = (frame[..., :3].float().clamp(0, 1) * 255).round().byte().cpu().numpy() h, w = rgb.shape[:2] _sam_predictor.set_image(rgb) # Foreground center + upper-center points + central box prompt pts = np.array([[w * 0.5, h * 0.45], [w * 0.5, h * 0.25], [w * 0.5, h * 0.70]]) lbls = np.array([1, 1, 1]) box = np.array([w * 0.08, h * 0.04, w * 0.92, h * 0.96]) masks, scores, _ = _sam_predictor.predict( point_coords=pts, point_labels=lbls, box=box, multimask_output=True) best = int(np.argmax(scores)) out.append(torch.from_numpy(masks[best].astype(np.float32))) return torch.stack(out) def cutout_masks(frames, backend="auto_rembg"): """`[T,H,W]` subject masks for `[T,H,W,C]` canvas frames. `backend`: `"auto_rembg"` (default, uses `rembg`) or `"auto_sam"` (uses SAM from `models/sams/`, falling back to `rembg` if unavailable). """ if str(backend or "").strip().lower() == "auto_sam": try: return _cutout_sam(frames) except Exception as exc: print(f"[{TAG}] SAM cutout unavailable ({exc}); falling back to rembg", flush=True) global _cutout_session try: from rembg import new_session, remove # noqa: PLC0415 except ImportError: _fail("subject_mask=auto needs rembg (pip install rembg), or wire a " "MASK into the builder's mask socket") import numpy as np # noqa: PLC0415 from PIL import Image # noqa: PLC0415 if _cutout_session is None: _cutout_session = new_session(CUTOUT_MODEL) out = [] for frame in frames: px = (frame[..., :3].float().clamp(0, 1) * 255).round().byte().cpu().numpy() m = remove(Image.fromarray(px), session=_cutout_session, only_mask=True) out.append(torch.from_numpy(np.asarray(m.convert("L"), dtype=np.float32) / 255.0)) return torch.stack(out) # A third-party RefMod (MiniMaxH3Mod's `refmod_config`) stores its step curve as # (direction, shape, value): the envelope's direction over denoising progress, how it # travels between its endpoints, and the non-zero endpoint. HTC evaluates those natively # (own implementation of the documented envelopes) instead of mapping to a named curve. _TRIPLE_DIRS = {"constant": "constant", "concept_at_start": "concept_at_start", "concept_at_middle": "concept_at_middle", "concept_at_end": "concept_at_end", "concept_at_ends": "concept_at_ends", "decrease": "concept_at_start", "increase": "concept_at_end"} _TRIPLE_SHAPES = ("linear", "ease", "sigmoid", "tanh", "quadratic", "cubic", "exponential", "stair", "elastic", "bump", "dip") def norm_step_curve(curve): """A step curve as HTC uses it: a STEP_CURVES name, a `[direction, shape, value]` triple, or "full" for anything else.""" if isinstance(curve, (list, tuple)) and len(curve) == 3: d = _TRIPLE_DIRS.get(str(curve[0]).strip().lower()) sh = str(curve[1]).strip().lower() try: v = float(curve[2]) except (TypeError, ValueError): return "full" if d and sh in _TRIPLE_SHAPES: if d == "constant" and sh == "linear" and v >= 1.0: return "full" return [d, sh, v] return "full" c = str(curve or "full").strip().lower() return c if c in STEP_CURVES else "full" def third_party_step_curve(meta): """`[direction, shape, value]` from a RefMod's `refmod_config` JSON, or None.""" raw = (meta or {}).get("refmod_config") try: cfg = json.loads(raw) if isinstance(raw, str) and raw.strip() else (raw or {}) except ValueError: return None sc = norm_step_curve((cfg or {}).get("step_curve")) if isinstance(cfg, dict) else "full" return sc if isinstance(sc, list) else None def _ease(shape, x): import math if shape == "ease": return x * x * (3.0 - 2.0 * x) if shape == "sigmoid": return 1.0 / (1.0 + math.exp(-12.0 * (x - 0.5))) if shape == "tanh": return 0.5 * (math.tanh(8.0 * (x - 0.5)) + 1.0) if shape == "quadratic": return x * x if shape == "cubic": return x ** 3 if shape == "exponential": return 2.0 ** x - 1.0 if shape == "stair": return min(1.0, math.floor(x * 4) / 3.0) if shape == "elastic": if x <= 0.0 or x >= 1.0: return max(0.0, min(1.0, x)) return 2.0 ** (-10.0 * x) * math.sin((x * 10.0 - 0.75) * (2.0 * math.pi / 3.0)) + 1.0 if shape == "bump": return 1.0 - abs(2.0 * x - 1.0) if shape == "dip": return abs(2.0 * x - 1.0) return x def _triple_value(spec, x): d, sh, v = spec v = float(v) if d == "constant": return v if sh == "linear" else max(0.0, min(1.0, v * _ease(sh, x))) y = _ease(sh, x) if d == "concept_at_end": w = y elif d == "concept_at_start": w = 1.0 - y elif d == "concept_at_middle": w = 1.0 - abs(2.0 * y - 1.0) else: # concept_at_ends w = abs(2.0 * y - 1.0) return max(0.0, min(1.0, v * w)) def step_curve_value(curve_name, progress): """Strength in [0, 1] at denoising `progress` (0 = noisy start, 1 = clean end). `curve_name` is a STEP_CURVES name or a third-party `[direction, shape, value]`.""" import math if isinstance(curve_name, (list, tuple)): spec = norm_step_curve(curve_name) if isinstance(spec, list): return _triple_value(spec, min(1.0, max(0.0, float(progress)))) return 1.0 c = str(curve_name or "full").strip().lower() x = min(1.0, max(0.0, float(progress))) if c == "early_lock": # Strong composition/anatomy anchor for first ~45%, smooth floor 0.15 late. e = 0.5 * (1.0 + math.cos(math.pi * min(1.0, x / 0.72))) return 0.15 + 0.85 * e if c == "late_detail": # Gentle early framing (0.25), ramps to 1.0 in the detail half. e = 0.5 * (1.0 - math.cos(math.pi * max(0.0, min(1.0, (x - 0.15) / 0.65)))) return 0.25 + 0.75 * e if c == "fade": return max(0.0, 1.0 - x) if c == "mid_peak": return 0.25 + 0.75 * (1.0 - abs(2.0 * x - 1.0)) return 1.0 def apply_strength(latent, strength): """`w * latent + (1-w) * blur`. `>= 1` returns the same tensor.""" w = float(strength) if w >= 1.0: return latent if w <= 0.0: return None return w * latent + (1.0 - w) * _blur_latent(latent) def visual_block(loaded, strength, step_curve="full"): """Single `minimax_refs` block for this mod, or None when strength drops it.""" latent = apply_strength(loaded["latent"], min(1.0, float(strength))) if latent is None: return None block = { "kind": loaded["kind"], "latent_h": int(latent.shape[3]), "latent_w": int(latent.shape[4]), "latent": latent, "refmod": True, } sc = norm_step_curve(step_curve or loaded.get("default_step_curve") or "full") if sc != "full": block["step_curve"] = sc if loaded["kind"] == "video": block["latent_t"] = int(latent.shape[2]) block["ref_audio_t"] = 0 block["audio_latent"] = None return block def visual_blocks(loaded, strength, step_curve="full"): """One or more `minimax_refs` blocks. `strength > 1.0` stacks copies + residual blur.""" import math w = min(MAX_STRENGTH, max(0.0, float(strength))) if w <= 0.0: return [] if w <= 1.0: b = visual_block(loaded, w, step_curve=step_curve) return [b] if b is not None else [] n_full = min(MAX_COPIES, int(math.floor(w))) rem = round(w - n_full, 4) out = [] for _ in range(n_full): b = visual_block(loaded, 1.0, step_curve=step_curve) if b is not None: out.append(b) if rem >= 0.05 and len(out) < MAX_COPIES: b = visual_block(loaded, rem, step_curve=step_curve) if b is not None: out.append(b) return out def audio_block(loaded_audio, strength=1.0, step_curve="full"): """`minimax_refs` standalone audio block from pre-encoded `[1,32,2,T]` latent.""" if not loaded_audio or loaded_audio.get("audio_latent") is None: return None z = apply_strength(loaded_audio["audio_latent"], min(1.0, float(strength))) if z is None: return None block = { "kind": "audio", "ref_audio_t": int(z.shape[-1]), "audio_latent": z, "refmod": True, } sc = norm_step_curve(step_curve or "full") if sc != "full": block["step_curve"] = sc return block _STEP_CURVE_SEQ = 0 def attach_step_curve_wrapper(model): """Attach per-RefMod denoising step-curve mixing (zero cost when no block carries `step_curve`).""" global _STEP_CURVE_SEQ if model is None or not hasattr(model, "add_wrapper_with_key"): return model from contextvars import ContextVar import comfy.patcher_extension as _pe _STEP_CURVE_SEQ += 1 key = f"htc_refmod_step_curve_{_STEP_CURVE_SEQ}" start_var = ContextVar(key, default=1000.0) shift_var = ContextVar(key + "_shift", default=1.0) blur_cache = {} def _cached_blur(z): ck = (id(z), z.device, z.dtype) hit = blur_cache.get(ck) if hit is not None: return hit if len(blur_cache) > 64: blur_cache.clear() b = _blur_latent(z) blur_cache[ck] = b return b def _schedule(executor, noise, latent_image, sampler, sigmas, *args, **kwargs): blur_cache.clear() try: sampling = executor.class_obj.model_patcher.get_model_object("model_sampling") start = float(sampling.timestep(sigmas[0])) except Exception: start = 1000.0 tok = start_var.set(start) tok_s = shift_var.set(_sampling_shift(executor)) try: return executor(noise, latent_image, sampler, sigmas, *args, **kwargs) finally: start_var.reset(tok) shift_var.reset(tok_s) blur_cache.clear() def _wrapper(executor, x, timestep, context, transformer_options={}, **kwargs): payload = kwargs.get("minimax_payload") refs = (payload or {}).get("refs") or [] if not payload or not any(isinstance(r, dict) and r.get("step_curve") for r in refs): return executor(x, timestep, context, transformer_options=transformer_options, **kwargs) prog = _denoise_progress(transformer_options, timestep, start_var.get(), shift_var.get()) mixed = dict(payload) weights = [] kfs = payload.get("keyframes") or [] for field, latent_key in (("cond_video_latents", "latent"), ("cond_audio_latents", "audio_latent")): cond = payload.get(field) if not cond: continue out = list(cond) idx = sum(1 for k in kfs if k.get(latent_key) is not None) changed = False for r in refs: if r.get(latent_key) is None: continue if idx >= len(out): break sc = r.get("step_curve") if sc and sc != "full": w = step_curve_value(sc, prog) weights.append(w) if w < 0.999 and not REFMOD_VROW_CURVE: z = out[idx] out[idx] = (w * z + (1.0 - w) * _cached_blur(z)).to(dtype=z.dtype) changed = True idx += 1 if changed: mixed[field] = out # the step cache (h3_cache) must not reuse a residual across moved weights transformer_options = dict(transformer_options or {}) transformer_options["_htc_step_curve_w"] = tuple(weights) return executor(x, timestep, context, transformer_options=transformer_options, **dict(kwargs, minimax_payload=mixed)) out = model.clone() out.add_wrapper_with_key(_pe.WrappersMP.OUTER_SAMPLE, key, _schedule) out.add_wrapper_with_key(_pe.WrappersMP.DIFFUSION_MODEL, key, _wrapper) return out _VFADE_SEQ = 0 # CP-10: a RefMod step curve scales its block's V rows in attention (clean release at # w -> 0, layout untouched) instead of mixing its latent toward a blur. Off until its # 8-step A/B (lever refmod.REFMOD_VROW_CURVE). REFMOD_VROW_CURVE = False def _denoise_progress(transformer_options, timestep, start, shift=1.0): """Denoising progress, 0 = noisy start, 1 = clean end, by STEP. `1 - timestep / start` is progress in raw sigma, and a flow-shifted schedule spends almost all of its steps at high sigma: on the 8-step PDD grid at shift 12 the last step is still sigma 0.63, so that progress stopped at 0.368 and a fade starting at 0.55 or a `late_detail` curve never ran. The step index in `sample_sigmas` is the truth (the same reading as sparse_attn's schedule); without it the sigma is un-shifted back onto the uniform grid first. """ try: from . import sparse_attn as _sa # noqa: PLC0415 idx, n = _sa.resolve_step(transformer_options or {}) if idx is not None and n > 1: return _sa.schedule_progress(idx, n) except Exception: # noqa: BLE001 -- fall back to the sigma reading pass t = timestep.flatten()[0] if hasattr(timestep, "flatten") else timestep sigma = min(1.0, max(0.0, float(t) / max(float(start), 1e-8))) s = float(shift or 1.0) base = sigma / (s + sigma * (1.0 - s)) if s > 0 else sigma return 1.0 - min(1.0, max(0.0, base)) def _sampling_shift(executor): try: ms = executor.class_obj.model_patcher.get_model_object("model_sampling") return float(getattr(ms, "shift", 1.0) or 1.0) except Exception: # noqa: BLE001 return 1.0 def _cosine_fade_strength(prog: float, fade_start: float = 0.55, end_strength: float = 0.20) -> float: p = min(1.0, max(0.0, float(prog))) fs = min(0.99, max(0.0, float(fade_start))) es = min(1.0, max(0.0, float(end_strength))) if p <= fs: return 1.0 u = (p - fs) / max(1e-6, 1.0 - fs) return es + (1.0 - es) * 0.5 * (1.0 + math.cos(math.pi * u)) def _ref_video_v_spans(payload, context, video_x, audio_x, scale: float, prog=None): """Exact `(start, stop, v_scale)` spans of `video`/`video_audio` ref blocks in `PackedLayout`. `prog` given (REFMOD_VROW_CURVE): every picture/clip block that carries a `step_curve` gets its own scale, `step_curve_value(curve, prog)`, and `scale` is unused.""" if not payload: return () refs = payload.get("refs") or () if prog is None: if float(scale) >= 0.9999: return () if not any(isinstance(r, dict) and r.get("kind") in ("video", "video_audio") and not r.get("_keep_full_v") for r in refs): return () elif not any(isinstance(r, dict) and r.get("step_curve") not in (None, "", "full") for r in refs): return () try: from comfy.ldm.minimax.model import PackedLayout # noqa: PLC0415 except Exception: return () text_len = int(context.shape[1]) if hasattr(context, "shape") and context.ndim >= 2 else 0 lt, lh, lw = int(video_x.shape[2]), int(video_x.shape[3]), int(video_x.shape[4]) at = int(audio_x.shape[-1]) if audio_x is not None else 0 layout = payload.get("layout") if layout is None or getattr(layout, "signature", None) != (text_len, lt, lh, lw, at): layout = PackedLayout(text_len, lt, lh, lw, at, keyframes=payload.get("keyframes"), refs=refs) ref_img_segs = [(int(a), int(b)) for a, b, kind in getattr(layout, "segments", ()) if kind == "ref_img"] spans = [] ri = 0 for blk in refs: if not isinstance(blk, dict): continue knd = blk.get("kind") if knd in ("image", "video", "video_audio"): if ri >= len(ref_img_segs): break if prog is not None: sc = blk.get("step_curve") if sc not in (None, "", "full"): w = step_curve_value(sc, prog) if w < 0.9999: a, b = ref_img_segs[ri] spans.append((a, b, float(w))) elif knd in ("video", "video_audio") and not blk.get("_keep_full_v"): a, b = ref_img_segs[ri] spans.append((a, b, float(scale))) ri += 1 return tuple(spans) def attach_ref_video_fade_wrapper(model, fade_start=0.55, end_strength=0.20, mode="fade"): """Half-cosine fade on native `