Guest User

OnmiLoRA MinimaxH3 Training Fix

a guest
Nov 18th, 2026
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 191.73 KB | Source Code | 0 0
  1. """
  2. ComfyUI-Native Universal Model Adapter for OmniLoRA (`omni_lora/models/adapters.py`).
  3.  
  4. Communicates directly with ComfyUI's runtime objects (`ModelPatcher`, `BaseModel`,
  5. `model_sampling`, `latent_format`, `model_type`, and `extra_conds`) so that any
  6. current or future model supported by ComfyUI works automatically without hardcoded
  7. per-model configuration files.
  8.  
  9. Strictly 100% FP64-Free (`bf16` / `fp16` / `fp32` only) and zero per-step GPU-CPU
  10. synchronizations for Intel Arc XPU and multi-vendor GPUs.
  11. """
  12.  
  13. from __future__ import annotations
  14.  
  15. import contextlib
  16. import inspect
  17. import logging
  18. import math
  19. from pathlib import Path
  20. import re
  21. import sys
  22. from typing import Any, Dict, List, Optional, Tuple, Type
  23.  
  24. import torch
  25. import torch.nn as nn
  26. import torch.nn.functional as F
  27.  
  28.  
  29. def ensure_comfy_importable() -> bool:
  30. """
  31. Ensure ComfyUI's `comfy` package (`comfy.model_base`, `comfy.supported_models`,
  32. `comfy.model_detection`, `comfy.lora`, `comfy.latent_formats`) is importable
  33. both when running inside `ComfyUI/custom_nodes/omni_lora` and when running
  34. standalone alongside a sibling `ComfyUI/` checkout.
  35. """
  36. if "comfy" in sys.modules:
  37. return True
  38. try:
  39. import comfy # type: ignore # noqa: F401
  40. return True
  41. except Exception:
  42. pass
  43.  
  44. here = Path(__file__).resolve()
  45. # Check standard custom_nodes hierarchy (`ComfyUI/custom_nodes/omni_lora/omni_lora/models/adapters.py`)
  46. # as well as sibling `ComfyUI/` checkouts (`<workspace>/ComfyUI`).
  47. for ancestor in here.parents:
  48. for candidate in (ancestor, ancestor / "ComfyUI"):
  49. comfy_pkg = candidate / "comfy"
  50. if comfy_pkg.is_dir() and (comfy_pkg / "model_base.py").is_file():
  51. cand_str = str(candidate)
  52. if cand_str not in sys.path:
  53. sys.path.insert(0, cand_str)
  54. try:
  55. import comfy # type: ignore # noqa: F401
  56. return True
  57. except Exception:
  58. return False
  59. return False
  60.  
  61.  
  62. from ..backends.base import (
  63. install_dml_fp64_scalar_guards,
  64. is_inference_tensor,
  65. safe_to_device,
  66. sanitize_module_no_fp64,
  67. )
  68. from ..lora.layers import (
  69. LoRAInjector,
  70. LoRALinear,
  71. _UNET_BLOCK_CONTAINER_NAMES,
  72. _collect_repeating_block_module_ids,
  73. _is_conv_like,
  74. _is_linear_like,
  75. _is_pointwise_conv,
  76. _strip_numeric_segments,
  77. classify_block_structural_roles,
  78. trace_single_block_dataflow,
  79. )
  80. from .base import BaseModelAdapter, ModelSpec
  81.  
  82.  
  83. # ============================================================================
  84. # 1. Lightweight Synthetic Fallback Backbone (Offline Unit Tests Only)
  85. # ============================================================================
  86.  
  87. class ToyBackbone(nn.Module):
  88. """Minimal, FP64-free synthetic fallback backbone used only for offline dry-runs when no ComfyUI MODEL is connected."""
  89.  
  90. def __init__(self, in_channels: int = 16, context_dim: int = 2048) -> None:
  91. super().__init__()
  92. self.in_channels = in_channels
  93. self.patch_size = 2
  94. self.hidden_size = 64
  95. self.conv_in = nn.Conv2d(in_channels, 64, kernel_size=1)
  96. self.context_in = nn.Linear(context_dim, 64)
  97. self.attn_proj = nn.Linear(64, 64)
  98. self.conv_out = nn.Conv2d(64, in_channels, kernel_size=1)
  99. with torch.no_grad():
  100. for mod in (self.conv_in, self.context_in, self.attn_proj, self.conv_out):
  101. nn.init.normal_(mod.weight, mean=0.0, std=0.02)
  102. if mod.bias is not None:
  103. nn.init.zeros_(mod.bias)
  104.  
  105. def forward(
  106. self,
  107. x: torch.Tensor,
  108. timestep: torch.Tensor,
  109. context: Optional[torch.Tensor] = None,
  110. **kwargs: Any,
  111. ) -> torch.Tensor:
  112. if x.ndim == 5:
  113. b, c, t, h, w = x.shape
  114. x_2d = x.permute(0, 2, 1, 3, 4).contiguous().reshape(b * t, c, h, w)
  115. out_2d = self._forward_2d(x_2d, timestep, context)
  116. return out_2d.reshape(b, t, c, h, w).permute(0, 2, 1, 3, 4).contiguous()
  117. return self._forward_2d(x, timestep, context)
  118.  
  119. def _forward_2d(
  120. self,
  121. x: torch.Tensor,
  122. timestep: torch.Tensor,
  123. context: Optional[torch.Tensor],
  124. ) -> torch.Tensor:
  125. h = self.conv_in(x.contiguous())
  126. b, c, height, width = h.shape
  127. tokens = h.permute(0, 2, 3, 1).contiguous().reshape(b, height * width, c)
  128. if context is not None:
  129. ctx = self.context_in(context).mean(dim=1, keepdim=True)
  130. tokens = tokens + ctx
  131. tokens = tokens + self.attn_proj(tokens)
  132. out_h = tokens.reshape(b, height, width, c).permute(0, 3, 1, 2).contiguous()
  133. return self.conv_out(out_h)
  134.  
  135.  
  136. # ============================================================================
  137. # 2. Universal ComfyUI Native Model Adapter & Resilient Transformer Options
  138. # ============================================================================
  139.  
  140. _SAMPLE_SIGMAS_MULT_CACHE: Dict[Tuple[str, int], torch.Tensor] = {}
  141.  
  142.  
  143. def _is_omni_training_active() -> bool:
  144. """Return True when OmniLoRA autograd training is active (`grad` enabled or `mm.in_training`)."""
  145. if torch.is_grad_enabled():
  146. return True
  147. mm_mod = sys.modules.get("comfy.model_management")
  148. if mm_mod is not None and bool(getattr(mm_mod, "in_training", False)):
  149. return True
  150. return False
  151.  
  152.  
  153. def _unwrap_attn_tensor(tensor: Any) -> Any:
  154. """Unwrap a ComfyUI `AttentionTensorContainer` without consuming raw tensors."""
  155. if isinstance(tensor, torch.Tensor):
  156. return tensor
  157. if hasattr(tensor, "take") and callable(tensor.take):
  158. return tensor.take()
  159. return tensor
  160.  
  161.  
  162. def _run_pytorch_sdpa_attention(
  163. q: Any,
  164. k: Any,
  165. v: Any,
  166. heads: int,
  167. mask: Optional[torch.Tensor] = None,
  168. attn_precision: Any = None,
  169. skip_reshape: bool = False,
  170. skip_output_reshape: bool = False,
  171. **kwargs: Any,
  172. ) -> torch.Tensor:
  173. """
  174. Execute differentiable PyTorch SDPA (`attention_pytorch` / `F.scaled_dot_product_attention`)
  175. using ComfyUI's exact `(q, k, v, heads, mask, skip_reshape, skip_output_reshape)` contract.
  176. Includes a guard for `skip_output_reshape=True` when `b > 32768` (`SDP_BATCH_LIMIT`).
  177. """
  178. q = _unwrap_attn_tensor(q)
  179. k = _unwrap_attn_tensor(k)
  180. v = _unwrap_attn_tensor(v)
  181.  
  182. b_dim = int(q.shape[0]) if isinstance(q, torch.Tensor) and q.ndim >= 1 else 1
  183. comfy_attn = sys.modules.get("comfy.ldm.modules.attention")
  184. attn_pt = getattr(comfy_attn, "attention_pytorch", None) if comfy_attn is not None else None
  185. if callable(attn_pt) and not (skip_output_reshape and b_dim > 32768):
  186. raw_pt = getattr(attn_pt, "__wrapped__", None)
  187. if callable(raw_pt):
  188. return raw_pt(
  189. q,
  190. k,
  191. v,
  192. heads,
  193. mask=mask,
  194. attn_precision=attn_precision,
  195. skip_reshape=skip_reshape,
  196. skip_output_reshape=skip_output_reshape,
  197. **kwargs,
  198. )
  199. call_kw = dict(kwargs)
  200. call_kw.pop("preferred_attention", None)
  201. call_kw["_inside_attn_wrapper"] = True
  202. return attn_pt(
  203. q,
  204. k,
  205. v,
  206. heads,
  207. mask=mask,
  208. attn_precision=attn_precision,
  209. skip_reshape=skip_reshape,
  210. skip_output_reshape=skip_output_reshape,
  211. **call_kw,
  212. )
  213.  
  214. enable_gqa = bool(kwargs.get("enable_gqa", False))
  215. if skip_reshape:
  216. b, q_heads, _, dim_head = q.shape
  217. else:
  218. b = int(q.shape[0])
  219. dim_head = int(q.shape[-1]) // int(heads)
  220. q_heads = int(heads)
  221. k_heads = max(1, int(k.shape[-1]) // dim_head) if enable_gqa else q_heads
  222. v_heads = max(1, int(v.shape[-1]) // dim_head) if enable_gqa else q_heads
  223. q = q.reshape(b, -1, q_heads, dim_head).transpose(1, 2)
  224. k = k.reshape(b, -1, k_heads, dim_head).transpose(1, 2)
  225. v = v.reshape(b, -1, v_heads, dim_head).transpose(1, 2)
  226.  
  227. if mask is not None:
  228. if mask.ndim == 2:
  229. mask = mask.unsqueeze(0)
  230. if mask.ndim == 3:
  231. mask = mask.unsqueeze(1)
  232.  
  233. if k.shape[1] != q.shape[1]:
  234. rep_k = max(1, int(q.shape[1]) // max(1, int(k.shape[1])))
  235. rep_v = max(1, int(q.shape[1]) // max(1, int(v.shape[1])))
  236. if mask is not None:
  237. k = k.repeat_interleave(rep_k, dim=1)
  238. v = v.repeat_interleave(rep_v, dim=1)
  239. enable_gqa = False
  240. else:
  241. enable_gqa = True
  242. else:
  243. enable_gqa = False
  244.  
  245. sdpa_kwargs: Dict[str, Any] = {}
  246. if "scale" in kwargs and kwargs["scale"] is not None:
  247. sdpa_kwargs["scale"] = kwargs["scale"]
  248. if enable_gqa:
  249. sdpa_kwargs["enable_gqa"] = True
  250.  
  251. out = F.scaled_dot_product_attention(
  252. q,
  253. k,
  254. v,
  255. attn_mask=mask,
  256. dropout_p=0.0,
  257. is_causal=False,
  258. **sdpa_kwargs,
  259. )
  260. if not skip_output_reshape:
  261. out = out.transpose(1, 2).reshape(b, -1, int(heads) * dim_head)
  262. return out
  263.  
  264.  
  265. def _omni_training_attention_override(orig_func: Any, *args: Any, **kwargs: Any) -> torch.Tensor:
  266. """
  267. ComfyUI `transformer_options["optimized_attention_override"]` callback used during OmniLoRA
  268. training so `--use-ck-attention`, `--use-sage-attention`, and checkpoint `ComfyAttention`
  269. settings transparently execute via differentiable PyTorch SDPA.
  270. """
  271. return _run_pytorch_sdpa_attention(*args, **kwargs)
  272.  
  273.  
  274. def _build_training_sample_sigmas(
  275. timesteps: torch.Tensor,
  276. sigma: Optional[torch.Tensor] = None,
  277. num_steps: int = 20,
  278. ) -> torch.Tensor:
  279. """
  280. Construct a 1D descending schedule tensor `sample_sigmas` of length `num_steps + 1` (default 21)
  281. on `timesteps.device` with zero GPU-CPU syncs and zero `linspace`/`argmin`/`sort` kernel dependencies.
  282.  
  283. Guarantees that `timesteps[0]` is an exact interior entry at index `i = 1` followed
  284. by strictly smaller sigmas (`0.90 * ref_t`, ...) down to `0.0`, so step-lookahead / flow-map models
  285. (such as Flux 3 Klein: `i = int((sample_sigmas - timestep[0]).abs().argmin()); target = sample_sigmas[min(i + 1, ...)]`)
  286. always resolve `i = 1` and `target = sample_sigmas[2] = 0.90 * timestep[0] < timestep[0]`.
  287. """
  288. device = timesteps.device
  289. ref_t = timesteps.detach().flatten()[0].to(dtype=torch.float32).clamp(min=1e-4)
  290.  
  291. n = max(4, int(num_steps))
  292. cache_key = (str(device), n)
  293. multipliers = _SAMPLE_SIGMAS_MULT_CACHE.get(cache_key)
  294. if multipliers is None or multipliers.device != device:
  295. tail_len = n - 1
  296. mult_list = [1.25, 1.0] + [0.90 * (1.0 - float(k) / float(max(1, tail_len - 1))) for k in range(tail_len)]
  297. multipliers = safe_to_device(torch.tensor(mult_list, dtype=torch.float32), device=device, dtype=torch.float32)
  298. _SAMPLE_SIGMAS_MULT_CACHE[cache_key] = multipliers
  299. return ref_t * multipliers
  300.  
  301.  
  302. class OmniTransformerOptions(dict): # type: ignore[type-arg]
  303. """
  304. Copy-safe, resilient `transformer_options` dictionary passed to ComfyUI models during training.
  305. 1. Pre-populates all standard ComfyUI sampler/patcher keys (`sample_sigmas`, `sigmas`,
  306. `cond_or_uncond`, `patches`, `patches_replace`, `wrappers`, `callbacks`).
  307. 2. Preserves its class across `transformer_options = transformer_options.copy()` calls inside
  308. `comfy/ldm/*/model.py` and `WrapperExecutor`.
  309. 3. Provides safe fallback defaults via `__missing__` if a new or custom model accesses an
  310. unanticipated `transformer_options["..."]` key via `[]` instead of `.get()`.
  311. """
  312.  
  313. def copy(self) -> "OmniTransformerOptions":
  314. return OmniTransformerOptions(self)
  315.  
  316. def __missing__(self, key: str) -> Any:
  317. k_lower = str(key).lower()
  318. if "sample_sigma" in k_lower:
  319. return self.get("sample_sigmas")
  320. if "sigma" in k_lower or "timestep" in k_lower:
  321. return self.get("sigmas", self.get("sample_sigmas"))
  322. if "cond_or_uncond" in k_lower:
  323. return [0]
  324. if any(w in k_lower for w in ("patch", "wrapper", "callback", "replace", "option", "dict")):
  325. val: Dict[str, Any] = {}
  326. self[key] = val
  327. return val
  328. if any(w in k_lower for w in ("list", "uuid", "indices", "adain")):
  329. lst: List[Any] = []
  330. self[key] = lst
  331. return lst
  332. if any(w in k_lower for w in ("scale", "strength", "multiplier", "factor")):
  333. return 1.0
  334. if any(w in k_lower for w in ("step", "index", "idx", "total")):
  335. return 0
  336. return None
  337.  
  338.  
  339. class ComfyModelAdapter(BaseModelAdapter):
  340. """
  341. Universal ComfyUI Native Model Adapter.
  342.  
  343. Queries latent geometry (`latent_format`), noise schedule (`model_sampling`),
  344. training objective (`model_type` / `model_sampling`), conditioning dispatch (`extra_conds`),
  345. and LoRA target layers directly from the connected ComfyUI `ModelPatcher` / `BaseModel`.
  346. """
  347.  
  348. MODEL_ID = "comfy_model"
  349.  
  350. def __init__(
  351. self,
  352. comfy_model: Optional[Any] = None,
  353. model_id: str = "auto",
  354. gradient_checkpointing: bool = True,
  355. guidance_scale: float = 3.5,
  356. min_timestep: float = 0.0,
  357. max_timestep: float = 1.0,
  358. include_conv: bool = False,
  359. **kwargs: Any,
  360. ) -> None:
  361. self.comfy_model = comfy_model
  362. self.inner_model = getattr(comfy_model, "model", comfy_model) if comfy_model is not None else None
  363. self.diffusion_model = (
  364. self._get_comfy_object("diffusion_model")
  365. or getattr(self.inner_model, "diffusion_model", None)
  366. or getattr(comfy_model, "diffusion_model", None)
  367. or (self.inner_model if isinstance(self.inner_model, nn.Module) else None)
  368. )
  369.  
  370. self.model_config = (
  371. self._get_comfy_object("model_config")
  372. or getattr(self.inner_model, "model_config", None)
  373. or getattr(comfy_model, "model_config", None)
  374. )
  375. self.unet_config: Dict[str, Any] = (
  376. dict(getattr(self.model_config, "unet_config", None) or {})
  377. if self.model_config is not None
  378. else {}
  379. )
  380. self.model_sampling = (
  381. self._get_comfy_object("model_sampling")
  382. or getattr(self.inner_model, "model_sampling", None)
  383. )
  384. if self.model_sampling is not None and isinstance(self.model_sampling, nn.Module):
  385. sanitize_module_no_fp64(self.model_sampling)
  386. self.model_type = (
  387. self._get_comfy_object("model_type")
  388. or getattr(self.inner_model, "model_type", None)
  389. )
  390. self.latent_format = (
  391. self._get_comfy_object("latent_format")
  392. or getattr(self.inner_model, "latent_format", None)
  393. or (getattr(self.model_config, "latent_format", None) if self.model_config is not None else None)
  394. )
  395. self._gradient_checkpointing = gradient_checkpointing
  396. self.guidance_scale = float(guidance_scale)
  397. t_lo = max(0.0, min(1.0, float(min_timestep)))
  398. t_hi = max(0.0, min(1.0, float(max_timestep)))
  399. if t_hi <= t_lo:
  400. t_lo, t_hi = 0.0, 1.0
  401. self.min_timestep: float = t_lo
  402. self.max_timestep: float = t_hi
  403. raw_min_snr = kwargs.get("min_snr_gamma", 0.0)
  404. self.min_snr_gamma: float = float(0.0 if raw_min_snr is None else raw_min_snr)
  405. self.loss_type: str = str(kwargs.get("loss_type", "l2") or "l2").lower()
  406. self.huber_c: float = float(kwargs.get("huber_c", 0.1) or 0.1)
  407. self._cached_sigmas: Optional[torch.Tensor] = None
  408. self._cached_log_sigmas: Optional[torch.Tensor] = None
  409. self._cached_latent_channels: Dict[int, int] = {}
  410. self._cached_raw_input_channels: Dict[int, Optional[int]] = {}
  411. self._cached_context_dim: Dict[int, Optional[int]] = {}
  412. self._cached_vector_dim: Dict[int, Optional[int]] = {}
  413. self._cached_forward_sig: Dict[int, Tuple[set[str], bool]] = {}
  414.  
  415. cls_name = ""
  416. if self.diffusion_model is not None:
  417. cls_name = self.diffusion_model.__class__.__name__
  418. elif self.inner_model is not None:
  419. cls_name = self.inner_model.__class__.__name__
  420. elif comfy_model is not None:
  421. cls_name = comfy_model.__class__.__name__
  422.  
  423. native_info = resolve_comfy_native_architecture(
  424. comfy_model if comfy_model is not None else (self.inner_model or self.diffusion_model),
  425. unet_config=self.unet_config,
  426. )
  427. if self.model_config is None and native_info.get("model_config") is not None:
  428. self.model_config = native_info["model_config"]
  429. if not self.unet_config and isinstance(native_info.get("unet_config"), dict):
  430. self.unet_config = dict(native_info["unet_config"])
  431. if self.latent_format is None and native_info.get("latent_format") is not None:
  432. self.latent_format = native_info["latent_format"]
  433. if self.model_type is None and native_info.get("model_type") is not None:
  434. self.model_type = native_info["model_type"]
  435. if self.model_sampling is None and native_info.get("model_sampling") is not None:
  436. self.model_sampling = native_info["model_sampling"]
  437. if isinstance(self.model_sampling, nn.Module):
  438. sanitize_module_no_fp64(self.model_sampling)
  439.  
  440. detected_arch = str(native_info.get("canonical_id") or "") or detect_comfy_model_architecture(
  441. self.diffusion_model or self.inner_model,
  442. unet_config=self.unet_config,
  443. )
  444. resolved_id = (
  445. model_id.strip().lower()
  446. if model_id and model_id.strip().lower() != "auto"
  447. else (detected_arch or cls_name.lower() or "comfy_model")
  448. )
  449. self._model_id = resolved_id
  450.  
  451. # 1. Derive training objective from ComfyUI's ModelType and model_sampling MRO
  452. objective_type = self._resolve_objective_type(resolved_id)
  453.  
  454. # 2. Derive latent channels & 2D/3D video dimensionality from ComfyUI's latent_format & diffusion_model
  455. latent_channels = 16
  456. supports_video_5d = False
  457. if self.latent_format is not None:
  458. latent_channels = int(getattr(self.latent_format, "latent_channels", 16))
  459. latent_dimensions = int(getattr(self.latent_format, "latent_dimensions", 2))
  460. supports_video_5d = latent_dimensions == 3
  461. if isinstance(self.diffusion_model, nn.Module):
  462. # Cross-check with backbone if a custom loader attached a generic 16-ch/3D latent_format
  463. # to a 64-ch/2D model (e.g., QwenImage21 loaded via a generic QwenImage wrapper)
  464. if not self._infer_backbone_accepts_5d(self.diffusion_model, default=supports_video_5d):
  465. supports_video_5d = False
  466. inferred_c = self._infer_backbone_latent_channels(
  467. self.diffusion_model,
  468. fallback_channels=latent_channels,
  469. ignore_latent_format=True,
  470. )
  471. if inferred_c != latent_channels and self._backbone_strictly_requires_channels(
  472. self.diffusion_model, inferred_c
  473. ):
  474. latent_channels = inferred_c
  475. elif self.diffusion_model is not None:
  476. latent_channels = self._infer_backbone_latent_channels(self.diffusion_model, fallback_channels=16)
  477. supports_video_5d = self._infer_backbone_accepts_5d(self.diffusion_model, default=False)
  478.  
  479. # 3. Discover LoRA target modules from ComfyUI's live diffusion_model
  480. self.include_conv = bool(include_conv)
  481. default_targets: Tuple[str, ...] = ()
  482. if isinstance(self.diffusion_model, nn.Module):
  483. default_targets = discover_universal_target_modules(
  484. self.diffusion_model,
  485. comfy_inner_model=self.inner_model,
  486. include_conv=self.include_conv,
  487. )
  488.  
  489. # 4. Discover expected text conditioning dimension from the backbone
  490. text_dim = 2048
  491. if isinstance(self.diffusion_model, nn.Module):
  492. inferred_ctx = self._infer_backbone_context_dim(self.diffusion_model)
  493. if inferred_ctx is not None:
  494. text_dim = inferred_ctx
  495.  
  496. # 5. Check whether the model actually uses pooled/vector conditioning (`y`)
  497. # Note: In ComfyUI's UNetModel (SD1.5/SD2.1), `num_classes` is None and passing `y`
  498. # triggers `AssertionError: must specify y if and only if the model is class-conditional`.
  499. num_classes = getattr(self.diffusion_model, "num_classes", None)
  500. requires_pooled = bool(
  501. hasattr(self.diffusion_model, "vector_in")
  502. or hasattr(self.diffusion_model, "y_embedder")
  503. or hasattr(self.diffusion_model, "p_embedder")
  504. or (hasattr(self.diffusion_model, "label_emb") and num_classes is not None)
  505. )
  506.  
  507. raw_patch_size = getattr(
  508. self.diffusion_model,
  509. "patch_size",
  510. getattr(
  511. self.diffusion_model,
  512. "patch_spatial",
  513. self.unet_config.get("patch_size", self.unet_config.get("patch_spatial", 2)),
  514. ),
  515. )
  516. resolved_patch_size = (
  517. int(raw_patch_size[0])
  518. if isinstance(raw_patch_size, (tuple, list)) and len(raw_patch_size) > 0
  519. else (int(raw_patch_size) if isinstance(raw_patch_size, int) else 2)
  520. )
  521.  
  522. self._spec = ModelSpec(
  523. model_id=resolved_id,
  524. display_name=f"ComfyUI ({cls_name or resolved_id})",
  525. architecture_type=getattr(self.model_type, "name", objective_type),
  526. default_resolution=1024 if not supports_video_5d else 512,
  527. latent_channels=latent_channels,
  528. patch_size=resolved_patch_size,
  529. hidden_size=getattr(self.diffusion_model, "hidden_size", 256)
  530. if isinstance(getattr(self.diffusion_model, "hidden_size", None), int)
  531. else 256,
  532. double_blocks=2,
  533. single_blocks=2,
  534. default_target_modules=default_targets,
  535. recommended_vram_gb_bf16=12.0,
  536. objective_type=objective_type,
  537. text_dim=text_dim,
  538. supports_video_5d=supports_video_5d,
  539. requires_pooled_conditioning=requires_pooled,
  540. requires_guidance_embed=hasattr(self.diffusion_model, "guidance_in"),
  541. )
  542.  
  543. def _get_comfy_object(self, name: str) -> Any:
  544. """Query `comfy_model.get_model_object(name)` safely if `comfy_model` is a ComfyUI `ModelPatcher`."""
  545. if self.comfy_model is not None and hasattr(self.comfy_model, "get_model_object"):
  546. try:
  547. obj = self.comfy_model.get_model_object(name)
  548. if obj is not None:
  549. return obj
  550. except Exception:
  551. pass
  552. return None
  553.  
  554. def _infer_backbone_accepts_5d(self, backbone: nn.Module, default: bool = False) -> bool:
  555. """
  556. Determine structurally whether `backbone.forward` expects 5D `[B, C, T, H, W]` video/3D-patched
  557. latents or 4D `[B, C, H, W]` image latents across any ComfyUI model:
  558. - If `patch_size` is a 3-tuple `(pt, ph, pw)` or the backbone contains `nn.Conv3d`, `process_img`,
  559. or `patch_temporal` + `patch_spatial` (e.g. Cosmos Predict2 / Anima `MiniTrainDIT`), it accepts 5D latents.
  560. - If `patch_size` is None or 1, has no `process_img` and no `nn.Conv3d`, and `img_in` is a 2D `Linear`
  561. matching `in_channels == out_channels` (e.g., 64-ch 2D patch-packed DiTs), it expects 4D latents.
  562. """
  563. if hasattr(backbone, "process_img"):
  564. return True
  565. if hasattr(backbone, "patch_temporal") and hasattr(backbone, "patch_spatial"):
  566. return True
  567. p = getattr(backbone, "patch_size", self.unet_config.get("patch_size", None))
  568. if isinstance(p, (tuple, list)) and len(p) == 3:
  569. return True
  570. if any(isinstance(m, nn.Conv3d) for m in backbone.modules()):
  571. return True
  572. if p in (None, 1):
  573. img_in = getattr(backbone, "img_in", None)
  574. in_f = _get_linear_in_features(img_in)
  575. out_ch = getattr(backbone, "out_channels", self.unet_config.get("out_channels", None))
  576. if isinstance(in_f, int) and in_f > 0 and out_ch == in_f:
  577. return False
  578. return default
  579.  
  580. def _backbone_strictly_requires_channels(self, backbone: nn.Module, inferred_c: int) -> bool:
  581. """
  582. Return True when `backbone` structurally consumes unpatched `inferred_c`-channel latents
  583. directly into `img_in` (with `patch_size in (None, 1)` and no internal `process_img` patch packing).
  584. """
  585. p = getattr(backbone, "patch_size", self.unet_config.get("patch_size", None))
  586. if p in (None, 1) and not hasattr(backbone, "process_img"):
  587. img_in = getattr(backbone, "img_in", None)
  588. in_f = _get_linear_in_features(img_in)
  589. if isinstance(in_f, int) and in_f == inferred_c:
  590. return True
  591. return False
  592.  
  593. def _resolve_objective_type(self, resolved_id: str) -> str:
  594. """Query ComfyUI's `model_type` and `model_sampling` class hierarchy to determine the training objective."""
  595. if self.model_type is not None:
  596. type_name = getattr(self.model_type, "name", str(self.model_type)).upper()
  597. if "FLOW" in type_name or "CONST" in type_name:
  598. return "rectified_flow"
  599. if "V_PREDICTION" in type_name:
  600. return "v_prediction"
  601. if "EDM" in type_name:
  602. return "edm"
  603. if "X0" in type_name:
  604. return "x0"
  605. if "EPS" in type_name or "CASCADE" in type_name:
  606. return "ddpm_eps"
  607.  
  608. if self.model_sampling is not None:
  609. mro_names = [cls.__name__.upper() for cls in self.model_sampling.__class__.__mro__]
  610. if any("CONST" in n or "FLOW" in n for n in mro_names):
  611. return "rectified_flow"
  612. if any("V_PREDICTION" in n for n in mro_names):
  613. return "v_prediction"
  614. if any(n == "EDM" or "CONTINUOUSEDM" in n for n in mro_names):
  615. return "edm"
  616. if any(n == "X0" for n in mro_names):
  617. return "x0"
  618. if any("EPS" in n for n in mro_names):
  619. return "ddpm_eps"
  620.  
  621. if "sd15" in resolved_id or "sdxl" in resolved_id or "kolors" in resolved_id or "hunyuan_dit" in resolved_id:
  622. return "ddpm_eps"
  623. return "rectified_flow"
  624.  
  625. @property
  626. def spec(self) -> ModelSpec:
  627. return self._spec
  628.  
  629. def build_backbone(
  630. self,
  631. dtype: torch.dtype = torch.bfloat16,
  632. device: torch.device = torch.device("cpu"),
  633. ) -> nn.Module:
  634. if self.diffusion_model is not None and isinstance(self.diffusion_model, nn.Module):
  635. return self.diffusion_model.to(device=device, dtype=dtype)
  636. return ToyBackbone(
  637. in_channels=self.spec.latent_channels,
  638. context_dim=self.spec.text_dim,
  639. ).to(device=device, dtype=dtype)
  640.  
  641. def _infer_backbone_latent_channels(
  642. self,
  643. backbone: Optional[nn.Module] = None,
  644. fallback_channels: Optional[int] = None,
  645. ignore_latent_format: bool = False,
  646. ) -> int:
  647. """
  648. Inspect ComfyUI's `latent_format`, `model_config.unet_config`, and `diffusion_model`
  649. to determine expected input latent channels across all supported ComfyUI architectures.
  650. """
  651. # Special-case MiniMax H3 (video latents are 24-ch, audio is 32-ch)
  652. if backbone is not None:
  653. cls_name = backbone.__class__.__name__
  654. if "MiniMaxH3" in cls_name or "minimax_h3" in cls_name.lower():
  655. latents_dim = getattr(backbone, "latents_dim", None)
  656. if isinstance(latents_dim, int) and latents_dim > 0:
  657. return latents_dim
  658. # Fallback if attribute is missing
  659. return 24
  660.  
  661. if not ignore_latent_format and self.latent_format is not None:
  662. lf_ch = getattr(self.latent_format, "latent_channels", None)
  663. if isinstance(lf_ch, int) and lf_ch > 0:
  664. if backbone is None or not self._backbone_strictly_requires_channels(
  665. backbone,
  666. self._infer_backbone_latent_channels(backbone, fallback_channels=lf_ch, ignore_latent_format=True),
  667. ):
  668. return lf_ch
  669.  
  670. default_c = fallback_channels if (isinstance(fallback_channels, int) and fallback_channels > 0) else 16
  671. if backbone is None:
  672. return default_c
  673.  
  674. bid = id(backbone)
  675. if bid in self._cached_latent_channels:
  676. return self._cached_latent_channels[bid]
  677.  
  678. resolved_c: Optional[int] = None
  679. out_ch = getattr(
  680. backbone,
  681. "out_channels",
  682. getattr(backbone, "out_dim", self.unet_config.get("out_channels", self.unet_config.get("out_dim", None))),
  683. )
  684. in_ch = getattr(
  685. backbone,
  686. "in_channels",
  687. getattr(backbone, "in_dim", self.unet_config.get("in_channels", self.unet_config.get("in_dim", None))),
  688. )
  689. explicit_patch_size = getattr(backbone, "patch_size", self.unet_config.get("patch_size", None))
  690.  
  691. # If a model explicitly declares `in_channels` and `out_channels` where `in_channels` is
  692. # patch-packed (e.g. QwenImage 1.0: in_channels=64, out_channels=16, patch_size=2),
  693. # `out_channels` is the unpacked VAE latent channel count.
  694. if (
  695. isinstance(out_ch, int)
  696. and out_ch in (3, 4, 8, 12, 16, 32, 48, 64, 128)
  697. and isinstance(in_ch, int)
  698. and in_ch != out_ch
  699. ):
  700. resolved_c = int(out_ch)
  701.  
  702. img_in = getattr(backbone, "img_in", None) or getattr(backbone, "patch_embed", None)
  703. if resolved_c is None and img_in is not None:
  704. if hasattr(img_in, "in_channels") and isinstance(img_in.in_channels, int) and img_in.in_channels > 0:
  705. resolved_c = int(img_in.in_channels)
  706. elif hasattr(img_in, "proj") and hasattr(img_in.proj, "in_channels"):
  707. resolved_c = int(img_in.proj.in_channels)
  708. else:
  709. in_f = _get_linear_in_features(img_in)
  710. if isinstance(in_f, int) and in_f > 0:
  711. # Only divide by `patch_size^2` when the backbone explicitly defines `patch_size > 1`
  712. # and does NOT set `out_channels == in_f` (e.g. QwenImage21 has no patch_size and
  713. # consumes 64-channel latents directly, whereas Flux/Fibo2/QwenImage 1.0 have patch_size=2).
  714. if explicit_patch_size is not None and (out_ch != in_f or in_f == 128):
  715. p_area = (
  716. int(explicit_patch_size[0]) * int(explicit_patch_size[1])
  717. if isinstance(explicit_patch_size, (tuple, list)) and len(explicit_patch_size) >= 2
  718. else (int(explicit_patch_size[-1]) ** 2 if isinstance(explicit_patch_size, (tuple, list)) else int(explicit_patch_size) ** 2)
  719. )
  720. if p_area > 1 and in_f % p_area == 0 and (in_f // p_area) in (3, 4, 8, 12, 16, 32, 48, 64, 128):
  721. resolved_c = in_f // p_area
  722. if resolved_c is None and in_f in (3, 4, 8, 12, 16, 32, 48, 64, 128):
  723. resolved_c = in_f
  724.  
  725. if resolved_c is None:
  726. emb_in = getattr(backbone, "emb_in", None)
  727. if isinstance(emb_in, nn.ModuleDict) and len(emb_in) > 0:
  728. first_emb = emb_in["image"] if "image" in emb_in else next(iter(emb_in.values()))
  729. in_f = _get_linear_in_features(first_emb)
  730. if isinstance(in_f, int) and in_f > 0:
  731. p_area = 4 if (explicit_patch_size in (None, 2) and in_f in (64, 128)) else 1
  732. resolved_c = in_f // p_area
  733.  
  734. if resolved_c is None:
  735. x_embedder = getattr(backbone, "x_embedder", None)
  736. if x_embedder is not None and hasattr(x_embedder, "proj") and hasattr(x_embedder.proj, "in_channels"):
  737. resolved_c = int(x_embedder.proj.in_channels)
  738.  
  739. if resolved_c is None and isinstance(in_ch, int) and in_ch > 0:
  740. p = explicit_patch_size if isinstance(explicit_patch_size, int) else 1
  741. if in_ch == 64 and p == 2 and out_ch != 64 and hasattr(backbone, "process_img"):
  742. resolved_c = 16
  743. elif in_ch == 128 and (hasattr(backbone, "emb_in") or p == 2):
  744. resolved_c = 32
  745. else:
  746. resolved_c = int(in_ch)
  747.  
  748. final_c = resolved_c if resolved_c is not None else default_c
  749. self._cached_latent_channels[bid] = final_c
  750. return final_c
  751.  
  752. def _infer_backbone_context_dim(self, backbone: nn.Module) -> Optional[int]:
  753. """Inspect a live ComfyUI `diffusion_model` (or `unet_config`) to find its expected text conditioning feature width."""
  754. bid = id(backbone)
  755. if bid in self._cached_context_dim:
  756. return self._cached_context_dim[bid]
  757.  
  758. for norm_attr in ("llm_cond_norm", "context_norm", "txt_norm"):
  759. norm_mod = getattr(backbone, norm_attr, None)
  760. if norm_mod is not None:
  761. ns = getattr(norm_mod, "normalized_shape", None)
  762. if isinstance(ns, (tuple, list, torch.Size)) and len(ns) == 1 and int(ns[0]) > 0:
  763. self._cached_context_dim[bid] = int(ns[0])
  764. return int(ns[0])
  765.  
  766. text_embedder = getattr(backbone, "text_embedder", None)
  767. if text_embedder is not None:
  768. proj = getattr(text_embedder, "proj", None)
  769. in_f = _get_linear_in_features(proj)
  770. if in_f is not None:
  771. self._cached_context_dim[bid] = in_f
  772. return in_f
  773.  
  774. for attr in (
  775. "context_in",
  776. "context_embedder",
  777. "txt_embed",
  778. "cond_proj",
  779. "condition_proj",
  780. "text_proj",
  781. "caption_projection",
  782. "txt_in",
  783. "llm_proj",
  784. ):
  785. mod = getattr(backbone, attr, None)
  786. in_f = _get_linear_in_features(mod)
  787. if in_f is not None:
  788. self._cached_context_dim[bid] = in_f
  789. return in_f
  790.  
  791. text_emb = getattr(backbone, "text_embedding", None)
  792. if isinstance(text_emb, nn.Sequential) and len(text_emb) > 0:
  793. in_f = _get_linear_in_features(text_emb[0])
  794. if in_f is not None:
  795. self._cached_context_dim[bid] = in_f
  796. return in_f
  797.  
  798. for name, mod in backbone.named_modules():
  799. if any(
  800. name.endswith(suffix)
  801. for suffix in (
  802. "attn2.to_k",
  803. "cross_attn.k",
  804. "cross_attn.k_proj",
  805. "cross_attn.to_k",
  806. "cross_attn.to_kv",
  807. "txt_attn.qkv",
  808. "context_block.attn.qkv",
  809. )
  810. ):
  811. in_f = _get_linear_in_features(mod)
  812. if in_f is not None:
  813. self._cached_context_dim[bid] = in_f
  814. return in_f
  815.  
  816. for cfg_key in (
  817. "context_in_dim",
  818. "joint_attention_dim",
  819. "caption_channels",
  820. "cross_attention_dim",
  821. "context_dim",
  822. "text_dim",
  823. "text_in_dim",
  824. "llm_dim",
  825. ):
  826. cfg_val = getattr(backbone, cfg_key, self.unet_config.get(cfg_key))
  827. if isinstance(cfg_val, (tuple, list)) and cfg_val:
  828. non_zero = [int(v) for v in cfg_val if isinstance(v, int) and v > 0]
  829. if non_zero:
  830. cfg_val = non_zero[-1]
  831. if isinstance(cfg_val, int) and cfg_val > 0:
  832. self._cached_context_dim[bid] = cfg_val
  833. return cfg_val
  834.  
  835. self._cached_context_dim[bid] = None
  836. return None
  837.  
  838. def _infer_backbone_vector_dim(self, backbone: nn.Module) -> Optional[int]:
  839. """
  840. Inspect a live ComfyUI `diffusion_model` (or `unet_config`) to find its expected pooled/ADM
  841. vector conditioning width (`y` / `pooled_projections`, e.g. 2816 for SDXL `label_emb`,
  842. 768 for Flux `vector_in`, 2048 for SD3 `y_embedder`, or HiDream `p_embedder`).
  843. """
  844. bid = id(backbone)
  845. if bid in self._cached_vector_dim:
  846. return self._cached_vector_dim[bid]
  847.  
  848. for cfg_key in ("adm_in_channels", "vec_in_dim", "pooled_projection_dim"):
  849. cfg_val = getattr(backbone, cfg_key, None)
  850. if isinstance(cfg_val, int) and cfg_val > 0:
  851. self._cached_vector_dim[bid] = cfg_val
  852. return cfg_val
  853.  
  854. for attr in ("vector_in", "y_embedder", "p_embedder", "label_emb"):
  855. mod = getattr(backbone, attr, None)
  856. if mod is None:
  857. continue
  858. for sub in (
  859. mod,
  860. getattr(mod, "in_layer", None),
  861. getattr(mod, "mlp", None),
  862. getattr(mod, "linear_1", None),
  863. ):
  864. if sub is None:
  865. continue
  866. in_f = _get_linear_in_features(sub)
  867. if in_f is not None:
  868. self._cached_vector_dim[bid] = in_f
  869. return in_f
  870. if isinstance(sub, (nn.Sequential, nn.ModuleList)) and len(sub) > 0:
  871. first = sub[0]
  872. in_f = _get_linear_in_features(first)
  873. if in_f is not None:
  874. self._cached_vector_dim[bid] = in_f
  875. return in_f
  876. if isinstance(first, (nn.Sequential, nn.ModuleList)) and len(first) > 0:
  877. in_f = _get_linear_in_features(first[0])
  878. if in_f is not None:
  879. self._cached_vector_dim[bid] = in_f
  880. return in_f
  881.  
  882. for cfg_key in ("adm_in_channels", "vec_in_dim", "pooled_projection_dim"):
  883. cfg_val = self.unet_config.get(cfg_key)
  884. if isinstance(cfg_val, int) and cfg_val > 0:
  885. self._cached_vector_dim[bid] = cfg_val
  886. return cfg_val
  887.  
  888. self._cached_vector_dim[bid] = None
  889. return None
  890.  
  891. def _prepare_vector_embeds(
  892. self,
  893. y: torch.Tensor,
  894. backbone: nn.Module,
  895. spatial_h: int = 1024,
  896. spatial_w: int = 1024,
  897. ) -> torch.Tensor:
  898. """
  899. Ensure vector/ADM conditioning tensor `y` matches the input dimension of `backbone.label_emb`,
  900. `backbone.vector_in`, or `backbone.y_embedder`. When `backbone` is an SDXL-family UNet whose
  901. `label_emb` expects `pooled_output` + 256-dim sinusoidal `Timestep` ADM embeddings
  902. (`[height, width, crop_h, crop_w, target_height, target_width]` = 1536 dims) and only
  903. `pooled_output` (`[B, 1280]`) was provided, synthesizes exact sinusoidal ADM embeddings
  904. matching ComfyUI's `SDXL.encode_adm`.
  905. """
  906. expected_v = self._infer_backbone_vector_dim(backbone)
  907. if expected_v is None or y.ndim < 2:
  908. return y
  909. actual_v = int(y.shape[-1])
  910. if actual_v == expected_v:
  911. return y
  912. if expected_v > actual_v:
  913. diff = expected_v - actual_v
  914. if diff in (1536, 1280, 768, 512, 256) and diff % 256 == 0 and y.ndim == 2:
  915. try:
  916. num_adm_tokens = diff // 256
  917. adm_scalars = [
  918. float(spatial_h),
  919. float(spatial_w),
  920. 0.0,
  921. 0.0,
  922. float(spatial_h),
  923. float(spatial_w),
  924. ][:num_adm_tokens]
  925. half = 128
  926. freqs = torch.exp(
  927. -math.log(10000.0)
  928. * torch.arange(start=0, end=half, dtype=torch.float32)
  929. / float(half)
  930. )
  931. t_vals = torch.tensor(adm_scalars, dtype=torch.float32)[:, None] * freqs[None, :]
  932. adm_1d = torch.cat([torch.cos(t_vals), torch.sin(t_vals)], dim=-1).reshape(1, diff)
  933. adm_batch = safe_to_device(adm_1d, device=y.device, dtype=y.dtype).repeat(y.shape[0], 1)
  934. return torch.cat([y, adm_batch], dim=-1)
  935. except Exception:
  936. pass
  937. return F.pad(y, (0, diff))
  938. return y[..., :expected_v]
  939.  
  940. def _infer_backbone_raw_input_channels(self, backbone: nn.Module) -> Optional[int]:
  941. """
  942. Determine the unpacked input channel count directly expected by the first layer of `backbone`
  943. so that Inpaint / I2V / Control / Edit models (`in_channels > latent_channels`, e.g. 9 vs 4
  944. for SDXL-Inpaint, 36 vs 16 for Wan-I2V, 32/96 vs 16 for Flux Control/Fill) can have their
  945. extra `c_concat` conditioning channels populated automatically.
  946. """
  947. bid = id(backbone)
  948. if bid in self._cached_raw_input_channels:
  949. return self._cached_raw_input_channels[bid]
  950.  
  951. raw_c: Optional[int] = None
  952. explicit_patch_size = getattr(backbone, "patch_size", self.unet_config.get("patch_size", None))
  953.  
  954. # 1. Check OpenAI / SD1.5 / SDXL UNet `input_blocks[0][0]` or `conv_in` or `patch_embedding`
  955. for conv_attr in ("conv_in", "patch_embedding"):
  956. conv_mod = getattr(backbone, conv_attr, None)
  957. if conv_mod is not None and isinstance(getattr(conv_mod, "in_channels", None), int):
  958. raw_c = int(conv_mod.in_channels)
  959. break
  960.  
  961. if raw_c is None:
  962. input_blocks = getattr(backbone, "input_blocks", None)
  963. if isinstance(input_blocks, (nn.ModuleList, nn.Sequential)) and len(input_blocks) > 0:
  964. b0 = input_blocks[0]
  965. first_conv = b0[0] if isinstance(b0, (nn.ModuleList, nn.Sequential)) and len(b0) > 0 else b0
  966. if isinstance(getattr(first_conv, "in_channels", None), int):
  967. raw_c = int(first_conv.in_channels)
  968.  
  969. # 2. Check DiT / MMDiT `x_embedder`, `patch_embed`, `img_in`, `init_x_linear`, or `emb_in`
  970. if raw_c is None:
  971. for emb_attr in ("x_embedder", "patch_embed", "img_in", "init_x_linear", "patchify_proj"):
  972. emb_mod = getattr(backbone, emb_attr, None)
  973. if emb_mod is None:
  974. continue
  975. if isinstance(getattr(emb_mod, "in_channels", None), int) and int(emb_mod.in_channels) > 0:
  976. raw_c = int(emb_mod.in_channels)
  977. break
  978. proj = getattr(emb_mod, "proj", None)
  979. if proj is not None and isinstance(getattr(proj, "in_channels", None), int) and int(proj.in_channels) > 0:
  980. raw_c = int(proj.in_channels)
  981. break
  982. in_f = _get_linear_in_features(emb_mod)
  983. if isinstance(in_f, int) and in_f > 0:
  984. p_area = 1
  985. if explicit_patch_size is not None:
  986. p_area = (
  987. int(explicit_patch_size[0]) * int(explicit_patch_size[1])
  988. if isinstance(explicit_patch_size, (tuple, list)) and len(explicit_patch_size) >= 2
  989. else (
  990. int(explicit_patch_size[-1]) ** 2
  991. if isinstance(explicit_patch_size, (tuple, list))
  992. else int(explicit_patch_size) ** 2
  993. )
  994. )
  995. if p_area > 1 and in_f % p_area == 0:
  996. raw_c = in_f // p_area
  997. else:
  998. raw_c = in_f
  999. break
  1000.  
  1001. if raw_c is None:
  1002. emb_in = getattr(backbone, "emb_in", None)
  1003. if isinstance(emb_in, nn.ModuleDict) and len(emb_in) > 0:
  1004. first_emb = emb_in["image"] if "image" in emb_in else next(iter(emb_in.values()))
  1005. in_f = _get_linear_in_features(first_emb)
  1006. if isinstance(in_f, int) and in_f > 0:
  1007. p_area = 4 if (explicit_patch_size in (None, 2) and in_f in (64, 128)) else 1
  1008. raw_c = in_f // p_area
  1009.  
  1010. if raw_c is None:
  1011. in_ch = getattr(backbone, "in_channels", self.unet_config.get("in_channels", None))
  1012. if isinstance(in_ch, int) and in_ch > 0:
  1013. p = explicit_patch_size if isinstance(explicit_patch_size, int) else 1
  1014. if in_ch >= 64 and p == 2 and (hasattr(backbone, "process_img") or hasattr(backbone, "emb_in")) and in_ch % 4 == 0:
  1015. raw_c = in_ch // 4
  1016. else:
  1017. raw_c = int(in_ch)
  1018.  
  1019. self._cached_raw_input_channels[bid] = raw_c
  1020. return raw_c
  1021.  
  1022. def _prepare_concat_input_channels(
  1023. self,
  1024. noisy_latents: torch.Tensor,
  1025. backbone: nn.Module,
  1026. c_concat: Optional[torch.Tensor] = None,
  1027. clean_latents: Optional[torch.Tensor] = None,
  1028. ) -> torch.Tensor:
  1029. """
  1030. Apply ComfyUI's `c_concat` channel concatenation and automatically pad any remaining
  1031. conditioning channels required by Inpaint / I2V / Control / Edit models.
  1032. """
  1033. if isinstance(c_concat, torch.Tensor):
  1034. cc = c_concat.to(device=noisy_latents.device, dtype=noisy_latents.dtype)
  1035. if cc.ndim == noisy_latents.ndim - 1 and noisy_latents.ndim == 5:
  1036. cc = cc.unsqueeze(2).expand(-1, -1, noisy_latents.shape[2], -1, -1)
  1037. if cc.shape[0] == 1 and noisy_latents.shape[0] > 1:
  1038. cc = cc.repeat(noisy_latents.shape[0], *([1] * (cc.ndim - 1)))
  1039. if cc.shape[2:] == noisy_latents.shape[2:]:
  1040. noisy_latents = torch.cat([noisy_latents, cc], dim=1)
  1041.  
  1042. raw_in_c = self._infer_backbone_raw_input_channels(backbone)
  1043. actual_c = int(noisy_latents.shape[1])
  1044. if raw_in_c is not None and raw_in_c > actual_c:
  1045. extra_c = raw_in_c - actual_c
  1046. if (
  1047. isinstance(clean_latents, torch.Tensor)
  1048. and clean_latents.shape == noisy_latents.shape
  1049. and extra_c >= actual_c
  1050. ):
  1051. ref_cond = clean_latents.detach().to(device=noisy_latents.device, dtype=noisy_latents.dtype)
  1052. rem_c = extra_c - actual_c
  1053. if rem_c > 0:
  1054. pad_shape = list(noisy_latents.shape)
  1055. pad_shape[1] = rem_c
  1056. zeros = torch.zeros(pad_shape, device=noisy_latents.device, dtype=noisy_latents.dtype)
  1057. noisy_latents = torch.cat([noisy_latents, ref_cond, zeros], dim=1)
  1058. else:
  1059. noisy_latents = torch.cat([noisy_latents, ref_cond], dim=1)
  1060. else:
  1061. pad_shape = list(noisy_latents.shape)
  1062. pad_shape[1] = extra_c
  1063. zeros = torch.zeros(pad_shape, device=noisy_latents.device, dtype=noisy_latents.dtype)
  1064. noisy_latents = torch.cat([noisy_latents, zeros], dim=1)
  1065. return noisy_latents
  1066.  
  1067. @staticmethod
  1068. def _adapt_latent_channels_spatial(
  1069. latents: torch.Tensor,
  1070. expected_c: int,
  1071. ) -> Optional[torch.Tensor]:
  1072. """
  1073. Automatically adapt between unpacked (`[B, C, H, W]`, e.g. 16-ch @ 8x) and patch-packed
  1074. (`[B, C * r^2, H // r, W // r]`, e.g. 64-ch @ 16x) latent formats using exact, invertible
  1075. `F.pixel_unshuffle` / `F.pixel_shuffle` space-to-depth operations when `expected_c` and
  1076. `actual_c` differ by an integer square patch factor `r^2` (`r in (2, 4)`).
  1077. """
  1078. actual_c = int(latents.shape[1])
  1079. if actual_c == expected_c:
  1080. return latents
  1081. # Only adapt between modern 16+/32+ channel latents and their 2x2/4x4 patch-packed 64/128 channel counterparts;
  1082. # never convert 4-channel SD1.5/SDXL latents into 16-channel Flux/MOSS latents.
  1083. if min(actual_c, expected_c) < 16:
  1084. return None
  1085.  
  1086. is_5d = latents.ndim == 5
  1087. if is_5d:
  1088. b, c, t, h, w = latents.shape
  1089. lat_4d = latents.permute(0, 2, 1, 3, 4).reshape(b * t, c, h, w)
  1090. elif latents.ndim == 4:
  1091. lat_4d = latents
  1092. b, c, t, h, w = latents.shape[0], latents.shape[1], 1, latents.shape[2], latents.shape[3]
  1093. else:
  1094. return None
  1095.  
  1096. adapted_4d: Optional[torch.Tensor] = None
  1097. if expected_c > actual_c and expected_c % actual_c == 0:
  1098. ratio = expected_c // actual_c
  1099. r = int(round(ratio ** 0.5))
  1100. if r in (2, 4) and r * r == ratio and h >= 1 and w >= 1:
  1101. pad_h = (r - (h % r)) % r
  1102. pad_w = (r - (w % r)) % r
  1103. if pad_h > 0 or pad_w > 0:
  1104. lat_4d = F.pad(lat_4d, (0, pad_w, 0, pad_h), mode="replicate")
  1105. adapted_4d = F.pixel_unshuffle(lat_4d, r)
  1106. elif actual_c > expected_c and actual_c % expected_c == 0:
  1107. ratio = actual_c // expected_c
  1108. r = int(round(ratio ** 0.5))
  1109. if r in (2, 4) and r * r == ratio:
  1110. adapted_4d = F.pixel_shuffle(lat_4d, r)
  1111.  
  1112. if adapted_4d is None:
  1113. return None
  1114. if is_5d:
  1115. new_h, new_w = int(adapted_4d.shape[-2]), int(adapted_4d.shape[-1])
  1116. return adapted_4d.reshape(b, t, expected_c, new_h, new_w).permute(0, 2, 1, 3, 4)
  1117. return adapted_4d
  1118.  
  1119. def _validate_and_prepare_latents(
  1120. self,
  1121. latents: torch.Tensor,
  1122. backbone: nn.Module,
  1123. latent_scaled: bool = True,
  1124. ) -> torch.Tensor:
  1125. """
  1126. Apply ComfyUI's `process_latent_in` if not yet scaled during pre-caching, adjust 4D/5D
  1127. video axis if needed, verify (or auto-adapt 2x2/4x4 space-to-depth) VAE latent channels,
  1128. and align spatial dimensions `(H, W)` to the backbone's patchifier stride (`patch_size`).
  1129. """
  1130. scaled_ok = bool(latent_scaled)
  1131. if not scaled_ok:
  1132. process_in = getattr(self.inner_model, "process_latent_in", None) if self.inner_model is not None else None
  1133. if callable(process_in):
  1134. try:
  1135. latents = process_in(latents)
  1136. scaled_ok = True
  1137. except Exception:
  1138. pass
  1139. elif self.latent_format is not None and hasattr(self.latent_format, "process_in"):
  1140. try:
  1141. latents = self.latent_format.process_in(latents)
  1142. scaled_ok = True
  1143. except Exception:
  1144. pass
  1145.  
  1146. expected_c = self._infer_backbone_latent_channels(backbone, fallback_channels=int(latents.shape[1]))
  1147. actual_c = int(latents.shape[1])
  1148.  
  1149. if actual_c != expected_c:
  1150. adapted = self._adapt_latent_channels_spatial(latents, expected_c)
  1151. if adapted is not None:
  1152. latents = adapted
  1153. actual_c = int(latents.shape[1])
  1154.  
  1155. if not scaled_ok:
  1156. process_in = getattr(self.inner_model, "process_latent_in", None) if self.inner_model is not None else None
  1157. if callable(process_in):
  1158. try:
  1159. latents = process_in(latents)
  1160. except Exception:
  1161. pass
  1162. elif self.latent_format is not None and hasattr(self.latent_format, "process_in"):
  1163. try:
  1164. latents = self.latent_format.process_in(latents)
  1165. except Exception:
  1166. pass
  1167.  
  1168. accepts_5d = self._infer_backbone_accepts_5d(backbone, default=self.spec.supports_video_5d)
  1169. if accepts_5d and latents.ndim == 4:
  1170. latents = latents.unsqueeze(2)
  1171. elif not accepts_5d and latents.ndim == 5:
  1172. latents = latents[:, :, 0, :, :]
  1173.  
  1174. if actual_c != expected_c:
  1175. raise ValueError(
  1176. f"VAE latent channel mismatch: connected VAE produced {actual_c}-channel latents "
  1177. f"(shape {tuple(latents.shape)}), but the connected ComfyUI model "
  1178. f"('{self.spec.display_name}') expects {expected_c}-channel latents. "
  1179. f"Please connect the matching VAELoader for this model."
  1180. )
  1181.  
  1182. if latents.ndim >= 4:
  1183. raw_ps = getattr(
  1184. backbone,
  1185. "patch_size",
  1186. getattr(
  1187. backbone,
  1188. "patch_spatial",
  1189. self.unet_config.get("patch_size", self.unet_config.get("patch_spatial", self.spec.patch_size)),
  1190. ),
  1191. )
  1192. if isinstance(raw_ps, (tuple, list)) and len(raw_ps) >= 2:
  1193. stride_h = max(1, int(raw_ps[-2]))
  1194. stride_w = max(1, int(raw_ps[-1]))
  1195. elif isinstance(raw_ps, int) and raw_ps > 1:
  1196. stride_h = stride_w = int(raw_ps)
  1197. else:
  1198. stride_h = stride_w = max(2, int(self.spec.patch_size or 2))
  1199. if hasattr(backbone, "input_blocks") and hasattr(backbone, "output_blocks"):
  1200. stride_h = max(stride_h, 4)
  1201. stride_w = max(stride_w, 4)
  1202. lat_h, lat_w = int(latents.shape[-2]), int(latents.shape[-1])
  1203. pad_h = (stride_h - (lat_h % stride_h)) % stride_h
  1204. pad_w = (stride_w - (lat_w % stride_w)) % stride_w
  1205. if pad_h > 0 or pad_w > 0:
  1206. latents = F.pad(latents, (0, pad_w, 0, pad_h))
  1207. return latents
  1208.  
  1209. def _prepare_prompt_embeds(self, prompt_embeds: torch.Tensor, backbone: nn.Module) -> torch.Tensor:
  1210. """
  1211. Validate and automatically adapt the connected CLIP text encoder's embedding dimension
  1212. against the diffusion model's text input projection or conditioning norm (handling both
  1213. integer-multiple multi-layer widths like 4096 <-> 53248 and cross-encoder widths like 768 -> 4096).
  1214. """
  1215. expected_dim = self._infer_backbone_context_dim(backbone)
  1216. if expected_dim is None or prompt_embeds.ndim < 2:
  1217. return prompt_embeds
  1218. return _adapt_context_width(prompt_embeds, expected_dim, model_name=self.spec.display_name)
  1219.  
  1220. def _validate_context_dim(self, prompt_embeds: torch.Tensor, backbone: nn.Module) -> None:
  1221. """
  1222. Ensure the connected CLIP text encoder's embedding dimension can be adapted to the
  1223. diffusion model's text input projection.
  1224. """
  1225. _ = self._prepare_prompt_embeds(prompt_embeds, backbone)
  1226.  
  1227. def _get_forward_signature_info(self, backbone: nn.Module) -> Tuple[set[str], bool]:
  1228. """
  1229. Cache `inspect.signature` parameter metadata for `backbone.forward` and (when present)
  1230. `backbone._forward` (used by `comfy.patcher_extension.WrapperExecutor` in Flux 3, Flux,
  1231. Qwen, Wan, LTXV, etc.).
  1232. """
  1233. bid = id(backbone)
  1234. if bid in self._cached_forward_sig:
  1235. return self._cached_forward_sig[bid]
  1236. param_names: set[str] = set()
  1237. accepts_var_kwargs = True
  1238. try:
  1239. sig_fwd = inspect.signature(backbone.forward)
  1240. param_names.update(sig_fwd.parameters.keys())
  1241. fwd_var_kw = any(
  1242. p.kind == inspect.Parameter.VAR_KEYWORD for p in sig_fwd.parameters.values()
  1243. )
  1244. inner_fwd = getattr(backbone, "_forward", None)
  1245. if callable(inner_fwd):
  1246. sig_inner = inspect.signature(inner_fwd)
  1247. param_names.update(sig_inner.parameters.keys())
  1248. inner_var_kw = any(
  1249. p.kind == inspect.Parameter.VAR_KEYWORD for p in sig_inner.parameters.values()
  1250. )
  1251. accepts_var_kwargs = fwd_var_kw and inner_var_kw
  1252. else:
  1253. accepts_var_kwargs = fwd_var_kw
  1254. except (ValueError, TypeError):
  1255. param_names = set()
  1256. accepts_var_kwargs = True
  1257. param_names.discard("self")
  1258. self._cached_forward_sig[bid] = (param_names, accepts_var_kwargs)
  1259. return param_names, accepts_var_kwargs
  1260.  
  1261. def _build_transformer_options(
  1262. self,
  1263. noisy_latents: torch.Tensor,
  1264. timesteps: torch.Tensor,
  1265. sigma: Optional[torch.Tensor] = None,
  1266. existing: Optional[Dict[str, Any]] = None,
  1267. ) -> OmniTransformerOptions:
  1268. """
  1269. Construct a complete ComfyUI `transformer_options` dictionary populated with
  1270. `sample_sigmas`, `sigmas`, `cond_or_uncond`, and patch/wrapper registries.
  1271. """
  1272. opts = OmniTransformerOptions()
  1273. if self.comfy_model is not None:
  1274. model_opts = getattr(self.comfy_model, "model_options", None)
  1275. if isinstance(model_opts, dict):
  1276. base_to = model_opts.get("transformer_options")
  1277. if isinstance(base_to, dict):
  1278. opts.update(base_to)
  1279. if isinstance(existing, dict):
  1280. opts.update(existing)
  1281.  
  1282. bsz = int(noisy_latents.shape[0]) if noisy_latents.ndim >= 1 else 1
  1283. opts["sample_sigmas"] = _build_training_sample_sigmas(timesteps=timesteps, sigma=sigma)
  1284. opts["sigmas"] = (
  1285. sigma.detach().to(device=timesteps.device, dtype=timesteps.dtype)
  1286. if isinstance(sigma, torch.Tensor)
  1287. else timesteps.detach()
  1288. )
  1289. opts.setdefault("cond_or_uncond", [0] * bsz)
  1290. opts.setdefault("patches", {})
  1291. opts.setdefault("patches_replace", {})
  1292. opts.setdefault("wrappers", {})
  1293. opts.setdefault("callbacks", {})
  1294. if _is_omni_training_active():
  1295. # Route all attention calls carrying `transformer_options` through differentiable PyTorch SDPA
  1296. # even if ComfyUI was launched with `--use-ck-attention` / `--use-sage-attention`, the
  1297. # checkpoint embeds a `ComfyAttention` config, or a workflow node patched `model_options`.
  1298. opts["optimized_attention_override"] = _omni_training_attention_override
  1299. return opts
  1300.  
  1301. def _forward_backbone(
  1302. self,
  1303. backbone: nn.Module,
  1304. noisy_latents: torch.Tensor,
  1305. timesteps: torch.Tensor,
  1306. prompt_embeds: torch.Tensor,
  1307. pooled_output: Optional[torch.Tensor] = None,
  1308. extra_cond_dict: Optional[Dict[str, Any]] = None,
  1309. sigma: Optional[torch.Tensor] = None,
  1310. clean_latents: Optional[torch.Tensor] = None,
  1311. ) -> torch.Tensor:
  1312. """
  1313. Dispatch forward pass through ComfyUI's native `encode_adm`, `extra_conds`, `c_concat`,
  1314. `process_timestep`, `transformer_options`, and `diffusion_model` without mutating inference tensors.
  1315. """
  1316. prompt_embeds = self._prepare_prompt_embeds(prompt_embeds, backbone)
  1317. param_names, accepts_var_kwargs = self._get_forward_signature_info(backbone)
  1318.  
  1319. kwargs: Dict[str, Any] = {}
  1320. c_concat_tensor: Optional[torch.Tensor] = None
  1321. bsz = int(noisy_latents.shape[0]) if noisy_latents.ndim >= 1 else 1
  1322.  
  1323. spacial_ratio = (
  1324. int(getattr(self.latent_format, "spacial_downscale_ratio", 8))
  1325. if self.latent_format is not None
  1326. else 8
  1327. )
  1328. spatial_h = int(noisy_latents.shape[-2]) * spacial_ratio if noisy_latents.ndim >= 4 else 1024
  1329. spatial_w = int(noisy_latents.shape[-1]) * spacial_ratio if noisy_latents.ndim >= 4 else 1024
  1330.  
  1331. # 1. Ask ComfyUI's native BaseModel.encode_adm(...) & BaseModel.extra_conds(...) to construct conditioning
  1332. if self.inner_model is not None and hasattr(self.inner_model, "extra_conds"):
  1333. try:
  1334. expected_v = self._infer_backbone_vector_dim(backbone)
  1335. cond_pooled = pooled_output
  1336. if (
  1337. isinstance(cond_pooled, torch.Tensor)
  1338. and cond_pooled.ndim >= 2
  1339. and expected_v is not None
  1340. and expected_v > 1536
  1341. and hasattr(self.inner_model, "embedder")
  1342. ):
  1343. expected_clip_pooled = expected_v - 1536
  1344. actual_clip_pooled = int(cond_pooled.shape[-1])
  1345. if actual_clip_pooled < expected_clip_pooled:
  1346. cond_pooled = F.pad(cond_pooled, (0, expected_clip_pooled - actual_clip_pooled))
  1347. elif actual_clip_pooled > expected_clip_pooled and actual_clip_pooled != expected_v:
  1348. cond_pooled = cond_pooled[..., :expected_clip_pooled]
  1349.  
  1350. cond_in: Dict[str, Any] = {
  1351. "cross_attn": prompt_embeds,
  1352. "c_crossattn": prompt_embeds,
  1353. "pooled_output": cond_pooled,
  1354. "noise": noisy_latents,
  1355. "latent_image": clean_latents if isinstance(clean_latents, torch.Tensor) else noisy_latents,
  1356. "device": noisy_latents.device,
  1357. "width": spatial_w,
  1358. "height": spatial_h,
  1359. "crop_w": 0,
  1360. "crop_h": 0,
  1361. "target_width": spatial_w,
  1362. "target_height": spatial_h,
  1363. "aesthetic_score": 6.0,
  1364. "fps_id": 6,
  1365. "motion_bucket_id": 127,
  1366. "augmentation_level": 0.0,
  1367. "noise_aug_strength": 0.0,
  1368. "conditioning_scale": 1.0,
  1369. "seed": 0,
  1370. "prompt_type": "positive",
  1371. }
  1372. if self.spec.requires_guidance_embed or hasattr(backbone, "guidance_in"):
  1373. cond_in["guidance"] = self.guidance_scale
  1374. if extra_cond_dict:
  1375. for ek, ev in extra_cond_dict.items():
  1376. if ev is None:
  1377. continue
  1378. if ek not in cond_in or cond_in[ek] is None:
  1379. ev_for_cond = ev
  1380. # `comfy.model_base.Anima.extra_conds` assumes `t5xxl_ids` and `t5xxl_weights`
  1381. # are 1D `(L_t5,)` tensors and unconditionally calls `.unsqueeze(0)` on them.
  1382. if ek in ("t5xxl_ids", "t5xxl_weights") and isinstance(ev, torch.Tensor) and ev.ndim >= 2:
  1383. ev_for_cond = ev[0] if int(ev.shape[0]) >= 1 else ev.squeeze(0)
  1384. cond_in[ek] = (
  1385. safe_to_device(ev_for_cond, device=noisy_latents.device, dtype=noisy_latents.dtype)
  1386. if isinstance(ev_for_cond, torch.Tensor) and torch.is_floating_point(ev_for_cond)
  1387. else (
  1388. safe_to_device(ev_for_cond, device=noisy_latents.device)
  1389. if isinstance(ev_for_cond, torch.Tensor)
  1390. else ev_for_cond
  1391. )
  1392. )
  1393.  
  1394. if (
  1395. "adm_encoded" not in cond_in
  1396. and hasattr(self.inner_model, "encode_adm")
  1397. and callable(self.inner_model.encode_adm)
  1398. ):
  1399. try:
  1400. adm = self.inner_model.encode_adm(**cond_in)
  1401. if isinstance(adm, torch.Tensor):
  1402. cond_in["adm_encoded"] = safe_to_device(
  1403. adm,
  1404. device=noisy_latents.device,
  1405. dtype=noisy_latents.dtype,
  1406. )
  1407. except Exception:
  1408. pass
  1409.  
  1410. built_conds = self.inner_model.extra_conds(**cond_in)
  1411. for k, v in built_conds.items():
  1412. val = None
  1413. if hasattr(v, "process_cond") and callable(v.process_cond):
  1414. try:
  1415. processed = v.process_cond(batch_size=bsz, device=noisy_latents.device)
  1416. val = getattr(processed, "cond", processed)
  1417. except Exception:
  1418. val = getattr(v, "cond", v)
  1419. else:
  1420. val = getattr(v, "cond", v)
  1421.  
  1422. if isinstance(val, torch.Tensor):
  1423. val = val.clone() if (torch.is_grad_enabled() and val.requires_grad) else val.detach().clone()
  1424. if torch.is_floating_point(val):
  1425. val = safe_to_device(val, device=noisy_latents.device, dtype=noisy_latents.dtype)
  1426. else:
  1427. val = safe_to_device(val, device=noisy_latents.device)
  1428. if val.ndim >= 2 and val.shape[0] == 1 and bsz > 1 and k != "sample_sigmas":
  1429. val = val.repeat(bsz, *([1] * (val.ndim - 1)))
  1430.  
  1431. if k == "c_crossattn":
  1432. if "context" in param_names or accepts_var_kwargs:
  1433. kwargs["context"] = val
  1434. elif k == "c_concat" and isinstance(val, torch.Tensor) and "c_concat" not in param_names:
  1435. c_concat_tensor = val
  1436. elif k in param_names or accepts_var_kwargs:
  1437. kwargs[k] = val
  1438. except Exception:
  1439. pass
  1440.  
  1441. if c_concat_tensor is None and extra_cond_dict and isinstance(extra_cond_dict.get("c_concat"), torch.Tensor):
  1442. c_concat_tensor = extra_cond_dict["c_concat"]
  1443.  
  1444. if extra_cond_dict:
  1445. for ek, ev in extra_cond_dict.items():
  1446. if ev is None or ek in kwargs or ek in ("c_concat", "cross_attn", "c_crossattn", "pooled_output"):
  1447. continue
  1448. if ek in param_names or accepts_var_kwargs:
  1449. kwargs[ek] = (
  1450. safe_to_device(ev, device=noisy_latents.device, dtype=noisy_latents.dtype)
  1451. if isinstance(ev, torch.Tensor) and torch.is_floating_point(ev)
  1452. else (safe_to_device(ev, device=noisy_latents.device) if isinstance(ev, torch.Tensor) else ev)
  1453. )
  1454.  
  1455. # Ensure Anima's `t5xxl_ids` (`[B, L_t5]` int) and `t5xxl_weights` (`[B, L_t5, 1]` float)
  1456. # preserve exact per-sample batch contents and tensor ranks when passed to `Anima.forward`.
  1457. raw_t5_ids = extra_cond_dict.get("t5xxl_ids")
  1458. if isinstance(raw_t5_ids, torch.Tensor) and ("t5xxl_ids" in kwargs or "t5xxl_ids" in param_names or accepts_var_kwargs):
  1459. if not torch.is_inference_mode_enabled() or "t5xxl_ids" in kwargs:
  1460. t5_ids = safe_to_device(raw_t5_ids.detach().clone(), device=noisy_latents.device)
  1461. if torch.is_floating_point(t5_ids):
  1462. t5_ids = t5_ids.to(dtype=torch.long)
  1463. if t5_ids.ndim == 1:
  1464. t5_ids = t5_ids.unsqueeze(0)
  1465. elif t5_ids.ndim >= 3 and int(t5_ids.shape[0]) == 1:
  1466. t5_ids = t5_ids.squeeze(0)
  1467. if t5_ids.ndim == 2 and int(t5_ids.shape[0]) == 1 and bsz > 1:
  1468. t5_ids = t5_ids.repeat(bsz, 1)
  1469. kwargs["t5xxl_ids"] = t5_ids
  1470.  
  1471. raw_t5_w = extra_cond_dict.get("t5xxl_weights")
  1472. if isinstance(raw_t5_w, torch.Tensor) and ("t5xxl_weights" in kwargs or "t5xxl_weights" in param_names or accepts_var_kwargs):
  1473. if not torch.is_inference_mode_enabled() or "t5xxl_weights" in kwargs:
  1474. t5_w = safe_to_device(raw_t5_w.detach().clone(), device=noisy_latents.device, dtype=noisy_latents.dtype)
  1475. if t5_w.ndim == 1:
  1476. t5_w = t5_w.unsqueeze(0).unsqueeze(-1)
  1477. elif t5_w.ndim == 2:
  1478. t5_w = t5_w.unsqueeze(-1)
  1479. elif t5_w.ndim == 4 and int(t5_w.shape[0]) == 1:
  1480. t5_w = t5_w.squeeze(0)
  1481. if t5_w.ndim == 3 and int(t5_w.shape[0]) == 1 and bsz > 1:
  1482. t5_w = t5_w.repeat(bsz, 1, 1)
  1483. kwargs["t5xxl_weights"] = t5_w
  1484.  
  1485. # 2. Ensure primary text conditioning is mapped to the parameter name expected by backbone.forward
  1486. if not any(k in kwargs for k in ("context", "prompt_embeds", "encoder_hidden_states", "txt")):
  1487. if "context" in param_names:
  1488. kwargs["context"] = prompt_embeds
  1489. elif "prompt_embeds" in param_names:
  1490. kwargs["prompt_embeds"] = prompt_embeds
  1491. elif "encoder_hidden_states" in param_names:
  1492. kwargs["encoder_hidden_states"] = prompt_embeds
  1493. elif "txt" in param_names:
  1494. kwargs["txt"] = prompt_embeds
  1495. elif accepts_var_kwargs:
  1496. kwargs["context"] = prompt_embeds
  1497.  
  1498. # 3. Supply pooled/ADM `y` if `extra_conds` did not already build it AND the model requires pooled conditioning
  1499. has_vec_embedder = any(
  1500. hasattr(backbone, attr) for attr in ("vector_in", "y_embedder", "p_embedder", "label_emb")
  1501. )
  1502. backbone_accepts_y = not (
  1503. hasattr(backbone, "num_classes")
  1504. and getattr(backbone, "num_classes", None) is None
  1505. and not has_vec_embedder
  1506. )
  1507. if not backbone_accepts_y:
  1508. kwargs.pop("y", None)
  1509. elif (
  1510. pooled_output is not None
  1511. and (self.spec.requires_pooled_conditioning or has_vec_embedder)
  1512. and "y" not in kwargs
  1513. and "pooled_projections" not in kwargs
  1514. ):
  1515. if "y" in param_names or accepts_var_kwargs:
  1516. kwargs["y"] = pooled_output
  1517. elif "pooled_projections" in param_names:
  1518. kwargs["pooled_projections"] = pooled_output
  1519. elif (
  1520. "y" not in kwargs
  1521. and "pooled_projections" not in kwargs
  1522. and getattr(backbone, "num_classes", None) is not None
  1523. and ("y" in param_names or accepts_var_kwargs)
  1524. ):
  1525. expected_v = self._infer_backbone_vector_dim(backbone) or 2816
  1526. base_v = expected_v - 1536 if expected_v > 1536 else expected_v
  1527. kwargs["y"] = torch.zeros((bsz, base_v), device=noisy_latents.device, dtype=noisy_latents.dtype)
  1528.  
  1529. # Adapt vector conditioning (`y` / `pooled_projections`) width to match `label_emb` / `vector_in` / `y_embedder`
  1530. for vec_key in ("y", "pooled_projections"):
  1531. if isinstance(kwargs.get(vec_key), torch.Tensor):
  1532. kwargs[vec_key] = self._prepare_vector_embeds(
  1533. kwargs[vec_key],
  1534. backbone,
  1535. spatial_h=spatial_h,
  1536. spatial_w=spatial_w,
  1537. )
  1538.  
  1539. # 4. Supply guidance embedding if required by the model (e.g. Flux / Hunyuan / Wan guidance-distilled)
  1540. if (
  1541. (self.spec.requires_guidance_embed or hasattr(backbone, "guidance_in"))
  1542. and "guidance" in param_names
  1543. and "guidance" not in kwargs
  1544. ):
  1545. if noisy_latents.device.type in ("privateuseone", "dml"):
  1546. kwargs["guidance"] = safe_to_device(
  1547. torch.full((noisy_latents.shape[0],), self.guidance_scale, dtype=torch.float32),
  1548. device=noisy_latents.device,
  1549. dtype=noisy_latents.dtype,
  1550. )
  1551. else:
  1552. kwargs["guidance"] = torch.full(
  1553. (noisy_latents.shape[0],),
  1554. self.guidance_scale,
  1555. device=noisy_latents.device,
  1556. dtype=noisy_latents.dtype,
  1557. )
  1558.  
  1559. # 5. Apply `c_concat` and pad any extra input channels required by Inpaint / I2V / Control / Edit models
  1560. noisy_latents = self._prepare_concat_input_channels(
  1561. noisy_latents,
  1562. backbone=backbone,
  1563. c_concat=c_concat_tensor,
  1564. clean_latents=clean_latents,
  1565. )
  1566.  
  1567. # 6. Apply ComfyUI BaseModel.process_timestep if implemented on `self.inner_model`
  1568. if self.inner_model is not None and hasattr(self.inner_model, "process_timestep") and callable(self.inner_model.process_timestep):
  1569. try:
  1570. processed_t = self.inner_model.process_timestep(timesteps, x=noisy_latents, **kwargs)
  1571. if isinstance(processed_t, torch.Tensor):
  1572. timesteps = processed_t.to(device=noisy_latents.device, dtype=timesteps.dtype)
  1573. except Exception:
  1574. pass
  1575.  
  1576. # 7. Always populate `transformer_options` with `sample_sigmas`, `sigmas`, and patch registries
  1577. # whenever `transformer_options` is accepted by `backbone.forward` / `_forward`
  1578. if "transformer_options" in param_names or "transformer_options" in kwargs:
  1579. kwargs["transformer_options"] = self._build_transformer_options(
  1580. noisy_latents=noisy_latents,
  1581. timesteps=timesteps,
  1582. sigma=sigma,
  1583. existing=kwargs.get("transformer_options"),
  1584. )
  1585.  
  1586. # Remove positional argument names from kwargs to avoid TypeError: got multiple values for argument
  1587. for pos_key in ("x", "timestep", "timesteps"):
  1588. kwargs.pop(pos_key, None)
  1589.  
  1590. is_dml_dev = noisy_latents.device.type in ("privateuseone", "dml")
  1591. dml_infer_ctx = (
  1592. torch.inference_mode(False)
  1593. if (is_dml_dev and torch.is_inference_mode_enabled())
  1594. else contextlib.nullcontext()
  1595. )
  1596. with dml_infer_ctx:
  1597. if is_inference_tensor(noisy_latents):
  1598. noisy_latents = noisy_latents.detach().clone()
  1599. if is_inference_tensor(timesteps):
  1600. timesteps = timesteps.detach().clone()
  1601. if isinstance(prompt_embeds, torch.Tensor) and is_inference_tensor(prompt_embeds):
  1602. prompt_embeds = prompt_embeds.detach().clone()
  1603.  
  1604. for k, v in list(kwargs.items()):
  1605. if isinstance(v, torch.Tensor) and is_inference_tensor(v):
  1606. kwargs[k] = v.detach().clone()
  1607.  
  1608. mm_mod_for_train: Optional[Any] = None
  1609. prev_mm_in_training: Optional[bool] = None
  1610. if torch.is_grad_enabled():
  1611. if not noisy_latents.requires_grad:
  1612. noisy_latents = noisy_latents.detach().requires_grad_(True)
  1613. mp_mod = sys.modules.get("comfy.model_prefetch")
  1614. attn_mod = sys.modules.get("comfy.ldm.modules.attention")
  1615. if (
  1616. (mp_mod is not None and not getattr(getattr(mp_mod, "prefetch_queue_pop", None), "_omni_patched", False))
  1617. or (attn_mod is not None and not getattr(attn_mod, "_omni_attn_hooks_installed", False))
  1618. ):
  1619. install_comfy_runtime_hooks()
  1620. _rebind_comfy_attention_modules(backbone)
  1621. if hasattr(backbone, "reset_prefix_cache") and callable(backbone.reset_prefix_cache):
  1622. try:
  1623. backbone.reset_prefix_cache(False)
  1624. except TypeError:
  1625. try:
  1626. backbone.reset_prefix_cache()
  1627. except Exception:
  1628. pass
  1629. except Exception:
  1630. pass
  1631. mm_mod_for_train = sys.modules.get("comfy.model_management")
  1632. if mm_mod_for_train is not None:
  1633. prev_mm_in_training = bool(getattr(mm_mod_for_train, "in_training", False))
  1634. if not prev_mm_in_training:
  1635. try:
  1636. mm_mod_for_train.in_training = True
  1637. except Exception:
  1638. mm_mod_for_train = None
  1639.  
  1640. backbone_input: Any = noisy_latents
  1641. latent_shapes = kwargs.pop("latent_shapes", None)
  1642. if latent_shapes is not None:
  1643. try:
  1644. import comfy.utils as _cu # type: ignore
  1645.  
  1646. if hasattr(_cu, "unpack_latents"):
  1647. backbone_input = _cu.unpack_latents(noisy_latents, latent_shapes)
  1648. except Exception:
  1649. backbone_input = noisy_latents
  1650.  
  1651. # MiniMax H3 always expects a [video_latent, audio_latent] pair
  1652. # even for still-image (T=1) training. Supply a zero dummy audio latent.
  1653. cls_name = backbone.__class__.__name__ if backbone is not None else ""
  1654. if "MiniMaxH3" in cls_name or "minimax_h3" in cls_name.lower():
  1655. video = backbone_input
  1656. if isinstance(video, torch.Tensor) and video.ndim == 4:
  1657. video = video.unsqueeze(2) # force [B, C, 1, H, W]
  1658. if isinstance(video, torch.Tensor):
  1659. b = video.shape[0]
  1660. dummy_audio = torch.zeros(
  1661. (b, 32, 2, 1),
  1662. device=video.device,
  1663. dtype=video.dtype,
  1664. )
  1665. backbone_input = [video, dummy_audio]
  1666.  
  1667. try:
  1668. if kwargs:
  1669. try:
  1670. out = backbone(backbone_input, timesteps, **kwargs)
  1671. except TypeError:
  1672. if param_names:
  1673. filtered_kw = {k: v for k, v in kwargs.items() if k in param_names}
  1674. out = backbone(backbone_input, timesteps, **filtered_kw)
  1675. else:
  1676. raise
  1677. else:
  1678. out = backbone(backbone_input, timesteps, prompt_embeds)
  1679. finally:
  1680. if mm_mod_for_train is not None and prev_mm_in_training is False:
  1681. try:
  1682. mm_mod_for_train.in_training = False
  1683. except Exception:
  1684. pass
  1685.  
  1686. if isinstance(out, (tuple, list)):
  1687. # MiniMax H3 returns [-video_out, -audio_out]; we only train on the video stream
  1688. cls_name = backbone.__class__.__name__ if backbone is not None else ""
  1689. if "MiniMaxH3" in cls_name or "minimax_h3" in cls_name.lower():
  1690. out = out[0]
  1691. else:
  1692. if len(out) > 1 and all(isinstance(t, torch.Tensor) for t in out):
  1693. try:
  1694. import comfy.utils as _cu # type: ignore
  1695. if hasattr(_cu, "pack_latents"):
  1696. out = _cu.pack_latents(list(out))[0]
  1697. else:
  1698. out = out[0]
  1699. except Exception:
  1700. out = out[0]
  1701. else:
  1702. out = out[0]
  1703. elif isinstance(out, dict):
  1704. out = out.get("sample", next(iter(out.values())))
  1705.  
  1706. return out
  1707.  
  1708. @classmethod
  1709. def _align_prediction_to_target(cls, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
  1710. """
  1711. Ensure `pred` returned by `backbone.forward` matches `target.shape` when a model
  1712. adds/removes a singleton temporal axis (`[B, C, 1, H, W]` <-> `[B, C, H, W]`),
  1713. packs/unpacks spatial patches (`16ch <-> 64ch`), or outputs extra auxiliary channels.
  1714. """
  1715. if pred.shape == target.shape:
  1716. return pred
  1717. if pred.ndim == 5 and target.ndim == 4 and pred.shape[2] == 1:
  1718. pred = pred[:, :, 0, :, :]
  1719. elif pred.ndim == 4 and target.ndim == 5 and target.shape[2] == 1:
  1720. pred = pred.unsqueeze(2)
  1721. if pred.shape != target.shape and pred.ndim in (4, 5) and target.ndim == pred.ndim:
  1722. if int(pred.shape[1]) != int(target.shape[1]):
  1723. adapted = cls._adapt_latent_channels_spatial(pred, int(target.shape[1]))
  1724. if adapted is not None:
  1725. pred = adapted
  1726. elif int(pred.shape[1]) > int(target.shape[1]) and pred.shape[2:] == target.shape[2:]:
  1727. pred = pred[:, : int(target.shape[1])]
  1728. if int(pred.shape[-2]) > int(target.shape[-2]) or int(pred.shape[-1]) > int(target.shape[-1]):
  1729. pred = pred[..., : int(target.shape[-2]), : int(target.shape[-1])]
  1730. return pred
  1731.  
  1732. def _get_device_sigmas(self, sampling: Any, device: torch.device) -> Optional[torch.Tensor]:
  1733. """Return `sampling.sigmas` cached on `device` in `float32` with zero CPU-GPU syncs."""
  1734. sigmas = getattr(sampling, "sigmas", None)
  1735. if not isinstance(sigmas, torch.Tensor) or sigmas.numel() <= 1:
  1736. return None
  1737. if (
  1738. self._cached_sigmas is None
  1739. or self._cached_sigmas.device != device
  1740. or self._cached_sigmas.numel() != sigmas.numel()
  1741. ):
  1742. self._cached_sigmas = safe_to_device(sigmas.detach(), device=device, dtype=torch.float32)
  1743. return self._cached_sigmas
  1744.  
  1745. def _compute_device_timesteps(
  1746. self,
  1747. sampling: Any,
  1748. sigma: torch.Tensor,
  1749. device: torch.device,
  1750. dtype: torch.dtype,
  1751. ) -> torch.Tensor:
  1752. """
  1753. Compute `sampling.timestep(sigma)` on `device` without copying `sigma` back to CPU when
  1754. `sampling` is a `ModelSamplingDiscrete` whose `log_sigmas` buffer resides on CPU.
  1755. """
  1756. log_sigmas = getattr(sampling, "log_sigmas", None)
  1757. if (
  1758. isinstance(log_sigmas, torch.Tensor)
  1759. and log_sigmas.device != device
  1760. and device.type not in ("privateuseone", "dml")
  1761. ):
  1762. if (
  1763. self._cached_log_sigmas is None
  1764. or self._cached_log_sigmas.device != device
  1765. or self._cached_log_sigmas.numel() != log_sigmas.numel()
  1766. ):
  1767. self._cached_log_sigmas = safe_to_device(log_sigmas.detach(), device=device, dtype=torch.float32)
  1768. try:
  1769. orig_log_sigmas = log_sigmas
  1770. sampling.log_sigmas = self._cached_log_sigmas
  1771. try:
  1772. t_out = sampling.timestep(sigma)
  1773. finally:
  1774. sampling.log_sigmas = orig_log_sigmas
  1775. return safe_to_device(t_out, device=device, dtype=dtype)
  1776. except Exception:
  1777. pass
  1778. return safe_to_device(sampling.timestep(sigma), device=device, dtype=dtype)
  1779.  
  1780. def compute_training_loss(
  1781. self,
  1782. backbone: nn.Module,
  1783. batch: Dict[str, Any],
  1784. device: torch.device,
  1785. dtype: torch.dtype,
  1786. ) -> torch.Tensor:
  1787. if device.type in ("privateuseone", "dml") and dtype == torch.bfloat16:
  1788. dtype = torch.float16
  1789. raw_latents = safe_to_device(batch["latents"], device=device, dtype=dtype)
  1790. latent_scaled = bool(batch.get("latent_scaled", True))
  1791. latents = self._validate_and_prepare_latents(
  1792. raw_latents,
  1793. backbone=backbone,
  1794. latent_scaled=latent_scaled,
  1795. )
  1796.  
  1797. prompt_embeds = safe_to_device(batch["prompt_embeds"], device=device, dtype=dtype)
  1798. pooled_output = batch.get("pooled_output")
  1799. if isinstance(pooled_output, torch.Tensor):
  1800. pooled_output = safe_to_device(pooled_output, device=device, dtype=dtype)
  1801. elif self.spec.requires_pooled_conditioning:
  1802. pooled_output = prompt_embeds.to(dtype=torch.float32).mean(dim=1).to(dtype=dtype)
  1803. else:
  1804. pooled_output = None
  1805.  
  1806. extra_cond_dict = batch.get("extra_conds")
  1807.  
  1808. bsz = latents.shape[0]
  1809. broadcast_shape = [bsz] + [1] * (latents.ndim - 1)
  1810. is_flow_objective = self.spec.objective_type in ("rectified_flow", "flow_matching")
  1811. min_snr_gamma = float(getattr(self, "min_snr_gamma", 0.0))
  1812. snr_weight: Optional[torch.Tensor] = None
  1813. t_lo = float(getattr(self, "min_timestep", 0.0))
  1814. t_hi = float(getattr(self, "max_timestep", 1.0))
  1815. t_span = max(1e-5, t_hi - t_lo)
  1816.  
  1817. if self.model_sampling is not None:
  1818. sampling = self.model_sampling
  1819. sigmas_dev = self._get_device_sigmas(sampling, device=device)
  1820. if sigmas_dev is not None:
  1821. max_idx = sigmas_dev.numel() - 1
  1822. if is_flow_objective:
  1823. # Logit-normal timestep sampling for Rectified Flow / Flow Matching,
  1824. # mapped into [min_timestep, max_timestep] for single or split-stage models.
  1825. u_base = torch.sigmoid(torch.randn(bsz, device=device, dtype=torch.float32))
  1826. u_norm = t_lo + u_base * t_span
  1827. else:
  1828. u_base = torch.rand(bsz, device=device, dtype=torch.float32)
  1829. u_norm = t_lo + u_base * t_span
  1830. self.last_timestep = float(u_norm.mean().item())
  1831. pos = (u_norm * float(max_idx)).clamp(0.0, max(0.0, float(max_idx) - 1e-5))
  1832. idx0 = pos.long().clamp(0, max(0, max_idx - 1))
  1833. frac = pos - idx0.to(dtype=torch.float32)
  1834. s0 = sigmas_dev[idx0]
  1835. s1 = sigmas_dev[idx0 + 1]
  1836. sigma = (s0 + (s1 - s0) * frac).clamp(min=1e-5)
  1837. else:
  1838. if is_flow_objective:
  1839. u_base = torch.sigmoid(torch.randn(bsz, device=device, dtype=torch.float32))
  1840. flow_shift = float(getattr(sampling, "shift", 1.0) or 1.0)
  1841. if flow_shift > 0.0 and abs(flow_shift - 1.0) > 1e-4:
  1842. u_base = (flow_shift * u_base) / (1.0 + (flow_shift - 1.0) * u_base)
  1843. else:
  1844. u_base = torch.rand(bsz, device=device, dtype=torch.float32)
  1845. u_norm = (t_lo + u_base * t_span).clamp(1e-4, 0.999)
  1846. self.last_timestep = float(u_norm.mean().item())
  1847. sigma = u_norm
  1848.  
  1849. noise = torch.randn(latents.shape, device=latents.device, dtype=torch.float32).to(dtype=latents.dtype)
  1850.  
  1851. # Pass broadcast-shaped sigma [B, 1, 1, 1] to noise_scaling so both CONST and EPS
  1852. # (which computes `noise * sigma` without reshaping) work for any batch_size >= 1.
  1853. sigma_b = sigma.view(*broadcast_shape)
  1854. noisy_latents = sampling.noise_scaling(sigma_b, noise, latents).to(dtype=dtype)
  1855. xc = sampling.calculate_input(sigma_b, noisy_latents).to(dtype=dtype)
  1856. t_dtype = dtype if device.type in ("privateuseone", "dml") else torch.float32
  1857. timesteps = self._compute_device_timesteps(sampling, sigma, device=device, dtype=t_dtype).view(bsz)
  1858.  
  1859. if self.spec.objective_type == "ddpm_eps":
  1860. target = noise
  1861. if min_snr_gamma > 0.0:
  1862. sig_c = sigma.to(dtype=torch.float32).clamp(min=1e-4)
  1863. snr = (sig_c * sig_c).reciprocal()
  1864. snr_weight = torch.clamp(snr, max=min_snr_gamma) / snr.clamp(min=1e-5)
  1865. elif self.spec.objective_type == "v_prediction":
  1866. # Compute in float32 so `sig_exp * sig_exp` never overflows float16 (65504.0) when sigma > 255
  1867. sig_exp = sigma_b.to(dtype=torch.float32)
  1868. lat_f32 = latents.to(dtype=torch.float32)
  1869. noise_f32 = noise.to(dtype=torch.float32)
  1870. target = (noise_f32 - sig_exp * lat_f32) / torch.sqrt(sig_exp * sig_exp + 1.0)
  1871. if min_snr_gamma > 0.0:
  1872. sig_c = sigma.to(dtype=torch.float32).clamp(min=1e-4)
  1873. snr = (sig_c * sig_c).reciprocal()
  1874. snr_weight = torch.clamp(snr, max=min_snr_gamma) / (snr + 1.0)
  1875. elif self.spec.objective_type == "edm":
  1876. sig_exp = sigma_b.to(dtype=torch.float32)
  1877. lat_f32 = latents.to(dtype=torch.float32)
  1878. noise_f32 = noise.to(dtype=torch.float32)
  1879. sigma_data = float(getattr(sampling, "sigma_data", 1.0))
  1880. sd_sq = sigma_data * sigma_data
  1881. target = (sig_exp * lat_f32 - sd_sq * noise_f32) / (
  1882. sigma_data * torch.sqrt(sig_exp * sig_exp + sd_sq)
  1883. )
  1884. elif self.spec.objective_type == "x0":
  1885. target = latents
  1886. else:
  1887. target = noise.to(dtype=torch.float32) - latents.to(dtype=torch.float32)
  1888.  
  1889. pred = self._forward_backbone(
  1890. backbone=backbone,
  1891. noisy_latents=xc,
  1892. timesteps=timesteps,
  1893. prompt_embeds=prompt_embeds,
  1894. pooled_output=pooled_output,
  1895. extra_cond_dict=extra_cond_dict,
  1896. sigma=sigma,
  1897. clean_latents=latents,
  1898. )
  1899. elif self.spec.objective_type == "ddpm_eps":
  1900. # Fallback DDPM Epsilon-Prediction when model_sampling is not present
  1901. u_base = torch.rand(bsz, device=device, dtype=torch.float32)
  1902. u = (t_lo + u_base * t_span).clamp(1e-4, 0.9999)
  1903. self.last_timestep = float(u.mean().item())
  1904. timesteps = (u * 1000.0).to(dtype=dtype)
  1905. cos_u = torch.cos(u * 1.5707963)
  1906. alpha_bar = cos_u * cos_u
  1907. one_minus_ab = (1.0 - alpha_bar).clamp(min=1e-5)
  1908. sqrt_alpha_bar = torch.sqrt(alpha_bar.clamp(min=1e-5)).to(dtype=dtype).view(*broadcast_shape)
  1909. sqrt_one_minus_alpha_bar = torch.sqrt(one_minus_ab).to(dtype=dtype).view(*broadcast_shape)
  1910.  
  1911. snr = alpha_bar.clamp(min=1e-5) / one_minus_ab
  1912. if min_snr_gamma > 0.0:
  1913. snr_weight = torch.clamp(snr, max=min_snr_gamma) / snr.clamp(min=1e-5)
  1914.  
  1915. noise = torch.randn(latents.shape, device=latents.device, dtype=torch.float32).to(dtype=latents.dtype)
  1916. noisy_latents = sqrt_alpha_bar * latents + sqrt_one_minus_alpha_bar * noise
  1917. target = noise
  1918.  
  1919. pred = self._forward_backbone(
  1920. backbone=backbone,
  1921. noisy_latents=noisy_latents,
  1922. timesteps=timesteps,
  1923. prompt_embeds=prompt_embeds,
  1924. pooled_output=pooled_output,
  1925. extra_cond_dict=extra_cond_dict,
  1926. sigma=u.to(dtype=dtype),
  1927. clean_latents=latents,
  1928. )
  1929. else:
  1930. # Fallback Rectified Flow Velocity Matching when model_sampling is not present
  1931. u_base = torch.sigmoid(torch.randn(bsz, device=device, dtype=torch.float32))
  1932. u_norm = (t_lo + u_base * t_span).clamp(1e-4, 0.9999)
  1933. self.last_timestep = float(u_norm.mean().item())
  1934. timesteps = u_norm.to(dtype=dtype)
  1935. t_expand = timesteps.view(*broadcast_shape)
  1936.  
  1937. noise = torch.randn(latents.shape, device=latents.device, dtype=torch.float32).to(dtype=latents.dtype)
  1938. noisy_latents = latents + t_expand * (noise - latents)
  1939. target = noise - latents
  1940.  
  1941. pred = self._forward_backbone(
  1942. backbone=backbone,
  1943. noisy_latents=noisy_latents,
  1944. timesteps=timesteps,
  1945. prompt_embeds=prompt_embeds,
  1946. pooled_output=pooled_output,
  1947. extra_cond_dict=extra_cond_dict,
  1948. sigma=timesteps,
  1949. clean_latents=latents,
  1950. )
  1951.  
  1952. pred = self._align_prediction_to_target(pred, target)
  1953. diff = pred.to(dtype=torch.float32) - target.to(dtype=torch.float32)
  1954. loss_type = str(getattr(self, "loss_type", "l2") or "l2").lower()
  1955. if loss_type == "huber":
  1956. huber_c = float(getattr(self, "huber_c", 0.1) or 0.1)
  1957. loss_elem = torch.sqrt(diff * diff + (huber_c * huber_c)) - huber_c
  1958. elif loss_type == "l1":
  1959. loss_elem = torch.abs(diff)
  1960. else:
  1961. # Standard diffusion L2 (MSE) loss
  1962. loss_elem = diff * diff
  1963.  
  1964. # Optional spatial mask / alpha-channel loss weighting (`loss_mask` in [0, 1])
  1965. raw_loss_mask = batch.get("loss_mask")
  1966. if isinstance(raw_loss_mask, torch.Tensor) and raw_loss_mask.numel() > 0 and loss_elem.ndim >= 4:
  1967. mask_dev = (
  1968. torch.device("cpu")
  1969. if (raw_loss_mask.device.type == "cpu" or device.type in ("privateuseone", "dml"))
  1970. else device
  1971. )
  1972. m = raw_loss_mask.to(device=mask_dev, dtype=torch.float32)
  1973. if m.ndim == 2:
  1974. m = m.unsqueeze(0).unsqueeze(0)
  1975. elif m.ndim == 3:
  1976. m = m.unsqueeze(1)
  1977. elif m.ndim > 4:
  1978. m = m.view(int(m.shape[0]), 1, int(m.shape[-2]), int(m.shape[-1]))
  1979. if int(m.shape[0]) == 1 and int(loss_elem.shape[0]) > 1:
  1980. m = m.expand(int(loss_elem.shape[0]), -1, -1, -1)
  1981.  
  1982. lat_h, lat_w = int(loss_elem.shape[-2]), int(loss_elem.shape[-1])
  1983. if int(m.shape[-2]) != lat_h or int(m.shape[-1]) != lat_w:
  1984. if int(m.shape[-2]) >= lat_h and int(m.shape[-1]) >= lat_w:
  1985. m = F.interpolate(m, size=(lat_h, lat_w), mode="area")
  1986. else:
  1987. m = F.interpolate(m, size=(lat_h, lat_w), mode="bilinear", align_corners=False)
  1988.  
  1989. m = m.clamp(min=0.0)
  1990. m_mean = m.mean(dim=(-2, -1), keepdim=True).clamp(min=1e-4)
  1991. m_norm = safe_to_device(m / m_mean, device=device, dtype=torch.float32)
  1992. if loss_elem.ndim == 5:
  1993. m_norm = m_norm.unsqueeze(2)
  1994. loss_elem = loss_elem * m_norm
  1995.  
  1996. if snr_weight is not None:
  1997. reduce_dims = list(range(1, loss_elem.ndim))
  1998. per_sample_loss = loss_elem.mean(dim=reduce_dims) if reduce_dims else loss_elem
  1999. return (per_sample_loss * snr_weight.to(dtype=torch.float32)).mean()
  2000. return loss_elem.mean()
  2001.  
  2002. def create_synthetic_batch(
  2003. self,
  2004. batch_size: int,
  2005. resolution: int,
  2006. device: torch.device,
  2007. dtype: torch.dtype,
  2008. ) -> Dict[str, Any]:
  2009. latent_size = max(4, resolution // 8)
  2010. if self.spec.supports_video_5d:
  2011. latents = torch.randn(
  2012. batch_size,
  2013. self.spec.latent_channels,
  2014. 2,
  2015. latent_size,
  2016. latent_size,
  2017. device=device,
  2018. dtype=torch.float32,
  2019. ).to(dtype=dtype)
  2020. else:
  2021. latents = torch.randn(
  2022. batch_size,
  2023. self.spec.latent_channels,
  2024. latent_size,
  2025. latent_size,
  2026. device=device,
  2027. dtype=torch.float32,
  2028. ).to(dtype=dtype)
  2029. prompt_embeds = torch.randn(
  2030. batch_size, 77, self.spec.text_dim, device=device, dtype=torch.float32
  2031. ).to(dtype=dtype)
  2032. batch: Dict[str, Any] = {
  2033. "latents": latents,
  2034. "prompt_embeds": prompt_embeds,
  2035. "latent_scaled": True,
  2036. }
  2037. if self.spec.requires_pooled_conditioning:
  2038. batch["pooled_output"] = prompt_embeds.to(dtype=torch.float32).mean(dim=1).to(dtype=dtype)
  2039. return batch
  2040.  
  2041.  
  2042. # ============================================================================
  2043. # 3. ComfyUI Model Inspection, Target Discovery & Runtime Hooks
  2044. # ============================================================================
  2045.  
  2046. def _get_linear_in_features(mod: Any) -> Optional[int]:
  2047. """Extract `in_features` from `nn.Linear`, `LoRALinear`, GGUF `GGMLOps.Linear`, or `comfy.ops` Linear modules."""
  2048. if mod is None:
  2049. return None
  2050. in_f = getattr(mod, "in_features", None)
  2051. if isinstance(in_f, int) and in_f > 0:
  2052. return in_f
  2053. weight = getattr(mod, "weight", None)
  2054. t_shape = getattr(weight, "tensor_shape", None) or getattr(weight, "orig_shape", None)
  2055. if isinstance(t_shape, (tuple, list, torch.Size)) and len(t_shape) >= 2 and int(t_shape[1]) > 0:
  2056. return int(t_shape[1])
  2057. if isinstance(weight, torch.Tensor) and weight.ndim == 2 and weight.shape[1] > 0:
  2058. return int(weight.shape[1])
  2059. base = getattr(mod, "base_layer", None)
  2060. if base is not None:
  2061. return _get_linear_in_features(base)
  2062. return None
  2063.  
  2064.  
  2065. _LEGACY_MOSS_LAYER_RE = re.compile(
  2066. r"^diffusion_model\.layers_(\d+)_(proj_qkv|proj_o|proj_ffn_up_gate|proj_ffn_down)\.(lora_down\.weight|lora_up\.weight|alpha)$"
  2067. )
  2068. _LEGACY_MOSS_TEXT_BLOCK_RE = re.compile(
  2069. r"^diffusion_model\.text_embedder_blocks_(\d+)_(qkv|proj|ffn_gate|ffn_up|ffn_down)\.(lora_down\.weight|lora_up\.weight|alpha)$"
  2070. )
  2071.  
  2072.  
  2073. def normalize_legacy_lora_key(key: str) -> str:
  2074. """Convert legacy underscored keys to ComfyUI dotted format."""
  2075. m1 = _LEGACY_MOSS_LAYER_RE.match(key)
  2076. if m1:
  2077. idx, proj_name, suffix = m1.groups()
  2078. return f"diffusion_model.layers.{idx}.{proj_name}.{suffix}"
  2079. m2 = _LEGACY_MOSS_TEXT_BLOCK_RE.match(key)
  2080. if m2:
  2081. idx, proj_name, suffix = m2.groups()
  2082. return f"diffusion_model.text_embedder.blocks.{idx}.{proj_name}.{suffix}"
  2083. return key
  2084.  
  2085.  
  2086. _WARNED_CONTEXT_ADAPTATIONS: set[Tuple[int, int]] = set()
  2087. _CACHED_DM_EXPECTED_CONTEXT_DIM: Dict[int, Optional[int]] = {}
  2088.  
  2089.  
  2090. def _adapt_context_width(
  2091. input_t: torch.Tensor,
  2092. expected_dim: int,
  2093. model_name: Optional[str] = None,
  2094. ) -> torch.Tensor:
  2095. """
  2096. Adapt the feature width (last dimension) of text conditioning tensor `input_t` to `expected_dim`:
  2097. - Exact integer multiples (`expected_dim % actual_dim == 0`, e.g. `4096 -> 53248 = 13 * 4096`)
  2098. are tiled cleanly across the feature axis.
  2099. - Non-integer widths (e.g. `768 -> 4096`, `2048 -> 4096`, `2560 -> 4096`, `3584 -> 4096`)
  2100. repeat `ceil(expected_dim / actual_dim)` times and slice `[..., :expected_dim]` (or slice
  2101. `[..., :expected_dim]` when `actual_dim > expected_dim`), emitting a one-time warning when
  2102. non-integer adaptation occurs so workflows never crash on mismatched CLIPLoader connections.
  2103. """
  2104. if not isinstance(input_t, torch.Tensor) or input_t.ndim < 2 or expected_dim <= 0:
  2105. return input_t
  2106. actual_dim = int(input_t.shape[-1])
  2107. if actual_dim <= 0 or actual_dim == expected_dim:
  2108. return input_t
  2109. if expected_dim > actual_dim:
  2110. if expected_dim % actual_dim == 0:
  2111. ratio = expected_dim // actual_dim
  2112. return input_t.repeat(*([1] * (input_t.ndim - 1)), ratio)
  2113. repeats = (expected_dim + actual_dim - 1) // actual_dim
  2114. pair = (actual_dim, expected_dim)
  2115. if pair not in _WARNED_CONTEXT_ADAPTATIONS:
  2116. _WARNED_CONTEXT_ADAPTATIONS.add(pair)
  2117. label = f" for '{model_name}'" if model_name else ""
  2118. logging.warning(
  2119. "[OmniLoRA] Connected CLIP produced %d-dim text embeddings, while model%s expects %d-dim; "
  2120. "automatically adapting conditioning width (%d -> %d). For optimal quality, select the matching "
  2121. "text encoder in CLIPLoader.",
  2122. actual_dim,
  2123. label,
  2124. expected_dim,
  2125. actual_dim,
  2126. expected_dim,
  2127. )
  2128. return input_t.repeat(*([1] * (input_t.ndim - 1)), repeats)[..., :expected_dim]
  2129. if actual_dim % expected_dim == 0:
  2130. return input_t[..., -expected_dim:]
  2131. pair = (actual_dim, expected_dim)
  2132. if pair not in _WARNED_CONTEXT_ADAPTATIONS:
  2133. _WARNED_CONTEXT_ADAPTATIONS.add(pair)
  2134. label = f" for '{model_name}'" if model_name else ""
  2135. logging.warning(
  2136. "[OmniLoRA] Connected CLIP produced %d-dim text embeddings, while model%s expects %d-dim; "
  2137. "automatically slicing conditioning width (%d -> %d).",
  2138. actual_dim,
  2139. label,
  2140. expected_dim,
  2141. actual_dim,
  2142. expected_dim,
  2143. )
  2144. return input_t[..., :expected_dim]
  2145.  
  2146.  
  2147. def _infer_dm_expected_context_dim(
  2148. backbone: Optional[nn.Module],
  2149. unet_config: Optional[Dict[str, Any]] = None,
  2150. ) -> Optional[int]:
  2151. """Infer the expected text conditioning feature width for a ComfyUI `diffusion_model`."""
  2152. if backbone is None:
  2153. return None
  2154. if hasattr(backbone, "_omni_expected_context_dim"):
  2155. return getattr(backbone, "_omni_expected_context_dim")
  2156.  
  2157. for norm_attr in ("llm_cond_norm", "context_norm", "txt_norm"):
  2158. norm_mod = getattr(backbone, norm_attr, None)
  2159. if norm_mod is not None:
  2160. ns = getattr(norm_mod, "normalized_shape", None)
  2161. if isinstance(ns, (tuple, list, torch.Size)) and len(ns) == 1 and int(ns[0]) > 0:
  2162. setattr(backbone, "_omni_expected_context_dim", int(ns[0]))
  2163. return int(ns[0])
  2164.  
  2165. text_embedder = getattr(backbone, "text_embedder", None)
  2166. if text_embedder is not None:
  2167. proj = getattr(text_embedder, "proj", None)
  2168. in_f = _get_linear_in_features(proj)
  2169. if in_f is not None:
  2170. setattr(backbone, "_omni_expected_context_dim", in_f)
  2171. return in_f
  2172.  
  2173. for attr in ("context_in", "context_embedder", "txt_embed", "cond_proj", "caption_projection", "txt_in", "llm_proj"):
  2174. mod = getattr(backbone, attr, None)
  2175. in_f = _get_linear_in_features(mod)
  2176. if in_f is not None:
  2177. setattr(backbone, "_omni_expected_context_dim", in_f)
  2178. return in_f
  2179.  
  2180. text_emb = getattr(backbone, "text_embedding", None)
  2181. if isinstance(text_emb, nn.Sequential) and len(text_emb) > 0:
  2182. in_f = _get_linear_in_features(text_emb[0])
  2183. if in_f is not None:
  2184. setattr(backbone, "_omni_expected_context_dim", in_f)
  2185. return in_f
  2186.  
  2187. for name, mod in backbone.named_modules():
  2188. if any(
  2189. name.endswith(suffix)
  2190. for suffix in (
  2191. "attn2.to_k",
  2192. "cross_attn.k",
  2193. "cross_attn.k_proj",
  2194. "cross_attn.to_k",
  2195. "cross_attn.to_kv",
  2196. "txt_attn.qkv",
  2197. "context_block.attn.qkv",
  2198. )
  2199. ):
  2200. in_f = _get_linear_in_features(mod)
  2201. if in_f is not None:
  2202. setattr(backbone, "_omni_expected_context_dim", in_f)
  2203. return in_f
  2204.  
  2205. if isinstance(unet_config, dict):
  2206. for cfg_key in (
  2207. "context_in_dim",
  2208. "joint_attention_dim",
  2209. "caption_channels",
  2210. "cross_attention_dim",
  2211. "context_dim",
  2212. "llm_dim",
  2213. ):
  2214. cfg_val = unet_config.get(cfg_key)
  2215. if isinstance(cfg_val, (tuple, list)) and cfg_val:
  2216. non_zero = [int(v) for v in cfg_val if isinstance(v, int) and v > 0]
  2217. if non_zero:
  2218. cfg_val = non_zero[-1]
  2219. if isinstance(cfg_val, int) and cfg_val > 0:
  2220. setattr(backbone, "_omni_expected_context_dim", cfg_val)
  2221. return cfg_val
  2222.  
  2223. setattr(backbone, "_omni_expected_context_dim", None)
  2224. return None
  2225.  
  2226.  
  2227. def _adapt_norm_input_last_dim(
  2228. input_t: torch.Tensor,
  2229. normalized_shape: Any,
  2230. ) -> torch.Tensor:
  2231. """
  2232. Zero-overhead conditioning width adapter for `rms_norm` / `layer_norm`:
  2233. When a model's conditioning norm (such as `Ideogram4.llm_cond_norm` with `normalized_shape=[53248]`,
  2234. `13 * 4096`) receives a single-layer Qwen embedding (`[B, seq, 4096]`) or narrower CLIP embedding,
  2235. automatically adapts the last dimension so training and KSampler inference succeed.
  2236. """
  2237. if (
  2238. isinstance(input_t, torch.Tensor)
  2239. and input_t.ndim >= 2
  2240. and isinstance(normalized_shape, (tuple, list, torch.Size))
  2241. and len(normalized_shape) == 1
  2242. ):
  2243. expected_dim = int(normalized_shape[0])
  2244. actual_dim = int(input_t.shape[-1])
  2245. if actual_dim != expected_dim and actual_dim > 0 and expected_dim > 0:
  2246. return _adapt_context_width(input_t, expected_dim)
  2247. return input_t
  2248.  
  2249.  
  2250. def install_comfy_runtime_hooks() -> None:
  2251. """
  2252. Install non-intrusive ComfyUI runtime hooks so that:
  2253. 1. If a cached `diffusion_model` still has any residual `LoRALinear` wrappers, they are
  2254. unwrapped before `LoraLoader` inspects `model.state_dict()`.
  2255. 2. `comfy.lora.model_lora_keys_unet` registers both unprefixed (`<module>`) and prefixed
  2256. (`diffusion_model.<module>`) keys for all direct and tuple-sliced weights (including
  2257. GGUF `tensor_shape`-aware `.img_mlp.gate_layer` / `.proj` slices).
  2258. 3. `torch.nn.functional.rms_norm` and `layer_norm` automatically adapt integer-multiple
  2259. multi-layer conditioning embeddings (`4096 <-> 53248 = 13 * 4096`).
  2260. """
  2261. install_dml_fp64_scalar_guards()
  2262.  
  2263. def _pure_fp32_rms_norm(
  2264. x: torch.Tensor,
  2265. normalized_shape: Any,
  2266. weight: Optional[torch.Tensor] = None,
  2267. eps: Optional[float] = None,
  2268. ) -> torch.Tensor:
  2269. ndim_norm = len(normalized_shape) if isinstance(normalized_shape, (tuple, list, torch.Size)) else 1
  2270. dims = tuple(range(-ndim_norm, 0))
  2271. eps_val = float(eps) if eps is not None else 1e-6
  2272. x_f32 = x.to(dtype=torch.float32)
  2273. ms = (x_f32 * x_f32).mean(dim=dims, keepdim=True)
  2274. normed = (x_f32 / torch.sqrt(ms + eps_val)).to(dtype=x.dtype)
  2275. if weight is not None:
  2276. normed = normed * safe_to_device(weight, device=x.device, dtype=x.dtype)
  2277. return normed
  2278.  
  2279. # 1. Install RMSNorm / LayerNorm integer-multiple conditioning width adapter + DirectML fallbacks
  2280. # Never overwrite hardened `_omni_dml_safe` wrappers installed by `LoRATrainingPipeline`.
  2281. try:
  2282. if hasattr(F, "rms_norm") and not getattr(F.rms_norm, "_omni_dml_safe", False):
  2283. orig_f_rms_norm = getattr(F, "_omni_orig_rms_norm", F.rms_norm)
  2284. setattr(F, "_omni_orig_rms_norm", orig_f_rms_norm)
  2285.  
  2286. def _omni_f_rms_norm(
  2287. input: torch.Tensor,
  2288. normalized_shape: List[int],
  2289. weight: Optional[torch.Tensor] = None,
  2290. eps: Optional[float] = None,
  2291. ) -> torch.Tensor:
  2292. adapted = _adapt_norm_input_last_dim(input, normalized_shape)
  2293. if getattr(adapted.device, "type", "cpu") in ("privateuseone", "dml"):
  2294. return _pure_fp32_rms_norm(adapted, normalized_shape, weight=weight, eps=eps)
  2295. try:
  2296. return orig_f_rms_norm(adapted, normalized_shape, weight=weight, eps=eps)
  2297. except (RuntimeError, NotImplementedError):
  2298. return _pure_fp32_rms_norm(adapted, normalized_shape, weight=weight, eps=eps)
  2299.  
  2300. F.rms_norm = _omni_f_rms_norm
  2301.  
  2302. if hasattr(torch, "rms_norm") and not getattr(torch.rms_norm, "_omni_dml_safe", False):
  2303. orig_t_rms_norm = getattr(torch, "_omni_orig_rms_norm", torch.rms_norm)
  2304. setattr(torch, "_omni_orig_rms_norm", orig_t_rms_norm)
  2305.  
  2306. def _omni_t_rms_norm(
  2307. input: torch.Tensor,
  2308. normalized_shape: Any,
  2309. weight: Optional[torch.Tensor] = None,
  2310. eps: Optional[float] = None,
  2311. ) -> torch.Tensor:
  2312. adapted = _adapt_norm_input_last_dim(input, normalized_shape)
  2313. if getattr(adapted.device, "type", "cpu") in ("privateuseone", "dml"):
  2314. return _pure_fp32_rms_norm(adapted, normalized_shape, weight=weight, eps=eps)
  2315. try:
  2316. return orig_t_rms_norm(adapted, normalized_shape, weight, eps)
  2317. except (RuntimeError, NotImplementedError):
  2318. return _pure_fp32_rms_norm(adapted, normalized_shape, weight=weight, eps=eps)
  2319.  
  2320. torch.rms_norm = _omni_t_rms_norm # type: ignore[assignment]
  2321.  
  2322. if hasattr(F, "pixel_unshuffle") and not getattr(F.pixel_unshuffle, "_omni_dml_safe", False):
  2323. orig_pixel_unshuffle = getattr(F, "_omni_orig_pixel_unshuffle", F.pixel_unshuffle)
  2324. setattr(F, "_omni_orig_pixel_unshuffle", orig_pixel_unshuffle)
  2325.  
  2326. def _omni_pixel_unshuffle_5d(tensor: torch.Tensor, downscale_factor: int) -> torch.Tensor:
  2327. ctx = (
  2328. torch.inference_mode(False)
  2329. if torch.is_inference_mode_enabled()
  2330. else contextlib.nullcontext()
  2331. )
  2332. with ctx:
  2333. r = int(downscale_factor)
  2334. b, c, h, w = tensor.shape
  2335. if is_inference_tensor(tensor) or not tensor.is_contiguous() or tensor.storage_offset() != 0:
  2336. tensor = tensor.clone()
  2337. # Merge (B * C) so intermediate tensor is 5D (within DirectML's 5D tensor descriptor limit), never 6D
  2338. x_5d = tensor.reshape(b * c, h // r, r, w // r, r).permute(0, 2, 4, 1, 3).contiguous()
  2339. return x_5d.reshape(b, c * r * r, h // r, w // r)
  2340.  
  2341. def _omni_pixel_unshuffle(input: torch.Tensor, downscale_factor: int) -> torch.Tensor:
  2342. if (
  2343. isinstance(input, torch.Tensor)
  2344. and getattr(input.device, "type", "cpu") in ("privateuseone", "dml")
  2345. and input.ndim == 4
  2346. ):
  2347. return _omni_pixel_unshuffle_5d(input, downscale_factor)
  2348. try:
  2349. return orig_pixel_unshuffle(input, downscale_factor)
  2350. except (RuntimeError, NotImplementedError):
  2351. if isinstance(input, torch.Tensor) and input.ndim == 4:
  2352. return _omni_pixel_unshuffle_5d(input, downscale_factor)
  2353. raise
  2354.  
  2355. F.pixel_unshuffle = _omni_pixel_unshuffle
  2356.  
  2357. if hasattr(F, "pixel_shuffle") and not getattr(F.pixel_shuffle, "_omni_dml_safe", False):
  2358. orig_pixel_shuffle = getattr(F, "_omni_orig_pixel_shuffle", F.pixel_shuffle)
  2359. setattr(F, "_omni_orig_pixel_shuffle", orig_pixel_shuffle)
  2360.  
  2361. def _omni_pixel_shuffle_5d(tensor: torch.Tensor, upscale_factor: int) -> torch.Tensor:
  2362. ctx = (
  2363. torch.inference_mode(False)
  2364. if torch.is_inference_mode_enabled()
  2365. else contextlib.nullcontext()
  2366. )
  2367. with ctx:
  2368. r = int(upscale_factor)
  2369. b, c_in, h, w = tensor.shape
  2370. c_out = c_in // (r * r)
  2371. if is_inference_tensor(tensor) or not tensor.is_contiguous() or tensor.storage_offset() != 0:
  2372. tensor = tensor.clone()
  2373. # Merge (B * C_out) so intermediate tensor is 5D (within DirectML's 5D tensor descriptor limit), never 6D
  2374. x_5d = tensor.reshape(b * c_out, r, r, h, w).permute(0, 3, 1, 4, 2).contiguous()
  2375. return x_5d.reshape(b, c_out, h * r, w * r)
  2376.  
  2377. def _omni_pixel_shuffle(input: torch.Tensor, upscale_factor: int) -> torch.Tensor:
  2378. if (
  2379. isinstance(input, torch.Tensor)
  2380. and getattr(input.device, "type", "cpu") in ("privateuseone", "dml")
  2381. and input.ndim == 4
  2382. ):
  2383. return _omni_pixel_shuffle_5d(input, upscale_factor)
  2384. try:
  2385. return orig_pixel_shuffle(input, upscale_factor)
  2386. except (RuntimeError, NotImplementedError):
  2387. if isinstance(input, torch.Tensor) and input.ndim == 4:
  2388. return _omni_pixel_shuffle_5d(input, upscale_factor)
  2389. raise
  2390.  
  2391. F.pixel_shuffle = _omni_pixel_shuffle
  2392.  
  2393. if hasattr(F, "conv3d") and not getattr(F.conv3d, "_omni_dml_safe", False):
  2394. orig_conv3d = getattr(F, "_omni_orig_conv3d", F.conv3d)
  2395. setattr(F, "_omni_orig_conv3d", orig_conv3d)
  2396.  
  2397. def _omni_conv3d(
  2398. input: torch.Tensor,
  2399. weight: torch.Tensor,
  2400. bias: Optional[torch.Tensor] = None,
  2401. stride: Any = 1,
  2402. padding: Any = 0,
  2403. dilation: Any = 1,
  2404. groups: int = 1,
  2405. ) -> torch.Tensor:
  2406. if (
  2407. isinstance(input, torch.Tensor)
  2408. and getattr(input.device, "type", "cpu") in ("privateuseone", "dml")
  2409. and input.ndim == 5
  2410. and isinstance(weight, torch.Tensor)
  2411. and weight.ndim == 5
  2412. and isinstance(padding, (int, tuple, list))
  2413. ):
  2414. ctx = (
  2415. torch.inference_mode(False)
  2416. if torch.is_inference_mode_enabled()
  2417. else contextlib.nullcontext()
  2418. )
  2419. with ctx:
  2420. if is_inference_tensor(input) or not input.is_contiguous() or input.storage_offset() != 0:
  2421. input = input.clone()
  2422. if weight.device != input.device or weight.dtype != input.dtype:
  2423. weight = safe_to_device(weight, device=input.device, dtype=input.dtype)
  2424. if is_inference_tensor(weight) or not weight.is_contiguous() or weight.storage_offset() != 0:
  2425. weight = weight.clone()
  2426. if isinstance(bias, torch.Tensor):
  2427. if bias.device != input.device or bias.dtype != input.dtype:
  2428. bias = safe_to_device(bias, device=input.device, dtype=input.dtype)
  2429. if is_inference_tensor(bias) or not bias.is_contiguous() or bias.storage_offset() != 0:
  2430. bias = bias.clone()
  2431. s_tup = (stride, stride, stride) if isinstance(stride, int) else tuple(stride)
  2432. p_tup = (padding, padding, padding) if isinstance(padding, int) else tuple(padding)
  2433. d_tup = (dilation, dilation, dilation) if isinstance(dilation, int) else tuple(dilation)
  2434. s_t, s_h, s_w = int(s_tup[0]), int(s_tup[1]), int(s_tup[2])
  2435. p_t, p_h, p_w = int(p_tup[0]), int(p_tup[1]), int(p_tup[2])
  2436. d_t, d_h, d_w = int(d_tup[0]), int(d_tup[1]), int(d_tup[2])
  2437. k_t = int(weight.shape[2])
  2438. b, c, t_len, h, w = input.shape
  2439. if k_t == 1 and s_t == 1 and p_t == 0:
  2440. x_2d = input.permute(0, 2, 1, 3, 4).contiguous().reshape(b * t_len, c, h, w)
  2441. w_2d = weight.squeeze(2).clone()
  2442. out_2d = F.conv2d(
  2443. x_2d,
  2444. w_2d,
  2445. bias=bias,
  2446. stride=(s_h, s_w),
  2447. padding=(p_h, p_w),
  2448. dilation=(d_h, d_w),
  2449. groups=groups,
  2450. )
  2451. _, out_c, out_h, out_w = out_2d.shape
  2452. return out_2d.reshape(b, t_len, out_c, out_h, out_w).permute(0, 2, 1, 3, 4).contiguous()
  2453. if p_t > 0:
  2454. input = F.pad(input, (0, 0, 0, 0, p_t, p_t))
  2455. t_padded = int(input.shape[2])
  2456. eff_k_t = (k_t - 1) * d_t + 1
  2457. t_out_len = max(1, (t_padded - eff_k_t) // s_t + 1)
  2458. frames: List[torch.Tensor] = []
  2459. for t_idx in range(t_out_len):
  2460. t_start = t_idx * s_t
  2461. acc: Optional[torch.Tensor] = None
  2462. for kt_idx in range(k_t):
  2463. x_slice = input[:, :, t_start + kt_idx * d_t, :, :].clone()
  2464. w_slice = weight[:, :, kt_idx, :, :].clone()
  2465. conv_step = F.conv2d(
  2466. x_slice,
  2467. w_slice,
  2468. bias=bias if kt_idx == 0 else None,
  2469. stride=(s_h, s_w),
  2470. padding=(p_h, p_w),
  2471. dilation=(d_h, d_w),
  2472. groups=groups,
  2473. )
  2474. acc = conv_step if acc is None else (acc + conv_step)
  2475. assert acc is not None
  2476. frames.append(acc.unsqueeze(2))
  2477. return torch.cat(frames, dim=2)
  2478. return orig_conv3d(input, weight, bias, stride, padding, dilation, groups)
  2479.  
  2480. F.conv3d = _omni_conv3d
  2481. except Exception:
  2482. pass
  2483.  
  2484. # 2. Install universal `model_lora_keys_unet` hook (always refreshes to latest implementation)
  2485. try:
  2486. import comfy.lora # type: ignore
  2487.  
  2488. if hasattr(comfy.lora, "model_lora_keys_unet"):
  2489. _orig_model_lora_keys_unet = getattr(
  2490. comfy.lora,
  2491. "_omni_orig_model_lora_keys_unet",
  2492. comfy.lora.model_lora_keys_unet,
  2493. )
  2494. setattr(comfy.lora, "_omni_orig_model_lora_keys_unet", _orig_model_lora_keys_unet)
  2495.  
  2496. def _omni_model_lora_keys_unet(
  2497. model: Any,
  2498. key_map: Optional[Dict[str, Any]] = None,
  2499. ) -> Dict[str, Any]:
  2500. if key_map is None:
  2501. key_map = {}
  2502.  
  2503. res_map = _orig_model_lora_keys_unet(model, key_map)
  2504. try:
  2505. # Strip any `.base_layer` artifact keys/values if model has injected LoRA layers
  2506. clean_map: Dict[str, Any] = {}
  2507. for k, v in res_map.items():
  2508. ck = k.replace(".base_layer", "")
  2509. if isinstance(v, tuple):
  2510. cv = (v[0].replace(".base_layer.weight", ".weight") if isinstance(v[0], str) else v[0], v[1])
  2511. elif isinstance(v, str):
  2512. cv = v.replace(".base_layer.weight", ".weight")
  2513. else:
  2514. cv = v
  2515. clean_map[ck] = cv
  2516. clean_map[k] = v
  2517. res_map = clean_map
  2518.  
  2519. sd = model.state_dict() if hasattr(model, "state_dict") and callable(model.state_dict) else {}
  2520.  
  2521. # Ensure every `.weight` in `model.state_dict()` (including GGUF 1D packed weights)
  2522. # AND fused `.img_mlp.gate_up` layers have bidirectional `<module>` and
  2523. # `diffusion_model.<module>` entries in `res_map`.
  2524. for raw_k, w_tensor in sd.items():
  2525. if not isinstance(raw_k, str):
  2526. continue
  2527. clean_k = raw_k.replace(".base_layer.weight", ".weight")
  2528. if not clean_k.endswith(".weight"):
  2529. continue
  2530. short_mod = clean_k.removeprefix("diffusion_model.")[: -len(".weight")]
  2531. full_mod = f"diffusion_model.{short_mod}"
  2532. canonical_w = clean_k if clean_k.startswith("diffusion_model.") else f"diffusion_model.{clean_k}"
  2533. res_map.setdefault(short_mod, canonical_w)
  2534. res_map.setdefault(full_mod, canonical_w)
  2535.  
  2536. if clean_k.endswith(".img_mlp.gate_up.weight"):
  2537. t_shape = getattr(w_tensor, "tensor_shape", getattr(w_tensor, "orig_shape", None))
  2538. if isinstance(t_shape, (tuple, list, torch.Size)) and len(t_shape) >= 2:
  2539. out_f = int(t_shape[0])
  2540. elif isinstance(w_tensor, torch.Tensor) and w_tensor.ndim >= 2:
  2541. out_f = int(w_tensor.shape[0])
  2542. else:
  2543. continue
  2544. if out_f > 0 and out_f % 2 == 0:
  2545. half = out_f // 2
  2546. short_base = clean_k.removeprefix("diffusion_model.")[: -len(".gate_up.weight")]
  2547. res_map[f"{short_base}.gate_layer"] = (canonical_w, (0, 0, half))
  2548. res_map[f"diffusion_model.{short_base}.gate_layer"] = (canonical_w, (0, 0, half))
  2549. res_map[f"{short_base}.proj"] = (canonical_w, (0, half, half))
  2550. res_map[f"diffusion_model.{short_base}.proj"] = (canonical_w, (0, half, half))
  2551.  
  2552. # Register bidirectional `<module>` <-> `diffusion_model.<module>` aliases for all entries
  2553. for k, v in list(res_map.items()):
  2554. if isinstance(k, str) and not k.startswith("lora_"):
  2555. short_k = k[len("diffusion_model.") :] if k.startswith("diffusion_model.") else k
  2556. full_k = f"diffusion_model.{short_k}"
  2557. res_map.setdefault(short_k, v)
  2558. res_map.setdefault(full_k, v)
  2559. raw_k = v[0] if isinstance(v, tuple) and len(v) > 0 else v
  2560. if isinstance(raw_k, str) and raw_k.startswith("diffusion_model.") and raw_k.endswith(".weight"):
  2561. short_w = raw_k[len("diffusion_model.") : -len(".weight")]
  2562. full_w = raw_k[: -len(".weight")]
  2563. res_map.setdefault(short_w, raw_k)
  2564. res_map.setdefault(full_w, raw_k)
  2565. except Exception:
  2566. pass
  2567. return res_map
  2568.  
  2569. comfy.lora.model_lora_keys_unet = _omni_model_lora_keys_unet
  2570. comfy.lora._omni_lora_keys_patched = True
  2571.  
  2572. try:
  2573. import comfy.sd # type: ignore
  2574.  
  2575. if hasattr(comfy.sd, "model_lora_keys_unet"):
  2576. comfy.sd.model_lora_keys_unet = _omni_model_lora_keys_unet
  2577. except Exception:
  2578. pass
  2579. except Exception:
  2580. pass
  2581.  
  2582. # 3. Guard `comfy_aimdo.malloc_graph` and `comfy.model_prefetch` so ComfyUI's inference-only
  2583. # C memory graph compiler (`control.lib.malloc_graph_pop`) never runs or raises
  2584. # `RuntimeError: aimdo memory compile error` (`rogues: N`) when autograd saves activations during training.
  2585. def _is_omni_training_active() -> bool:
  2586. if torch.is_grad_enabled():
  2587. return True
  2588. mm_mod = sys.modules.get("comfy.model_management")
  2589. if mm_mod is not None and bool(getattr(mm_mod, "in_training", False)):
  2590. return True
  2591. return False
  2592.  
  2593. def _patch_malloc_graph_obj(mg_target: Any) -> None:
  2594. if mg_target is None:
  2595. return
  2596. is_cls = isinstance(mg_target, type)
  2597. if not is_cls:
  2598. _patch_malloc_graph_obj(type(mg_target))
  2599. target_dict = getattr(mg_target, "__dict__", {})
  2600. if isinstance(target_dict, dict) and target_dict.get("_omni_aimdo_patched", False):
  2601. return
  2602. try:
  2603. setattr(mg_target, "_omni_aimdo_patched", True)
  2604. except Exception:
  2605. return
  2606.  
  2607. if hasattr(mg_target, "_call"):
  2608. orig_call = target_dict.get("_omni_orig_call") if isinstance(target_dict, dict) else None
  2609. if orig_call is None:
  2610. orig_call = getattr(mg_target, "_call")
  2611. try:
  2612. setattr(mg_target, "_omni_orig_call", orig_call)
  2613.  
  2614. def _safe_aimdo_call(*args: Any, **kwargs: Any) -> Any:
  2615. if _is_omni_training_active():
  2616. return 2
  2617. try:
  2618. return orig_call(*args, **kwargs)
  2619. except RuntimeError as exc:
  2620. if "aimdo" in str(exc).lower() or "compile error" in str(exc).lower():
  2621. return 2
  2622. raise
  2623.  
  2624. setattr(mg_target, "_call", _safe_aimdo_call)
  2625. except Exception:
  2626. pass
  2627.  
  2628. for method_name in ("iterate", "push", "pop", "begin", "end", "pause", "resume"):
  2629. if not hasattr(mg_target, method_name):
  2630. continue
  2631. orig_m = target_dict.get(f"_omni_orig_{method_name}") if isinstance(target_dict, dict) else None
  2632. if orig_m is None:
  2633. orig_m = getattr(mg_target, method_name)
  2634. try:
  2635. setattr(mg_target, f"_omni_orig_{method_name}", orig_m)
  2636.  
  2637. def _make_safe_mg_method(orig_fn: Any) -> Any:
  2638. def _wrapped(*a: Any, **kw: Any) -> Any:
  2639. if _is_omni_training_active():
  2640. return False
  2641. try:
  2642. return orig_fn(*a, **kw)
  2643. except RuntimeError as exc:
  2644. if "aimdo" in str(exc).lower() or "compile error" in str(exc).lower():
  2645. return False
  2646. raise
  2647.  
  2648. return _wrapped
  2649.  
  2650. setattr(mg_target, method_name, _make_safe_mg_method(orig_m))
  2651. except Exception:
  2652. pass
  2653.  
  2654. _aimdo_mg = sys.modules.get("comfy_aimdo.malloc_graph")
  2655. if _aimdo_mg is None:
  2656. try:
  2657. import comfy_aimdo.malloc_graph as _aimdo_mg # type: ignore
  2658. except Exception:
  2659. _aimdo_mg = None
  2660. if _aimdo_mg is not None:
  2661. _patch_malloc_graph_obj(getattr(_aimdo_mg, "MallocGraph", None))
  2662. _patch_malloc_graph_obj(getattr(_aimdo_mg, "malloc_graph", None))
  2663.  
  2664. _mp = sys.modules.get("comfy.model_prefetch")
  2665. if _mp is None:
  2666. try:
  2667. import comfy.model_prefetch as _mp # type: ignore
  2668. except Exception:
  2669. _mp = None
  2670.  
  2671. if _mp is not None:
  2672. mg_inst = getattr(_mp, "malloc_graph", None)
  2673. if mg_inst is not None:
  2674. _patch_malloc_graph_obj(type(mg_inst))
  2675. _patch_malloc_graph_obj(mg_inst)
  2676.  
  2677. if hasattr(_mp, "malloc_graph_enabled") and not getattr(_mp.malloc_graph_enabled, "_omni_patched", False):
  2678. _orig_mg_enabled = getattr(_mp, "_omni_orig_malloc_graph_enabled", _mp.malloc_graph_enabled)
  2679. setattr(_mp, "_omni_orig_malloc_graph_enabled", _orig_mg_enabled)
  2680.  
  2681. def _omni_malloc_graph_enabled(*args: Any, **kwargs: Any) -> bool:
  2682. if _is_omni_training_active():
  2683. return False
  2684. return bool(_orig_mg_enabled(*args, **kwargs))
  2685.  
  2686. setattr(_omni_malloc_graph_enabled, "_omni_patched", True)
  2687. _mp.malloc_graph_enabled = _omni_malloc_graph_enabled
  2688.  
  2689. for _mp_fn_name in ("malloc_graph_begin", "malloc_graph_end"):
  2690. if hasattr(_mp, _mp_fn_name) and not getattr(getattr(_mp, _mp_fn_name), "_omni_patched", False):
  2691. _orig_mp_fn = getattr(_mp, f"_omni_orig_{_mp_fn_name}", getattr(_mp, _mp_fn_name))
  2692. setattr(_mp, f"_omni_orig_{_mp_fn_name}", _orig_mp_fn)
  2693.  
  2694. def _make_mp_noop(orig_f: Any) -> Any:
  2695. def _wrapped_mp(*args: Any, **kwargs: Any) -> Any:
  2696. if _is_omni_training_active():
  2697. return None
  2698. try:
  2699. return orig_f(*args, **kwargs)
  2700. except RuntimeError as exc:
  2701. if "aimdo" in str(exc).lower() or "compile error" in str(exc).lower():
  2702. return None
  2703. raise
  2704.  
  2705. setattr(_wrapped_mp, "_omni_patched", True)
  2706. return _wrapped_mp
  2707.  
  2708. setattr(_mp, _mp_fn_name, _make_mp_noop(_orig_mp_fn))
  2709.  
  2710. if hasattr(_mp, "prefetch_queue_pop") and not getattr(_mp.prefetch_queue_pop, "_omni_patched", False):
  2711. _orig_pq_pop = getattr(_mp, "_omni_orig_prefetch_queue_pop", _mp.prefetch_queue_pop)
  2712. setattr(_mp, "_omni_orig_prefetch_queue_pop", _orig_pq_pop)
  2713.  
  2714. def _omni_prefetch_queue_pop(*args: Any, **kwargs: Any) -> Any:
  2715. if _is_omni_training_active():
  2716. if "malloc_scope" in kwargs or "enable_graph" in kwargs:
  2717. kwargs = dict(kwargs)
  2718. if "malloc_scope" in kwargs:
  2719. kwargs["malloc_scope"] = None
  2720. if "enable_graph" in kwargs:
  2721. kwargs["enable_graph"] = False
  2722. try:
  2723. return _orig_pq_pop(*args, **kwargs)
  2724. except RuntimeError as exc:
  2725. if "aimdo" in str(exc).lower() or "compile error" in str(exc).lower():
  2726. return None
  2727. raise
  2728.  
  2729. setattr(_omni_prefetch_queue_pop, "_omni_patched", True)
  2730. _mp.prefetch_queue_pop = _omni_prefetch_queue_pop
  2731.  
  2732. # 4. Install `comfy.model_base.BaseModel.extra_conds` context width adapter so KSampler /
  2733. # downstream ComfyUI sampling automatically adapts `cross_attn` / `c_crossattn` width when needed.
  2734. try:
  2735. import comfy.model_base as _mb # type: ignore
  2736.  
  2737. base_cls = getattr(_mb, "BaseModel", None)
  2738. if base_cls is not None and hasattr(base_cls, "extra_conds") and not getattr(base_cls, "_omni_extra_conds_patched", False):
  2739. _orig_extra_conds = getattr(base_cls, "_omni_orig_extra_conds", base_cls.extra_conds)
  2740. setattr(base_cls, "_omni_orig_extra_conds", _orig_extra_conds)
  2741.  
  2742. def _omni_extra_conds(self: Any, **kwargs: Any) -> Dict[str, Any]:
  2743. try:
  2744. dm = getattr(self, "diffusion_model", None)
  2745. mc = getattr(self, "model_config", None)
  2746. ucfg = getattr(mc, "unet_config", None) if mc is not None else None
  2747. exp_dim = _infer_dm_expected_context_dim(dm, ucfg if isinstance(ucfg, dict) else None)
  2748. if exp_dim is not None and exp_dim > 0:
  2749. for ck in ("cross_attn", "c_crossattn"):
  2750. ct = kwargs.get(ck)
  2751. if isinstance(ct, torch.Tensor) and ct.ndim >= 2 and int(ct.shape[-1]) != exp_dim:
  2752. kwargs = dict(kwargs)
  2753. kwargs[ck] = _adapt_context_width(ct, exp_dim, model_name=type(dm).__name__ if dm is not None else None)
  2754. except Exception:
  2755. pass
  2756. return _orig_extra_conds(self, **kwargs)
  2757.  
  2758. setattr(base_cls, "extra_conds", _omni_extra_conds)
  2759. setattr(base_cls, "_omni_extra_conds_patched", True)
  2760. except Exception:
  2761. pass
  2762.  
  2763. # 5. Normalize Qwen3.5 / MOSS-Image text encoder state_dicts in `comfy.sd.detect_te_model` and
  2764. # `comfy.sd.load_text_encoder_state_dicts` when checkpoints use `model.layers.0.linear_attn.A_log`,
  2765. # `layers.0.linear_attn.A_log`, or `(text_encoders.)qwen35_*.transformer.model.layers.0.linear_attn.A_log`
  2766. # instead of `model.language_model.layers.0.linear_attn.A_log`, preventing fallback to SD1ClipModel (768-dim).
  2767. try:
  2768. import comfy.sd as _csd # type: ignore
  2769.  
  2770. def _normalize_qwen35_sd_in_place(sd: Any) -> Any:
  2771. if not isinstance(sd, dict) or "model.language_model.layers.0.linear_attn.A_log" in sd:
  2772. return sd
  2773. target_suffix = "layers.0.linear_attn.A_log"
  2774. matched_prefix: Optional[str] = None
  2775. if "model.layers.0.linear_attn.A_log" in sd:
  2776. matched_prefix = "model."
  2777. elif "layers.0.linear_attn.A_log" in sd:
  2778. matched_prefix = ""
  2779. else:
  2780. for k in sd.keys():
  2781. if isinstance(k, str) and k.endswith(target_suffix):
  2782. matched_prefix = k[: -len(target_suffix)]
  2783. break
  2784. if matched_prefix is None:
  2785. return sd
  2786. norm_key = f"{matched_prefix}layers.0.input_layernorm.weight"
  2787. if norm_key not in sd:
  2788. return sd
  2789. plen = len(matched_prefix)
  2790. remapped: Dict[str, Any] = {}
  2791. for k, v in sd.items():
  2792. if isinstance(k, str) and k.startswith(matched_prefix):
  2793. sub = k[plen:]
  2794. if sub.startswith(("layers.", "embed_tokens.", "norm.")):
  2795. remapped[f"model.language_model.{sub}"] = v
  2796. else:
  2797. remapped[k] = v
  2798. else:
  2799. remapped[k] = v
  2800. sd.clear()
  2801. sd.update(remapped)
  2802. return sd
  2803.  
  2804. if hasattr(_csd, "detect_te_model") and not getattr(_csd.detect_te_model, "_omni_patched", False):
  2805. _orig_detect_te = getattr(_csd, "_omni_orig_detect_te_model", _csd.detect_te_model)
  2806. setattr(_csd, "_omni_orig_detect_te_model", _orig_detect_te)
  2807.  
  2808. def _omni_detect_te_model(sd: Any) -> Any:
  2809. _normalize_qwen35_sd_in_place(sd)
  2810. return _orig_detect_te(sd)
  2811.  
  2812. setattr(_omni_detect_te_model, "_omni_patched", True)
  2813. _csd.detect_te_model = _omni_detect_te_model
  2814.  
  2815. if hasattr(_csd, "load_text_encoder_state_dicts") and not getattr(_csd.load_text_encoder_state_dicts, "_omni_patched", False):
  2816. _orig_load_te_sds = getattr(_csd, "_omni_orig_load_text_encoder_state_dicts", _csd.load_text_encoder_state_dicts)
  2817. setattr(_csd, "_omni_orig_load_text_encoder_state_dicts", _orig_load_te_sds)
  2818.  
  2819. def _omni_load_text_encoder_state_dicts(state_dicts: Any = [], *args: Any, **kwargs: Any) -> Any:
  2820. if isinstance(state_dicts, (list, tuple)):
  2821. for sd_item in state_dicts:
  2822. _normalize_qwen35_sd_in_place(sd_item)
  2823. return _orig_load_te_sds(state_dicts, *args, **kwargs)
  2824.  
  2825. setattr(_omni_load_text_encoder_state_dicts, "_omni_patched", True)
  2826. _csd.load_text_encoder_state_dicts = _omni_load_text_encoder_state_dicts
  2827. except Exception:
  2828. pass
  2829.  
  2830. # 6. Guard `comfy.weight_adapter` LoRAAdapter.calculate_weight so legacy 2D `[rank, in_c]`
  2831. # conv LoRA weights loaded onto 3D/4D/5D convolution layers (`[out_c, in_c, kH, kW]`) are
  2832. # automatically upgraded at the center spatial tap instead of failing `.reshape(weight.shape)`.
  2833. try:
  2834. import comfy.weight_adapter as _cwa # type: ignore
  2835.  
  2836. adapter_classes: List[Any] = []
  2837. if hasattr(_cwa, "LoRAAdapter"):
  2838. adapter_classes.append(getattr(_cwa, "LoRAAdapter"))
  2839. if hasattr(_cwa, "adapters") and isinstance(_cwa.adapters, (list, tuple)):
  2840. for ad_cls in _cwa.adapters:
  2841. if ad_cls not in adapter_classes and getattr(ad_cls, "name", "") == "lora":
  2842. adapter_classes.append(ad_cls)
  2843.  
  2844. for lora_ad_cls in adapter_classes:
  2845. if hasattr(lora_ad_cls, "calculate_weight") and not getattr(
  2846. lora_ad_cls, "_omni_calc_weight_patched", False
  2847. ):
  2848. _orig_ad_calc = getattr(lora_ad_cls, "_omni_orig_calculate_weight", lora_ad_cls.calculate_weight)
  2849. setattr(lora_ad_cls, "_omni_orig_calculate_weight", _orig_ad_calc)
  2850.  
  2851. def _make_safe_lora_calc(orig_fn: Any) -> Any:
  2852. def _omni_ad_calculate_weight(
  2853. self: Any,
  2854. weight: torch.Tensor,
  2855. key: str,
  2856. *args: Any,
  2857. **kwargs: Any,
  2858. ) -> Any:
  2859. try:
  2860. w_tuple = getattr(self, "weights", None)
  2861. if (
  2862. isinstance(weight, torch.Tensor)
  2863. and weight.ndim >= 3
  2864. and isinstance(w_tuple, (tuple, list))
  2865. and len(w_tuple) >= 2
  2866. ):
  2867. up_t, down_t = w_tuple[0], w_tuple[1]
  2868. if (
  2869. isinstance(up_t, torch.Tensor)
  2870. and isinstance(down_t, torch.Tensor)
  2871. and down_t.ndim == 2
  2872. and up_t.shape[0] == weight.shape[0]
  2873. and down_t.shape[1] == weight.shape[1]
  2874. and weight.numel() != up_t.shape[0] * down_t.shape[1]
  2875. ):
  2876. padded_down = torch.zeros(
  2877. (down_t.shape[0], weight.shape[1], *weight.shape[2:]),
  2878. dtype=down_t.dtype,
  2879. device=down_t.device,
  2880. )
  2881. center_idx = (slice(None), slice(None)) + tuple(
  2882. k // 2 for k in weight.shape[2:]
  2883. )
  2884. padded_down[center_idx] = down_t
  2885. reshaped_up = up_t.reshape(
  2886. up_t.shape[0], up_t.shape[1], *([1] * (weight.ndim - 2))
  2887. )
  2888. new_weights = list(w_tuple)
  2889. new_weights[0] = reshaped_up
  2890. new_weights[1] = padded_down
  2891. self.weights = tuple(new_weights) if isinstance(w_tuple, tuple) else new_weights
  2892. except Exception:
  2893. pass
  2894. return orig_fn(self, weight, key, *args, **kwargs)
  2895.  
  2896. return _omni_ad_calculate_weight
  2897.  
  2898. setattr(lora_ad_cls, "calculate_weight", _make_safe_lora_calc(_orig_ad_calc))
  2899. setattr(lora_ad_cls, "_omni_calc_weight_patched", True)
  2900. except Exception:
  2901. pass
  2902.  
  2903. # 7. Guard inference-only ComfyUI attention backends (`attention_comfy_kitchen_int8`,
  2904. # `attention_comfy_kitchen_sol`, `attention_sage`, `attention3_sage`), pre-loaded `ComfyAttention`
  2905. # instances, and direct `comfy_kitchen` / `comfy.quant_ops.ck` non-autograd kernels (`int8_attention`,
  2906. # `prequantize_int8_attention`, `sol_attn`, `rms_rope`, `rms_rope1`, `rms_rope_split_half`,
  2907. # `apply_rope`, `apply_rope1`, `apply_rope_split_half`, `adaln`, `rms_adaln`) during training.
  2908. def _sdpa_4d_fallback(
  2909. q: torch.Tensor,
  2910. k: torch.Tensor,
  2911. v: torch.Tensor,
  2912. scale: Optional[float] = None,
  2913. attn_mask: Optional[torch.Tensor] = None,
  2914. ) -> torch.Tensor:
  2915. if attn_mask is not None:
  2916. if attn_mask.ndim == 2:
  2917. attn_mask = attn_mask.unsqueeze(0)
  2918. if attn_mask.ndim == 3:
  2919. attn_mask = attn_mask.unsqueeze(1)
  2920. sdpa_kw: Dict[str, Any] = {}
  2921. if scale is not None:
  2922. sdpa_kw["scale"] = scale
  2923. if k.ndim == 4 and q.ndim == 4 and k.shape[1] != q.shape[1]:
  2924. rep_k = max(1, int(q.shape[1]) // max(1, int(k.shape[1])))
  2925. rep_v = max(1, int(q.shape[1]) // max(1, int(v.shape[1])))
  2926. k = k.repeat_interleave(rep_k, dim=1)
  2927. v = v.repeat_interleave(rep_v, dim=1)
  2928. return F.scaled_dot_product_attention(
  2929. q,
  2930. k,
  2931. v,
  2932. attn_mask=attn_mask,
  2933. dropout_p=0.0,
  2934. is_causal=False,
  2935. **sdpa_kw,
  2936. )
  2937.  
  2938. def _rms_norm_t(
  2939. x_t: torch.Tensor,
  2940. w_t: Optional[torch.Tensor] = None,
  2941. eps: float = 1e-6,
  2942. ) -> torch.Tensor:
  2943. w_cast: Optional[torch.Tensor] = None
  2944. if isinstance(w_t, torch.Tensor):
  2945. w_cast = safe_to_device(w_t, device=x_t.device, dtype=x_t.dtype)
  2946. if hasattr(F, "rms_norm"):
  2947. return F.rms_norm(x_t, (int(x_t.shape[-1]),), weight=w_cast, eps=float(eps))
  2948. x_f32 = x_t.to(dtype=torch.float32)
  2949. ms = (x_f32 * x_f32).mean(dim=-1, keepdim=True)
  2950. out_t = (x_f32 * torch.rsqrt(ms + float(eps))).to(dtype=x_t.dtype)
  2951. if w_cast is not None:
  2952. out_t = out_t * w_cast
  2953. return out_t
  2954.  
  2955. def _torch_apply_rope_interleaved1(x_t: torch.Tensor, pe: torch.Tensor) -> torch.Tensor:
  2956. freqs = pe
  2957. x_ = x_t.to(dtype=freqs.dtype).reshape(*x_t.shape[:-1], -1, 1, 2)
  2958. if x_.ndim >= 4 and freqs.ndim >= 4 and x_.shape[2] != 1 and freqs.shape[2] != 1 and x_.shape[2] != freqs.shape[2]:
  2959. freqs = freqs[:, :, : x_.shape[2]]
  2960. x_out = freqs[..., 0] * x_[..., 0] + freqs[..., 1] * x_[..., 1]
  2961. return x_out.reshape(*x_t.shape).to(dtype=x_t.dtype)
  2962.  
  2963. def _torch_apply_rope_split_half1(
  2964. x_t: torch.Tensor,
  2965. pe: torch.Tensor,
  2966. rot_dim: Optional[int] = None,
  2967. ) -> torch.Tensor:
  2968. total_d = int(x_t.shape[-1])
  2969. pe_rot_d = int(pe.shape[-3]) * 2 if pe.ndim >= 3 else total_d
  2970. r_dim = int(rot_dim) if rot_dim is not None else min(total_d, pe_rot_d)
  2971. if 0 < r_dim < total_d:
  2972. head_part = x_t[..., :r_dim]
  2973. tail_part = x_t[..., r_dim:]
  2974. rot_head = _torch_apply_rope_split_half1(head_part, pe, rot_dim=r_dim)
  2975. return torch.cat((rot_head, tail_part), dim=-1)
  2976. x_ = x_t.to(dtype=pe.dtype).reshape(*x_t.shape[:-1], 2, -1).movedim(-2, -1).unsqueeze(-2)
  2977. x_out = pe[..., 0] * x_[..., 0] + pe[..., 1] * x_[..., 1]
  2978. return x_out.movedim(-1, -2).reshape(*x_t.shape).to(dtype=x_t.dtype)
  2979.  
  2980. def _torch_rms_rope_interleaved(
  2981. q: torch.Tensor,
  2982. k: torch.Tensor,
  2983. pe: torch.Tensor,
  2984. q_scale: Optional[torch.Tensor],
  2985. k_scale: Optional[torch.Tensor],
  2986. eps: float = 1e-6,
  2987. ) -> Tuple[torch.Tensor, torch.Tensor]:
  2988. q_n = _rms_norm_t(q, q_scale, eps=eps)
  2989. k_n = _rms_norm_t(k, k_scale, eps=eps)
  2990. return _torch_apply_rope_interleaved1(q_n, pe), _torch_apply_rope_interleaved1(k_n, pe)
  2991.  
  2992. def _torch_rms_rope_split_half(
  2993. q: torch.Tensor,
  2994. k: torch.Tensor,
  2995. pe: torch.Tensor,
  2996. q_scale: Optional[torch.Tensor],
  2997. k_scale: Optional[torch.Tensor],
  2998. eps: float = 1e-6,
  2999. rot_dim: Optional[int] = None,
  3000. ) -> Tuple[torch.Tensor, torch.Tensor]:
  3001. q_n = _rms_norm_t(q, q_scale, eps=eps)
  3002. k_n = _rms_norm_t(k, k_scale, eps=eps)
  3003. return (
  3004. _torch_apply_rope_split_half1(q_n, pe, rot_dim=rot_dim),
  3005. _torch_apply_rope_split_half1(k_n, pe, rot_dim=rot_dim),
  3006. )
  3007.  
  3008. try:
  3009. comfy_attn = sys.modules.get("comfy.ldm.modules.attention")
  3010. if comfy_attn is None and "comfy.ldm" in sys.modules:
  3011. try:
  3012. import comfy.ldm.modules.attention as comfy_attn # type: ignore
  3013. except Exception:
  3014. comfy_attn = None
  3015.  
  3016. if comfy_attn is not None:
  3017. import functools
  3018.  
  3019. target_attn_names = (
  3020. "attention_comfy_kitchen_int8",
  3021. "attention_comfy_kitchen_sol",
  3022. "attention_sage",
  3023. "attention3_sage",
  3024. )
  3025. replaced_map: Dict[int, Tuple[Any, Any]] = {}
  3026.  
  3027. for fn_name in target_attn_names:
  3028. cur_fn = getattr(comfy_attn, fn_name, None)
  3029. if cur_fn is None:
  3030. continue
  3031.  
  3032. orig_fn = getattr(cur_fn, "_omni_orig_attn_fn", cur_fn)
  3033. if not getattr(cur_fn, "_omni_train_attn_safe", False):
  3034. orig_container = getattr(orig_fn, "container_function", None)
  3035. if callable(orig_container) and not getattr(orig_container, "_omni_train_attn_safe", False):
  3036. def _make_safe_container(orig_c: Any) -> Any:
  3037. def _safe_container(*c_args: Any, **c_kwargs: Any) -> Any:
  3038. if _is_omni_training_active():
  3039. return _run_pytorch_sdpa_attention(*c_args, **c_kwargs)
  3040. return orig_c(*c_args, **c_kwargs)
  3041.  
  3042. setattr(_safe_container, "_omni_train_attn_safe", True)
  3043. setattr(_safe_container, "_omni_orig_attn_fn", orig_c)
  3044. return _safe_container
  3045.  
  3046. safe_c = _make_safe_container(orig_container)
  3047. try:
  3048. setattr(orig_fn, "container_function", safe_c)
  3049. except Exception:
  3050. pass
  3051.  
  3052. def _make_safe_attn_fn(orig_f: Any) -> Any:
  3053. @functools.wraps(orig_f)
  3054. def _safe_attn(*a: Any, **kw: Any) -> Any:
  3055. if _is_omni_training_active():
  3056. return _run_pytorch_sdpa_attention(*a, **kw)
  3057. return orig_f(*a, **kw)
  3058.  
  3059. setattr(_safe_attn, "_omni_train_attn_safe", True)
  3060. setattr(_safe_attn, "_omni_orig_attn_fn", orig_f)
  3061. if getattr(orig_f, "container_function", None) is not None:
  3062. setattr(_safe_attn, "container_function", getattr(orig_f, "container_function"))
  3063. return _safe_attn
  3064.  
  3065. safe_fn = _make_safe_attn_fn(orig_fn)
  3066. setattr(comfy_attn, fn_name, safe_fn)
  3067. replaced_map[id(orig_fn)] = (orig_fn, safe_fn)
  3068. else:
  3069. replaced_map[id(orig_fn)] = (orig_fn, cur_fn)
  3070.  
  3071. if replaced_map:
  3072. setattr(comfy_attn, "_omni_replaced_attn_map", replaced_map)
  3073. reg_map = getattr(comfy_attn, "REGISTERED_ATTENTION_FUNCTIONS", None)
  3074. if isinstance(reg_map, dict):
  3075. for reg_k, reg_v in list(reg_map.items()):
  3076. pair = replaced_map.get(id(reg_v))
  3077. if pair is not None:
  3078. reg_map[reg_k] = pair[1]
  3079.  
  3080. for global_attr in ("optimized_attention", "optimized_attention_masked"):
  3081. g_val = getattr(comfy_attn, global_attr, None)
  3082. pair = replaced_map.get(id(g_val))
  3083. if pair is not None:
  3084. setattr(comfy_attn, global_attr, pair[1])
  3085.  
  3086. # Rebind already-imported `from comfy.ldm.modules.attention import optimized_attention`
  3087. # references across loaded `comfy.*` submodules (e.g. ernie, mmdit, wan, qwen_image21).
  3088. for mod_name, mod_obj in list(sys.modules.items()):
  3089. if not isinstance(mod_name, str) or not mod_name.startswith("comfy.") or mod_obj is None:
  3090. continue
  3091. for attr_n in ("optimized_attention", "optimized_attention_masked"):
  3092. try:
  3093. cur_ref = getattr(mod_obj, attr_n, None)
  3094. except Exception:
  3095. continue
  3096. pair = replaced_map.get(id(cur_ref))
  3097. if pair is not None:
  3098. try:
  3099. setattr(mod_obj, attr_n, pair[1])
  3100. except Exception:
  3101. pass
  3102.  
  3103. setattr(comfy_attn, "_omni_attn_hooks_installed", True)
  3104. except Exception:
  3105. pass
  3106.  
  3107. try:
  3108. import functools as _ft
  3109.  
  3110. ck_targets: List[Any] = []
  3111. ck_mod = sys.modules.get("comfy_kitchen")
  3112. if ck_mod is not None:
  3113. ck_targets.append(ck_mod)
  3114. qops_mod = sys.modules.get("comfy.quant_ops")
  3115. if qops_mod is not None and getattr(qops_mod, "ck", None) is not None:
  3116. qops_ck = getattr(qops_mod, "ck")
  3117. if qops_ck not in ck_targets:
  3118. ck_targets.append(qops_ck)
  3119.  
  3120. for ck_obj in ck_targets:
  3121. if hasattr(ck_obj, "int8_attention") and not getattr(ck_obj.int8_attention, "_omni_train_safe", False):
  3122. _orig_ck_int8 = getattr(ck_obj, "_omni_orig_int8_attention", ck_obj.int8_attention)
  3123. setattr(ck_obj, "_omni_orig_int8_attention", _orig_ck_int8)
  3124.  
  3125. def _make_ck_int8_wrapper(orig_f: Any) -> Any:
  3126. def _safe_ck_int8(
  3127. q: torch.Tensor,
  3128. k: torch.Tensor,
  3129. v: torch.Tensor,
  3130. scale: Optional[float] = None,
  3131. attn_mask: Optional[torch.Tensor] = None,
  3132. *args: Any,
  3133. **kwargs: Any,
  3134. ) -> torch.Tensor:
  3135. if _is_omni_training_active():
  3136. return _sdpa_4d_fallback(q, k, v, scale=scale, attn_mask=attn_mask)
  3137. return orig_f(q, k, v, scale=scale, attn_mask=attn_mask, *args, **kwargs)
  3138.  
  3139. setattr(_safe_ck_int8, "_omni_train_safe", True)
  3140. return _safe_ck_int8
  3141.  
  3142. setattr(ck_obj, "int8_attention", _make_ck_int8_wrapper(_orig_ck_int8))
  3143.  
  3144. if (
  3145. hasattr(ck_obj, "prequantize_int8_attention")
  3146. and hasattr(ck_obj, "int8_attention_from_prequantized")
  3147. and not getattr(ck_obj.prequantize_int8_attention, "_omni_train_safe", False)
  3148. ):
  3149. _orig_preq = getattr(ck_obj, "_omni_orig_prequantize_int8_attention", ck_obj.prequantize_int8_attention)
  3150. _orig_from_preq = getattr(
  3151. ck_obj, "_omni_orig_int8_attention_from_prequantized", ck_obj.int8_attention_from_prequantized
  3152. )
  3153. setattr(ck_obj, "_omni_orig_prequantize_int8_attention", _orig_preq)
  3154. setattr(ck_obj, "_omni_orig_int8_attention_from_prequantized", _orig_from_preq)
  3155.  
  3156. def _make_preq_pair(orig_p: Any, orig_fp: Any) -> Tuple[Any, Any]:
  3157. def _safe_preq(
  3158. q: torch.Tensor,
  3159. k: torch.Tensor,
  3160. v: torch.Tensor,
  3161. scale: Optional[float] = None,
  3162. attn_mask: Optional[torch.Tensor] = None,
  3163. *args: Any,
  3164. **kwargs: Any,
  3165. ) -> Any:
  3166. if _is_omni_training_active():
  3167. return {"_omni_sdpa_qkv": (q, k, v, scale, attn_mask)}
  3168. return orig_p(q, k, v, scale=scale, attn_mask=attn_mask, *args, **kwargs)
  3169.  
  3170. def _safe_from_preq(quantized: Any, *args: Any, **kwargs: Any) -> torch.Tensor:
  3171. if isinstance(quantized, dict) and "_omni_sdpa_qkv" in quantized:
  3172. q, k, v, scale, attn_mask = quantized["_omni_sdpa_qkv"]
  3173. return _sdpa_4d_fallback(q, k, v, scale=scale, attn_mask=attn_mask)
  3174. return orig_fp(quantized, *args, **kwargs)
  3175.  
  3176. setattr(_safe_preq, "_omni_train_safe", True)
  3177. setattr(_safe_from_preq, "_omni_train_safe", True)
  3178. return _safe_preq, _safe_from_preq
  3179.  
  3180. safe_preq, safe_from_preq = _make_preq_pair(_orig_preq, _orig_from_preq)
  3181. setattr(ck_obj, "prequantize_int8_attention", safe_preq)
  3182. setattr(ck_obj, "int8_attention_from_prequantized", safe_from_preq)
  3183.  
  3184. if hasattr(ck_obj, "sol_attn") and not getattr(ck_obj.sol_attn, "_omni_train_safe", False):
  3185. _orig_sol = getattr(ck_obj, "_omni_orig_sol_attn", ck_obj.sol_attn)
  3186. setattr(ck_obj, "_omni_orig_sol_attn", _orig_sol)
  3187.  
  3188. def _make_sol_wrapper(orig_f: Any) -> Any:
  3189. def _safe_sol(
  3190. q: torch.Tensor,
  3191. k: torch.Tensor,
  3192. v: torch.Tensor,
  3193. tau: float = 1.0,
  3194. scale: Optional[float] = None,
  3195. *args: Any,
  3196. **kwargs: Any,
  3197. ) -> torch.Tensor:
  3198. if _is_omni_training_active():
  3199. base_scale = float(scale) if scale is not None else float(int(q.shape[-1]) ** -0.5)
  3200. eff_scale = base_scale / max(1e-6, float(tau or 1.0))
  3201. out_4d = _sdpa_4d_fallback(
  3202. q.transpose(1, 2),
  3203. k.transpose(1, 2),
  3204. v.transpose(1, 2),
  3205. scale=eff_scale,
  3206. attn_mask=None,
  3207. )
  3208. return out_4d.transpose(1, 2)
  3209. return orig_f(q, k, v, tau=tau, scale=scale, *args, **kwargs)
  3210.  
  3211. setattr(_safe_sol, "_omni_train_safe", True)
  3212. return _safe_sol
  3213.  
  3214. setattr(ck_obj, "sol_attn", _make_sol_wrapper(_orig_sol))
  3215.  
  3216. if hasattr(ck_obj, "rms_rope") and not getattr(ck_obj.rms_rope, "_omni_train_safe", False):
  3217. _orig_rms_rope = getattr(ck_obj, "_omni_orig_rms_rope", ck_obj.rms_rope)
  3218. setattr(ck_obj, "_omni_orig_rms_rope", _orig_rms_rope)
  3219.  
  3220. def _make_rms_rope_wrapper(orig_f: Any) -> Any:
  3221. def _safe_rms_rope(
  3222. q: torch.Tensor,
  3223. k: torch.Tensor,
  3224. pe: torch.Tensor,
  3225. q_scale: Optional[torch.Tensor] = None,
  3226. k_scale: Optional[torch.Tensor] = None,
  3227. eps: float = 1e-6,
  3228. *args: Any,
  3229. **kwargs: Any,
  3230. ) -> Tuple[torch.Tensor, torch.Tensor]:
  3231. if _is_omni_training_active():
  3232. eff_eps = float(kwargs.get("epsilon", eps))
  3233. return _torch_rms_rope_interleaved(q, k, pe, q_scale, k_scale, eps=eff_eps)
  3234. return orig_f(q, k, pe, q_scale, k_scale, eps, *args, **kwargs)
  3235.  
  3236. setattr(_safe_rms_rope, "_omni_train_safe", True)
  3237. return _safe_rms_rope
  3238.  
  3239. setattr(ck_obj, "rms_rope", _make_rms_rope_wrapper(_orig_rms_rope))
  3240.  
  3241. if hasattr(ck_obj, "rms_rope1") and not getattr(ck_obj.rms_rope1, "_omni_train_safe", False):
  3242. _orig_rms_rope1 = getattr(ck_obj, "_omni_orig_rms_rope1", ck_obj.rms_rope1)
  3243. setattr(ck_obj, "_omni_orig_rms_rope1", _orig_rms_rope1)
  3244.  
  3245. def _make_rms_rope1_wrapper(orig_f: Any) -> Any:
  3246. def _safe_rms_rope1(
  3247. x: torch.Tensor,
  3248. pe: torch.Tensor,
  3249. scale: Optional[torch.Tensor] = None,
  3250. eps: float = 1e-6,
  3251. *args: Any,
  3252. **kwargs: Any,
  3253. ) -> torch.Tensor:
  3254. if _is_omni_training_active():
  3255. eff_eps = float(kwargs.get("epsilon", eps))
  3256. return _torch_apply_rope_interleaved1(_rms_norm_t(x, scale, eps=eff_eps), pe)
  3257. return orig_f(x, pe, scale, eps, *args, **kwargs)
  3258.  
  3259. setattr(_safe_rms_rope1, "_omni_train_safe", True)
  3260. return _safe_rms_rope1
  3261.  
  3262. setattr(ck_obj, "rms_rope1", _make_rms_rope1_wrapper(_orig_rms_rope1))
  3263.  
  3264. for split_fn_name in ("rms_rope_split_half", "rms_rope_split_half_"):
  3265. if hasattr(ck_obj, split_fn_name) and not getattr(getattr(ck_obj, split_fn_name), "_omni_train_safe", False):
  3266. _orig_split = getattr(ck_obj, f"_omni_orig_{split_fn_name}", getattr(ck_obj, split_fn_name))
  3267. setattr(ck_obj, f"_omni_orig_{split_fn_name}", _orig_split)
  3268. is_inplace_split = split_fn_name.endswith("_")
  3269.  
  3270. def _make_rms_rope_split_wrapper(orig_f: Any, inplace_flag: bool) -> Any:
  3271. def _safe_rms_rope_split(
  3272. q: torch.Tensor,
  3273. k: torch.Tensor,
  3274. pe: torch.Tensor,
  3275. q_scale: Optional[torch.Tensor] = None,
  3276. k_scale: Optional[torch.Tensor] = None,
  3277. eps: float = 1e-6,
  3278. *args: Any,
  3279. **kwargs: Any,
  3280. ) -> Tuple[torch.Tensor, torch.Tensor]:
  3281. if _is_omni_training_active():
  3282. eff_eps = float(kwargs.get("epsilon", eps))
  3283. rot_dim = kwargs.get("rot_dim", args[0] if len(args) > 0 else None)
  3284. rq, rk = _torch_rms_rope_split_half(
  3285. q, k, pe, q_scale, k_scale, eps=eff_eps, rot_dim=rot_dim
  3286. )
  3287. if inplace_flag and not (q.requires_grad or k.requires_grad):
  3288. q.copy_(rq)
  3289. k.copy_(rk)
  3290. return q, k
  3291. return rq, rk
  3292. return orig_f(q, k, pe, q_scale, k_scale, eps, *args, **kwargs)
  3293.  
  3294. setattr(_safe_rms_rope_split, "_omni_train_safe", True)
  3295. return _safe_rms_rope_split
  3296.  
  3297. setattr(ck_obj, split_fn_name, _make_rms_rope_split_wrapper(_orig_split, is_inplace_split))
  3298.  
  3299. if hasattr(ck_obj, "apply_rope_split_half") and not getattr(ck_obj.apply_rope_split_half, "_omni_train_safe", False):
  3300. _orig_apply_split = getattr(ck_obj, "_omni_orig_apply_rope_split_half", ck_obj.apply_rope_split_half)
  3301. setattr(ck_obj, "_omni_orig_apply_rope_split_half", _orig_apply_split)
  3302.  
  3303. def _make_apply_rope_split_wrapper(orig_f: Any) -> Any:
  3304. def _safe_apply_rope_split(
  3305. xq: torch.Tensor,
  3306. xk: torch.Tensor,
  3307. freqs_cis: torch.Tensor,
  3308. *args: Any,
  3309. **kwargs: Any,
  3310. ) -> Tuple[torch.Tensor, torch.Tensor]:
  3311. if _is_omni_training_active():
  3312. rot_dim = kwargs.get("rot_dim", args[0] if len(args) > 0 else None)
  3313. return (
  3314. _torch_apply_rope_split_half1(xq, freqs_cis, rot_dim=rot_dim),
  3315. _torch_apply_rope_split_half1(xk, freqs_cis, rot_dim=rot_dim),
  3316. )
  3317. return orig_f(xq, xk, freqs_cis, *args, **kwargs)
  3318.  
  3319. setattr(_safe_apply_rope_split, "_omni_train_safe", True)
  3320. return _safe_apply_rope_split
  3321.  
  3322. setattr(ck_obj, "apply_rope_split_half", _make_apply_rope_split_wrapper(_orig_apply_split))
  3323.  
  3324. if hasattr(ck_obj, "apply_rope") and not getattr(ck_obj.apply_rope, "_omni_train_safe", False):
  3325. _orig_apply_rope = getattr(ck_obj, "_omni_orig_apply_rope", ck_obj.apply_rope)
  3326. setattr(ck_obj, "_omni_orig_apply_rope", _orig_apply_rope)
  3327.  
  3328. def _make_apply_rope_wrapper(orig_f: Any) -> Any:
  3329. def _safe_apply_rope(
  3330. xq: torch.Tensor,
  3331. xk: torch.Tensor,
  3332. freqs_cis: torch.Tensor,
  3333. *args: Any,
  3334. **kwargs: Any,
  3335. ) -> Tuple[torch.Tensor, torch.Tensor]:
  3336. if _is_omni_training_active():
  3337. return (
  3338. _torch_apply_rope_interleaved1(xq, freqs_cis),
  3339. _torch_apply_rope_interleaved1(xk, freqs_cis),
  3340. )
  3341. return orig_f(xq, xk, freqs_cis, *args, **kwargs)
  3342.  
  3343. setattr(_safe_apply_rope, "_omni_train_safe", True)
  3344. return _safe_apply_rope
  3345.  
  3346. setattr(ck_obj, "apply_rope", _make_apply_rope_wrapper(_orig_apply_rope))
  3347.  
  3348. if hasattr(ck_obj, "apply_rope1") and not getattr(ck_obj.apply_rope1, "_omni_train_safe", False):
  3349. _orig_apply_rope1 = getattr(ck_obj, "_omni_orig_apply_rope1", ck_obj.apply_rope1)
  3350. setattr(ck_obj, "_omni_orig_apply_rope1", _orig_apply_rope1)
  3351.  
  3352. def _make_apply_rope1_wrapper(orig_f: Any) -> Any:
  3353. def _safe_apply_rope1(
  3354. x: torch.Tensor,
  3355. freqs_cis: torch.Tensor,
  3356. *args: Any,
  3357. **kwargs: Any,
  3358. ) -> torch.Tensor:
  3359. if _is_omni_training_active():
  3360. return _torch_apply_rope_interleaved1(x, freqs_cis)
  3361. return orig_f(x, freqs_cis, *args, **kwargs)
  3362.  
  3363. setattr(_safe_apply_rope1, "_omni_train_safe", True)
  3364. return _safe_apply_rope1
  3365.  
  3366. setattr(ck_obj, "apply_rope1", _make_apply_rope1_wrapper(_orig_apply_rope1))
  3367.  
  3368. if hasattr(ck_obj, "adaln") and not getattr(ck_obj.adaln, "_omni_train_safe", False):
  3369. _orig_adaln = getattr(ck_obj, "_omni_orig_adaln", ck_obj.adaln)
  3370. setattr(ck_obj, "_omni_orig_adaln", _orig_adaln)
  3371.  
  3372. def _make_adaln_wrapper(orig_f: Any) -> Any:
  3373. def _safe_adaln(
  3374. x: torch.Tensor,
  3375. scale: torch.Tensor,
  3376. shift: torch.Tensor,
  3377. eps: float = 1e-6,
  3378. *args: Any,
  3379. **kwargs: Any,
  3380. ) -> torch.Tensor:
  3381. if _is_omni_training_active():
  3382. normed = F.layer_norm(x, (int(x.shape[-1]),), eps=float(eps or 1e-6))
  3383. return torch.addcmul(shift, normed, 1.0 + scale)
  3384. return orig_f(x, scale, shift, eps, *args, **kwargs)
  3385.  
  3386. setattr(_safe_adaln, "_omni_train_safe", True)
  3387. return _safe_adaln
  3388.  
  3389. setattr(ck_obj, "adaln", _make_adaln_wrapper(_orig_adaln))
  3390.  
  3391. if hasattr(ck_obj, "rms_adaln") and not getattr(ck_obj.rms_adaln, "_omni_train_safe", False):
  3392. _orig_rms_adaln = getattr(ck_obj, "_omni_orig_rms_adaln", ck_obj.rms_adaln)
  3393. setattr(ck_obj, "_omni_orig_rms_adaln", _orig_rms_adaln)
  3394.  
  3395. def _make_rms_adaln_wrapper(orig_f: Any) -> Any:
  3396. def _safe_rms_adaln(
  3397. x: torch.Tensor,
  3398. scale: torch.Tensor,
  3399. shift: torch.Tensor,
  3400. eps: float = 1e-6,
  3401. *args: Any,
  3402. **kwargs: Any,
  3403. ) -> torch.Tensor:
  3404. if _is_omni_training_active():
  3405. normed = _rms_norm_t(x, None, eps=float(eps or 1e-6))
  3406. return torch.addcmul(shift, normed, 1.0 + scale)
  3407. return orig_f(x, scale, shift, eps, *args, **kwargs)
  3408.  
  3409. setattr(_safe_rms_adaln, "_omni_train_safe", True)
  3410. return _safe_rms_adaln
  3411.  
  3412. setattr(ck_obj, "rms_adaln", _make_rms_adaln_wrapper(_orig_rms_adaln))
  3413. except Exception:
  3414. pass
  3415.  
  3416.  
  3417. def _rebind_comfy_attention_modules(root: Optional[nn.Module]) -> None:
  3418. """
  3419. Ensure any pre-loaded `ComfyAttention` submodule on `root` whose `.function` (or
  3420. `functools.partial.func`) bound an unpatched `attention_comfy_kitchen_*` / `attention_sage`
  3421. callable before `install_comfy_runtime_hooks()` is rebound to the training-safe wrapper.
  3422. """
  3423. if root is None or not isinstance(root, nn.Module):
  3424. return
  3425. comfy_attn = sys.modules.get("comfy.ldm.modules.attention")
  3426. replaced_map = getattr(comfy_attn, "_omni_replaced_attn_map", None) if comfy_attn is not None else None
  3427. if not isinstance(replaced_map, dict) or not replaced_map:
  3428. return
  3429. import functools
  3430.  
  3431. for mod in root.modules():
  3432. candidates = [mod]
  3433. ca = getattr(mod, "comfy_attention", None)
  3434. if ca is not None and ca is not mod:
  3435. candidates.append(ca)
  3436. for obj in candidates:
  3437. fn = getattr(obj, "function", None)
  3438. if fn is None or getattr(fn, "_omni_train_attn_safe", False):
  3439. continue
  3440. pair = replaced_map.get(id(fn))
  3441. if pair is not None:
  3442. try:
  3443. setattr(obj, "function", pair[1])
  3444. except Exception:
  3445. pass
  3446. elif isinstance(fn, functools.partial):
  3447. inner_pair = replaced_map.get(id(fn.func))
  3448. if inner_pair is not None:
  3449. try:
  3450. new_partial = functools.partial(inner_pair[1], *fn.args, **(fn.keywords or {}))
  3451. setattr(new_partial, "_omni_train_attn_safe", True)
  3452. setattr(obj, "function", new_partial)
  3453. except Exception:
  3454. pass
  3455.  
  3456.  
  3457. def unwrap_comfy_diffusion_model(
  3458. comfy_model: Any,
  3459. load_to_gpu: bool = False,
  3460. memory_required_mb: float = 4608.0,
  3461. ) -> Optional[nn.Module]:
  3462. """Unwrap a ComfyUI `ModelPatcher` (`MODEL`) to extract the underlying `diffusion_model` (`nn.Module`)."""
  3463. install_comfy_runtime_hooks()
  3464. if comfy_model is None:
  3465. return None
  3466.  
  3467. # Only call comfy.model_management.load_models_gpu on an actual ModelPatcher when explicitly requested,
  3468. # passing `memory_required` so ComfyUI reserves VRAM headroom for activations and optimizer states.
  3469. if load_to_gpu and not isinstance(comfy_model, nn.Module) and hasattr(comfy_model, "model"):
  3470. try:
  3471. import comfy.model_management as mm # type: ignore
  3472.  
  3473. mem_req_bytes = int(max(2048.0, float(memory_required_mb)) * (1024**2))
  3474. try:
  3475. mm.load_models_gpu([comfy_model], memory_required=mem_req_bytes)
  3476. except TypeError:
  3477. mm.load_models_gpu([comfy_model])
  3478. except Exception:
  3479. pass
  3480.  
  3481. candidates: List[Any] = []
  3482. if hasattr(comfy_model, "get_model_object") and callable(comfy_model.get_model_object):
  3483. try:
  3484. dm = comfy_model.get_model_object("diffusion_model")
  3485. if dm is not None:
  3486. candidates.append(dm)
  3487. except Exception:
  3488. pass
  3489.  
  3490. if hasattr(comfy_model, "model"):
  3491. inner = comfy_model.model
  3492. if hasattr(inner, "diffusion_model"):
  3493. candidates.append(inner.diffusion_model)
  3494. if hasattr(inner, "transformer"):
  3495. candidates.append(inner.transformer)
  3496. candidates.append(inner)
  3497.  
  3498. if hasattr(comfy_model, "diffusion_model"):
  3499. candidates.append(comfy_model.diffusion_model)
  3500. if hasattr(comfy_model, "transformer"):
  3501. candidates.append(comfy_model.transformer)
  3502. candidates.append(comfy_model)
  3503.  
  3504. for cand in candidates:
  3505. if isinstance(cand, nn.Module):
  3506. has_children = any(True for _ in cand.children())
  3507. has_params = any(True for _ in cand.parameters())
  3508. if has_children or has_params:
  3509. _rebind_comfy_attention_modules(cand)
  3510. LoRAInjector.capture_comfy_lora_key_map(cand, comfy_model=comfy_model)
  3511. return cand
  3512.  
  3513. return None
  3514.  
  3515.  
  3516. _COMFY_SUPPORTED_MODEL_CANONICAL_MAP: Dict[str, str] = {
  3517. "mossimage": "moss_image",
  3518. "krea2": "krea2",
  3519. "flux3": "flux3",
  3520. "flux3klein": "flux3",
  3521. "mockflux3klein": "flux3",
  3522. "flux2": "flux2",
  3523. "flux": "flux_dev",
  3524. "fluxschnell": "flux_dev",
  3525. "fluxinpaint": "flux_dev",
  3526. "fibo2": "fibo2",
  3527. "chroma": "chroma",
  3528. "chromaradiance": "chroma_radiance",
  3529. "hidream": "hidream",
  3530. "hidreamo1": "hidream_o1",
  3531. "sd3": "sd3_5",
  3532. "sdxl": "sdxl_base",
  3533. "sdxlrefiner": "sdxl_base",
  3534. "sdxl_instructpix2pix": "sdxl_base",
  3535. "ssd1b": "sdxl_base",
  3536. "sd15": "sd15",
  3537. "sd15_instructpix2pix": "sd15",
  3538. "sd20": "sd15",
  3539. "sd21unclipl": "sd15",
  3540. "sd21uncliph": "sd15",
  3541. "qwenimage21": "qwen_image21",
  3542. "qwenimage": "qwen_image",
  3543. "lumina2": "lumina2",
  3544. "zimage": "lumina2",
  3545. "zimagepixelspace": "lumina2",
  3546. "omnigen2": "omnigen2",
  3547. "auraflow": "auraflow",
  3548. "pixartalpha": "pixart",
  3549. "pixartsigma": "pixart",
  3550. "hunyuandit": "hunyuan_dit",
  3551. "hunyuandit1": "hunyuan_dit",
  3552. "stable_cascade_c": "stable_cascade",
  3553. "stable_cascade_b": "stable_cascade",
  3554. "stablecascade_c": "stable_cascade",
  3555. "stablecascade_b": "stable_cascade",
  3556. "ideogram4": "ideogram4",
  3557. "boogu": "boogu",
  3558. "joyimage": "joyimage",
  3559. "mageflow": "mage_flow",
  3560. "anima": "anima",
  3561. "pixelditt2i": "pixeldit",
  3562. "pid": "pixeldit",
  3563. "pixeldit": "pixeldit",
  3564. "ernieimage": "ernie",
  3565. "lens": "lens",
  3566. "wan22_t2v": "wan22",
  3567. "wan22_camera": "wan22",
  3568. "wan22_s2v": "wan22",
  3569. "wan22_animate": "wan22",
  3570. "wan22_relayvsr": "wan22",
  3571. "wan22_wandancer": "wan22",
  3572. "wan22": "wan22",
  3573. "wan21_t2v": "wan_t2v",
  3574. "wan21_i2v": "wan_t2v",
  3575. "wan21_funcontrol2v": "wan_t2v",
  3576. "wan21_vace": "wan_t2v",
  3577. "wan21_camera": "wan_t2v",
  3578. "wan21_humo": "wan_t2v",
  3579. "wan21_causalar_t2v": "wan_t2v",
  3580. "wan21": "wan_t2v",
  3581. "hunyuanvideo": "hunyuan_video",
  3582. "hunyuanvideoi2v": "hunyuan_video",
  3583. "hunyuanvideo15": "hunyuan_video",
  3584. "hunyuanvideo15_sr_distilled": "hunyuan_video",
  3585. "hunyuanvideoskyreelsi2v": "hunyuan_video",
  3586. "hunyuanimage21": "hunyuan_video",
  3587. "ltxv": "ltx_video",
  3588. "ltxav": "ltxav",
  3589. "cosmost2v": "cosmos",
  3590. "cosmosi2v": "cosmos",
  3591. "cosmost2ipredict2": "cosmos",
  3592. "cosmosi2vpredict2": "cosmos",
  3593. "cosmosvideo": "cosmos",
  3594. "cosmospredict2": "cosmos",
  3595. "kandinsky5": "kandinsky5",
  3596. "kandinsky5image": "kandinsky5",
  3597. "cogvideox": "cogvideo",
  3598. "cogvideox_t2v": "cogvideo",
  3599. "cogvideox_i2v": "cogvideo",
  3600. "cogvideox_inpaint": "cogvideo",
  3601. "genmomochi": "genmo_mochi",
  3602. "acestep": "ace_step",
  3603. "acestep15": "ace_step15",
  3604. "stableaudio": "mmaudio",
  3605. "stableaudio3": "mmaudio",
  3606. "yue2": "yue2",
  3607. "hunyuan3dv2": "hunyuan3d",
  3608. "hunyuan3dv2_1": "hunyuan3dv2_1",
  3609. "hunyuan3dv2mini": "hunyuan3d",
  3610. "sensenovau15": "sensenova",
  3611. "sensenova": "sensenova",
  3612. "minimaxh3": "minimax",
  3613. "minimax": "minimax",
  3614. "minimaxmusic3": "minimax_music",
  3615. "minimax_music": "minimax_music",
  3616. "seedvr2": "seedvr",
  3617. "seedvr": "seedvr",
  3618. "trellis2": "trellis2",
  3619. "triposplat": "triposplat",
  3620. }
  3621.  
  3622.  
  3623. _COMFY_LDM_MODULE_TO_CANONICAL: Dict[str, str] = {
  3624. "comfy.ldm.moss_image": "moss_image",
  3625. "comfy.ldm.krea2": "krea2",
  3626. "comfy.ldm.flux3": "flux3",
  3627. "comfy.ldm.flux": "flux_dev",
  3628. "comfy.ldm.fibo2": "fibo2",
  3629. "comfy.ldm.chroma_radiance": "chroma_radiance",
  3630. "comfy.ldm.chroma": "chroma",
  3631. "comfy.ldm.hidream_o1": "hidream_o1",
  3632. "comfy.ldm.hidream": "hidream",
  3633. "comfy.ldm.qwen_image21": "qwen_image21",
  3634. "comfy.ldm.qwen_image": "qwen_image",
  3635. "comfy.ldm.lumina": "lumina2",
  3636. "comfy.ldm.omnigen": "omnigen2",
  3637. "comfy.ldm.aura": "auraflow",
  3638. "comfy.ldm.wan": "wan_t2v",
  3639. "comfy.ldm.hunyuan_video": "hunyuan_video",
  3640. "comfy.ldm.lightricks.av_model": "ltxav",
  3641. "comfy.ldm.lightricks": "ltx_video",
  3642. "comfy.ldm.cosmos": "cosmos",
  3643. "comfy.ldm.ideogram4": "ideogram4",
  3644. "comfy.ldm.boogu": "boogu",
  3645. "comfy.ldm.joyimage": "joyimage",
  3646. "comfy.ldm.mage_flow": "mage_flow",
  3647. "comfy.ldm.anima": "anima",
  3648. "comfy.ldm.pixeldit": "pixeldit",
  3649. "comfy.ldm.ernie": "ernie",
  3650. "comfy.ldm.lens": "lens",
  3651. "comfy.ldm.kandinsky5": "kandinsky5",
  3652. "comfy.ldm.cogvideo": "cogvideo",
  3653. "comfy.ldm.genmo": "genmo_mochi",
  3654. "comfy.ldm.ace.ace_step15": "ace_step15",
  3655. "comfy.ldm.ace": "ace_step",
  3656. "comfy.ldm.mmaudio": "mmaudio",
  3657. "comfy.ldm.audio": "mmaudio",
  3658. "comfy.ldm.yue2": "yue2",
  3659. "comfy.ldm.hunyuan3dv2_1": "hunyuan3dv2_1",
  3660. "comfy.ldm.hunyuan3d": "hunyuan3d",
  3661. "comfy.ldm.hydit": "hunyuan_dit",
  3662. "comfy.ldm.hunyuandit": "hunyuan_dit",
  3663. "comfy.ldm.pixart": "pixart",
  3664. "comfy.ldm.cascade": "stable_cascade",
  3665. "comfy.ldm.sensenova": "sensenova",
  3666. "comfy.ldm.minimax_music": "minimax_music",
  3667. "comfy.ldm.minimax": "minimax",
  3668. "comfy.ldm.seedvr": "seedvr",
  3669. "comfy.ldm.trellis2": "trellis2",
  3670. "comfy.ldm.triposplat": "triposplat",
  3671. "comfy.ldm.modules.diffusionmodules.mmdit": "sd3_5",
  3672. "comfy.ldm.modules.diffusionmodules.openaimodel": "sdxl_base",
  3673. }
  3674.  
  3675.  
  3676. def resolve_comfy_native_architecture(
  3677. comfy_model_or_backbone: Any,
  3678. unet_config: Optional[Dict[str, Any]] = None,
  3679. ) -> Dict[str, Any]:
  3680. """
  3681. Directly query ComfyUI's native runtime modules (`comfy.model_base`,
  3682. `comfy.supported_models`, `comfy.model_detection`, and `comfy.latent_formats`)
  3683. to identify the exact model architecture, `model_config`, `unet_config`,
  3684. `latent_format`, `model_type`, and `model_sampling` without string guessing.
  3685. """
  3686. ensure_comfy_importable()
  3687.  
  3688. result: Dict[str, Any] = {
  3689. "canonical_id": None,
  3690. "comfy_model_base_class": None,
  3691. "comfy_supported_model_class": None,
  3692. "comfy_ldm_class": None,
  3693. "model_config": None,
  3694. "unet_config": dict(unet_config) if isinstance(unet_config, dict) else {},
  3695. "latent_format": None,
  3696. "model_type": None,
  3697. "model_sampling": None,
  3698. }
  3699. if comfy_model_or_backbone is None:
  3700. return result
  3701.  
  3702. inner_model = getattr(comfy_model_or_backbone, "model", comfy_model_or_backbone)
  3703. backbone = getattr(inner_model, "diffusion_model", None)
  3704. if backbone is None and isinstance(comfy_model_or_backbone, nn.Module):
  3705. backbone = comfy_model_or_backbone
  3706.  
  3707. model_cfg = (
  3708. getattr(inner_model, "model_config", None)
  3709. or getattr(comfy_model_or_backbone, "model_config", None)
  3710. )
  3711.  
  3712. # 1. Inspect `backbone` (`comfy.ldm.*` class identity)
  3713. if isinstance(backbone, nn.Module):
  3714. b_mod = getattr(backbone.__class__, "__module__", "")
  3715. b_cls = backbone.__class__.__name__
  3716. result["comfy_ldm_class"] = f"{b_mod}.{b_cls}"
  3717. for mod_prefix, canon_id in _COMFY_LDM_MODULE_TO_CANONICAL.items():
  3718. if b_mod == mod_prefix or b_mod.startswith(f"{mod_prefix}."):
  3719. if mod_prefix == "comfy.ldm.hidream" and "hidreamo1" in b_cls.lower():
  3720. result["canonical_id"] = "hidream_o1"
  3721. elif mod_prefix == "comfy.ldm.modules.diffusionmodules.openaimodel":
  3722. # Distinguish SD1.5 (no adm/label_emb) vs SDXL (num_classes == "sequential")
  3723. result["canonical_id"] = (
  3724. "sdxl_base" if getattr(backbone, "num_classes", None) == "sequential" else "sd15"
  3725. )
  3726. elif mod_prefix == "comfy.ldm.wan":
  3727. in_d = getattr(backbone, "in_dim", getattr(getattr(backbone, "patch_embedding", None), "in_channels", 16))
  3728. result["canonical_id"] = "wan22" if int(in_d or 16) == 48 else "wan_t2v"
  3729. else:
  3730. result["canonical_id"] = canon_id
  3731. break
  3732.  
  3733. # 2. If a bare `diffusion_model` (`nn.Module`) was provided without `model_config`,
  3734. # invoke ComfyUI's native `comfy.model_detection.model_config_from_unet` or match `comfy.supported_models.models`.
  3735. if model_cfg is None and isinstance(backbone, nn.Module):
  3736. try:
  3737. import comfy.model_detection as _cmd # type: ignore
  3738.  
  3739. sd = backbone.state_dict()
  3740. if sd:
  3741. detected_cfg = _cmd.model_config_from_unet(sd, "", use_base_if_no_match=False)
  3742. if detected_cfg is not None:
  3743. model_cfg = detected_cfg
  3744. except Exception:
  3745. pass
  3746.  
  3747. if model_cfg is None and result["canonical_id"] is not None:
  3748. try:
  3749. import comfy.supported_models as _csm # type: ignore
  3750.  
  3751. target_canon = result["canonical_id"]
  3752. for sm_cls in getattr(_csm, "models", []):
  3753. sm_name_l = sm_cls.__name__.lower()
  3754. if _COMFY_SUPPORTED_MODEL_CANONICAL_MAP.get(sm_name_l) == target_canon:
  3755. base_ucfg = dict(getattr(sm_cls, "unet_config", {}) or {})
  3756. base_ucfg.update(result["unet_config"])
  3757. base_ucfg["disable_unet_model_creation"] = True
  3758. model_cfg = sm_cls(base_ucfg)
  3759. break
  3760. except Exception:
  3761. pass
  3762.  
  3763. if model_cfg is not None:
  3764. result["model_config"] = model_cfg
  3765. cfg_cls_name = model_cfg.__class__.__name__
  3766. result["comfy_supported_model_class"] = f"{model_cfg.__class__.__module__}.{cfg_cls_name}"
  3767. raw_ucfg = getattr(model_cfg, "unet_config", None)
  3768. if isinstance(raw_ucfg, dict) and raw_ucfg:
  3769. merged_ucfg = dict(raw_ucfg)
  3770. merged_ucfg.update(result["unet_config"])
  3771. result["unet_config"] = merged_ucfg
  3772. lf = getattr(model_cfg, "latent_format", None)
  3773. if lf is not None:
  3774. result["latent_format"] = lf
  3775. if isinstance(lf, type):
  3776. try:
  3777. result["latent_format"] = lf()
  3778. except Exception:
  3779. pass
  3780. if result["model_type"] is None and hasattr(model_cfg, "model_type") and callable(model_cfg.model_type):
  3781. try:
  3782. result["model_type"] = model_cfg.model_type({})
  3783. except Exception:
  3784. pass
  3785. mapped = _COMFY_SUPPORTED_MODEL_CANONICAL_MAP.get(cfg_cls_name.lower())
  3786. if mapped:
  3787. result["canonical_id"] = mapped
  3788.  
  3789. # 3. Inspect `inner_model` against `comfy.model_base.BaseModel` subclasses & `ModelType`
  3790. try:
  3791. import comfy.model_base as _cmb # type: ignore
  3792.  
  3793. if isinstance(inner_model, _cmb.BaseModel):
  3794. mb_cls_name = inner_model.__class__.__name__
  3795. result["comfy_model_base_class"] = f"{inner_model.__class__.__module__}.{mb_cls_name}"
  3796. if getattr(inner_model, "model_type", None) is not None:
  3797. result["model_type"] = inner_model.model_type
  3798. if getattr(inner_model, "latent_format", None) is not None:
  3799. result["latent_format"] = inner_model.latent_format
  3800. if getattr(inner_model, "model_sampling", None) is not None:
  3801. result["model_sampling"] = inner_model.model_sampling
  3802. if result["canonical_id"] is None:
  3803. mapped_mb = _COMFY_SUPPORTED_MODEL_CANONICAL_MAP.get(mb_cls_name.lower())
  3804. if mapped_mb:
  3805. result["canonical_id"] = mapped_mb
  3806.  
  3807. if result["model_sampling"] is None and model_cfg is not None:
  3808. m_type = result["model_type"] if result["model_type"] is not None else _cmb.ModelType.EPS
  3809. result["model_sampling"] = _cmb.model_sampling(model_cfg, m_type)
  3810. except Exception:
  3811. pass
  3812.  
  3813. # 4. Check `unet_config["image_model"]` or `unet_config["audio_model"]` populated by ComfyUI's `supported_models.py`
  3814. ucfg = result["unet_config"]
  3815. if result["canonical_id"] is None and isinstance(ucfg, dict):
  3816. for k_field in ("image_model", "audio_model"):
  3817. val = ucfg.get(k_field)
  3818. if isinstance(val, str) and val.strip():
  3819. norm_val = val.strip().lower()
  3820. result["canonical_id"] = _COMFY_SUPPORTED_MODEL_CANONICAL_MAP.get(norm_val, norm_val)
  3821. break
  3822.  
  3823. return result
  3824.  
  3825.  
  3826. def detect_comfy_model_architecture(
  3827. comfy_model_or_backbone: Any,
  3828. unet_config: Optional[Dict[str, Any]] = None,
  3829. ) -> str:
  3830. """
  3831. Inspect a ComfyUI `ModelPatcher`, `comfy.model_base.BaseModel`, `comfy.supported_models` config,
  3832. `unet_config`, or `comfy.ldm.*` `diffusion_model` via `resolve_comfy_native_architecture`
  3833. and return its canonical architecture ID.
  3834. """
  3835. if comfy_model_or_backbone is None and not unet_config:
  3836. return "auto"
  3837.  
  3838. native_info = resolve_comfy_native_architecture(comfy_model_or_backbone, unet_config=unet_config)
  3839. if isinstance(native_info.get("canonical_id"), str) and native_info["canonical_id"]:
  3840. return str(native_info["canonical_id"])
  3841.  
  3842. if comfy_model_or_backbone is None:
  3843. return "auto"
  3844.  
  3845. backbone = (
  3846. comfy_model_or_backbone
  3847. if isinstance(comfy_model_or_backbone, nn.Module)
  3848. else (unwrap_comfy_diffusion_model(comfy_model_or_backbone, load_to_gpu=False) or comfy_model_or_backbone)
  3849. )
  3850. cls_name = backbone.__class__.__name__.lower()
  3851. if cls_name.startswith("mock"):
  3852. unmocked = cls_name[4:]
  3853. if unmocked in _COMFY_SUPPORTED_MODEL_CANONICAL_MAP:
  3854. return _COMFY_SUPPORTED_MODEL_CANONICAL_MAP[unmocked]
  3855. return _COMFY_SUPPORTED_MODEL_CANONICAL_MAP.get(cls_name, cls_name or "auto")
  3856.  
  3857.  
  3858. def is_optimal_lora_target_path(
  3859. module_name: str,
  3860. structural_roles: Optional[Dict[str, str]] = None,
  3861. backbone: Optional[nn.Module] = None,
  3862. model: Optional[nn.Module] = None,
  3863. ) -> bool:
  3864. """
  3865. Return True if `module_name` is an optimal LoRA target (Self/Cross/Joint Attention,
  3866. FeedForward/MLP/SwiGLU/MoE-Expert, or repeating-block Linear / 1x1 `block_projection`
  3867. such as SpatialTransformer `proj_in` / `proj_out`), evaluated structurally via
  3868. `classify_block_structural_roles`:
  3869. - Returns True for `"attention"`, `"ffn"`, `"attention_or_ffn"`, and `"block_projection"` roles.
  3870. - Returns False for `"stem_or_head"`, `"modulation"` (AdaLN / timestep modulations),
  3871. and `"moe_router"` (`ff_i.gate`) roles.
  3872. """
  3873. if not module_name or not _strip_numeric_segments(module_name.replace("__", ".")):
  3874. return False
  3875.  
  3876. if backbone is None and model is not None:
  3877. backbone = model
  3878.  
  3879. if structural_roles is None and isinstance(backbone, nn.Module):
  3880. structural_roles = classify_block_structural_roles(backbone)
  3881.  
  3882. if structural_roles is not None:
  3883. role = structural_roles.get(module_name)
  3884. if role is None:
  3885. norm_name = module_name.replace("__", ".")
  3886. for path, r in structural_roles.items():
  3887. if LoRAInjector._matches_target(path, (norm_name,)):
  3888. role = r
  3889. break
  3890. if role is not None:
  3891. return role in ("attention", "ffn", "attention_or_ffn", "block_projection")
  3892. if backbone is not None:
  3893. return False
  3894.  
  3895. return True
  3896.  
  3897.  
  3898. def discover_universal_target_modules(
  3899. backbone: nn.Module,
  3900. comfy_inner_model: Optional[Any] = None,
  3901. include_conv: bool = False,
  3902. ) -> Tuple[str, ...]:
  3903. """
  3904. Universal ComfyUI LoRA target discovery:
  3905. 1. Queries `comfy.lora.model_lora_keys_unet` (if available) so any module exposed by ComfyUI's
  3906. own LoRA loader (including tuple-sliced keys like QwenImage21's `img_mlp.gate_up`) is recognized.
  3907. 2. Classifies every Linear-like and pointwise 1x1 `block_projection` module by its structural role
  3908. in the residual stream topology via `classify_block_structural_roles(backbone)` (distinguishing
  3909. Attention, FFN/MoE-Expert, and block/skip projections like SpatialTransformer `proj_in`/`proj_out`
  3910. from AdaLN modulations, MoE router gates `ff_i.gate`, and top-level stems/heads without string guessing).
  3911. 3. Strips numeric block indices (`layers.0.proj_qkv` -> `layers.proj_qkv`) so all Attention,
  3912. MLP/expert, and block projections inside repeating transformer/UNet blocks are adapted by default.
  3913. 4. When `include_conv=True` (LoCon / Conv-LoRA mode), also discovers spatial ResNet/Downsample/Upsample
  3914. Convolution layers inside repeating blocks (e.g., `in_layers.2`, `out_layers.3`, `skip_connection`,
  3915. `op`, `conv`), while still excluding raw input/output stems.
  3916. """
  3917. comfy_valid_paths: Optional[set[str]] = None
  3918. if comfy_inner_model is not None:
  3919. try:
  3920. import comfy.lora # type: ignore
  3921.  
  3922. if hasattr(comfy.lora, "model_lora_keys_unet"):
  3923. key_map = comfy.lora.model_lora_keys_unet(comfy_inner_model, {})
  3924. paths: set[str] = set()
  3925. for v in key_map.values():
  3926. raw_k = v[0] if isinstance(v, tuple) and len(v) > 0 else v
  3927. if isinstance(raw_k, str) and raw_k.endswith(".weight"):
  3928. clean_w = raw_k.replace(".base_layer.weight", ".weight")
  3929. paths.add(clean_w[: -len(".weight")].removeprefix("diffusion_model."))
  3930. if paths:
  3931. comfy_valid_paths = paths
  3932. except Exception:
  3933. comfy_valid_paths = None
  3934.  
  3935. block_module_ids = _collect_repeating_block_module_ids(backbone)
  3936. structural_roles = classify_block_structural_roles(backbone)
  3937.  
  3938. discovered: List[str] = []
  3939. seen: set[str] = set()
  3940.  
  3941. for _, _, name, module in LoRAInjector._iter_injectable_modules(backbone):
  3942. if not name:
  3943. continue
  3944. if comfy_valid_paths is not None and name not in comfy_valid_paths:
  3945. continue
  3946. if block_module_ids and id(module) not in block_module_ids:
  3947. continue
  3948. is_pointwise_block_proj = (
  3949. _is_pointwise_conv(module) and structural_roles.get(name) == "block_projection"
  3950. )
  3951. if (
  3952. _is_linear_like(module)
  3953. or (isinstance(module, LoRALinear) and not getattr(module, "is_conv", False))
  3954. or is_pointwise_block_proj
  3955. ):
  3956. if not is_optimal_lora_target_path(name, structural_roles=structural_roles):
  3957. continue
  3958. stripped = _strip_numeric_segments(name)
  3959. if stripped and stripped not in seen:
  3960. seen.add(stripped)
  3961. discovered.append(stripped)
  3962.  
  3963. if include_conv:
  3964. for _, _, name, module in LoRAInjector._iter_injectable_modules(backbone):
  3965. if not name:
  3966. continue
  3967. if comfy_valid_paths is not None and name not in comfy_valid_paths:
  3968. continue
  3969. if block_module_ids and id(module) not in block_module_ids:
  3970. continue
  3971. is_conv_mod = _is_conv_like(module) or (isinstance(module, LoRALinear) and getattr(module, "is_conv", False))
  3972. if is_conv_mod:
  3973. stripped = _strip_numeric_segments(name)
  3974. if (
  3975. stripped
  3976. and stripped.lower() not in (_UNET_BLOCK_CONTAINER_NAMES | {"out", "conv_in", "conv_out"})
  3977. and stripped not in seen
  3978. ):
  3979. seen.add(stripped)
  3980. discovered.append(stripped)
  3981.  
  3982. if not discovered:
  3983. for _, _, name, module in LoRAInjector._iter_injectable_modules(backbone):
  3984. if _is_linear_like(module) and name:
  3985. if not is_optimal_lora_target_path(name, structural_roles=structural_roles):
  3986. continue
  3987. stripped = _strip_numeric_segments(name)
  3988. if stripped and stripped not in seen:
  3989. seen.add(stripped)
  3990. discovered.append(stripped)
  3991.  
  3992. if not discovered:
  3993. for _, _, name, module in LoRAInjector._iter_injectable_modules(backbone):
  3994. if (_is_linear_like(module) or _is_conv_like(module)) and name:
  3995. stripped = _strip_numeric_segments(name)
  3996. if stripped and stripped not in seen:
  3997. seen.add(stripped)
  3998. discovered.append(stripped)
  3999.  
  4000. return tuple(discovered)
  4001.  
  4002.  
  4003. def resolve_model_adapter(
  4004. model_id: str = "auto",
  4005. comfy_model: Optional[Any] = None,
  4006. **kwargs: Any,
  4007. ) -> ComfyModelAdapter:
  4008. """Instantiate a universal ComfyModelAdapter driven by the connected ComfyUI MODEL."""
  4009. return ComfyModelAdapter(comfy_model=comfy_model, model_id=model_id, **kwargs)
  4010.  
  4011.  
  4012. # Backwards-compatible aliases pointing to the single universal ComfyModelAdapter
  4013. UniversalModelAdapter = ComfyModelAdapter
  4014. MossImageAdapter = ComfyModelAdapter
  4015. FluxModelAdapter = ComfyModelAdapter
  4016. SD3ModelAdapter = ComfyModelAdapter
  4017. SDXLModelAdapter = ComfyModelAdapter
  4018. SD15ModelAdapter = ComfyModelAdapter
  4019. WanVideoAdapter = ComfyModelAdapter
  4020. HunyuanVideoAdapter = ComfyModelAdapter
  4021. LTXVideoAdapter = ComfyModelAdapter
  4022. QwenImageAdapter = ComfyModelAdapter
  4023.  
  4024.  
  4025. class _DynamicModelSpecDict(dict): # type: ignore[type-arg]
  4026. """On-demand ModelSpec lookup that works for any model identifier without hardcoded tables."""
  4027.  
  4028. def __missing__(self, key: str) -> ModelSpec:
  4029. return ComfyModelAdapter(model_id=str(key)).spec
  4030.  
  4031.  
  4032. MODEL_REGISTRY: Dict[str, Type[ComfyModelAdapter]] = {
  4033. "auto": ComfyModelAdapter,
  4034. "comfy_model": ComfyModelAdapter,
  4035. "moss_image": ComfyModelAdapter,
  4036. "krea2": ComfyModelAdapter,
  4037. "flux3": ComfyModelAdapter,
  4038. "flux2": ComfyModelAdapter,
  4039. "flux_dev": ComfyModelAdapter,
  4040. "fibo2": ComfyModelAdapter,
  4041. "hidream": ComfyModelAdapter,
  4042. "hidream_o1": ComfyModelAdapter,
  4043. "chroma": ComfyModelAdapter,
  4044. "chroma_radiance": ComfyModelAdapter,
  4045. "sd3_5": ComfyModelAdapter,
  4046. "sdxl_base": ComfyModelAdapter,
  4047. "sd15": ComfyModelAdapter,
  4048. "wan_t2v": ComfyModelAdapter,
  4049. "wan21": ComfyModelAdapter,
  4050. "wan22": ComfyModelAdapter,
  4051. "hunyuan_video": ComfyModelAdapter,
  4052. "ltx_video": ComfyModelAdapter,
  4053. "qwen_image": ComfyModelAdapter,
  4054. "qwen_image21": ComfyModelAdapter,
  4055. "lumina2": ComfyModelAdapter,
  4056. "omnigen2": ComfyModelAdapter,
  4057. "cosmos": ComfyModelAdapter,
  4058. "auraflow": ComfyModelAdapter,
  4059. "ideogram4": ComfyModelAdapter,
  4060. "boogu": ComfyModelAdapter,
  4061. "joyimage": ComfyModelAdapter,
  4062. "mage_flow": ComfyModelAdapter,
  4063. "anima": ComfyModelAdapter,
  4064. "pixeldit": ComfyModelAdapter,
  4065. "ernie": ComfyModelAdapter,
  4066. "lens": ComfyModelAdapter,
  4067. "kandinsky5": ComfyModelAdapter,
  4068. "cogvideo": ComfyModelAdapter,
  4069. "genmo_mochi": ComfyModelAdapter,
  4070. "ace_step": ComfyModelAdapter,
  4071. "ace_step15": ComfyModelAdapter,
  4072. "mmaudio": ComfyModelAdapter,
  4073. "yue2": ComfyModelAdapter,
  4074. "hunyuan3d": ComfyModelAdapter,
  4075. "hunyuan3dv2_1": ComfyModelAdapter,
  4076. "pixart": ComfyModelAdapter,
  4077. "hunyuan_dit": ComfyModelAdapter,
  4078. "stable_cascade": ComfyModelAdapter,
  4079. "sensenova": ComfyModelAdapter,
  4080. "minimax": ComfyModelAdapter,
  4081. "minimax_music": ComfyModelAdapter,
  4082. "seedvr": ComfyModelAdapter,
  4083. "trellis2": ComfyModelAdapter,
  4084. "triposplat": ComfyModelAdapter,
  4085. "ltxav": ComfyModelAdapter,
  4086. }
  4087.  
  4088. MODEL_SPECS: Dict[str, ModelSpec] = _DynamicModelSpecDict(
  4089. {k: ComfyModelAdapter(model_id=k).spec for k in MODEL_REGISTRY}
  4090. )
  4091.  
Advertisement
Add Comment
Please, Sign In to add comment