Commit ·
de17ab7
1
Parent(s): 7610864
klein9 refmods
Browse files- klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/README.md +74 -0
- klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/__init__.py +20 -0
- klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/common.py +49 -0
- klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/core.py +195 -0
- klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/extract_klein9_mod.py +145 -0
- klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/nodes.py +362 -0
- klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/requirements.txt +4 -0
- klein9/docs/examples/Flux2-Klein9-AlisonBrie-5Col-Comparison-Grid.png +3 -0
- klein9/docs/examples/Flux2-Klein9-BrettCooper-5Col-Comparison-Grid.png +3 -0
- klein9/docs/examples/Flux2-Klein9-Gosia-5Col-Comparison-Grid.png +3 -0
- klein9/docs/examples/Flux2-Klein9-JodieFoster-5Col-Comparison-Grid.png +3 -0
- klein9/docs/examples/Flux2-Klein9-OliviaWilde-5Col-Comparison-Grid.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-AlisonBrie-Run1_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-AlisonBrie-Run2_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-AlisonBrie-Run3_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-BrettCooper-Run1_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-BrettCooper-Run2_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-BrettCooper-Run3_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-JodieFoster-Run1_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-JodieFoster-Run2_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-JodieFoster-Run3_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-OliviaWilde-Run1_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-OliviaWilde-Run2_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-OliviaWilde-Run3_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-RebeccaFerguson-Run1_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-RebeccaFerguson-Run2_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-RebeccaFerguson-Run3_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-SydneySweeney-Run1_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-SydneySweeney-Run2_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-PureLoRA10-SydneySweeney-Run3_00001_.png +3 -0
- klein9/docs/examples/Flux2-Klein9-RebeccaFerguson-5Col-Comparison-Grid.png +3 -0
- klein9/docs/examples/Flux2-Klein9-SydneySweeney-5Col-Comparison-Grid.png +3 -0
klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ComfyUI-Flux2Klein9Mod
|
| 2 |
+
|
| 3 |
+
**No-training "RefMod" reference adapters for FLUX.2 and Klein9.**
|
| 4 |
+
|
| 5 |
+
RefMods pre-encode reference images and datasets into compact, reusable `.safetensors` adapters stored in `models/refmods-klein9/`. Rather than loading and VAE-encoding raw 4K/1024px image files on every generation run (which adds 4096+ tokens and heavy attention latency), RefMods inject pre-computed reference latents directly into the FLUX.2 / Klein9 2D RoPE sequence with instant loading, zero VAE overhead, and full multi-character scaling.
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## 📦 Features
|
| 10 |
+
|
| 11 |
+
- **Pre-encoded Latent Storage:** Stored in `ComfyUI/models/refmods-klein9/`.
|
| 12 |
+
- **Zero VAE Generation Latency:** Latents are loaded directly from disk without runtime VAE encoding.
|
| 13 |
+
- **Configurable Token Budgets:** Native resolution or spatial pooling to target budgets (e.g. 512, 1024, 2048 tokens).
|
| 14 |
+
- **Multi-Subject Scaling:** Load up to 8 distinct RefMods simultaneously (`mod_1` through `mod_8`) with independent strengths.
|
| 15 |
+
- **Manifold Blending:** Smooth weakening and strength attenuation using spatial low-pass filtering along the latent manifold instead of noise degradation.
|
| 16 |
+
- **Universal Compatibility:** Works with any standard ComfyUI `CONDITIONING` graph for FLUX.2, Klein 4B, Klein 8B, and Klein 9B models.
|
| 17 |
+
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
## 🚀 Installation
|
| 21 |
+
|
| 22 |
+
1. Navigate to your ComfyUI `custom_nodes` folder:
|
| 23 |
+
```bash
|
| 24 |
+
cd ComfyUI/custom_nodes
|
| 25 |
+
```
|
| 26 |
+
2. Clone or place this repository:
|
| 27 |
+
```bash
|
| 28 |
+
git clone https://github.com/malcolmrey/ComfyUI-Flux2Klein9Mod.git
|
| 29 |
+
```
|
| 30 |
+
3. Ensure the model folder exists:
|
| 31 |
+
```text
|
| 32 |
+
ComfyUI/models/refmods-klein9/
|
| 33 |
+
```
|
| 34 |
+
4. Restart ComfyUI.
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
## 🧩 Nodes
|
| 39 |
+
|
| 40 |
+
| Node Name | Category | Description |
|
| 41 |
+
| :--- | :--- | :--- |
|
| 42 |
+
| **`Load Klein9 RefMods (FLUX.2)`** (`Klein9RefModsLoader`) | `model/conditioning/klein9` | Loads 1–8 RefMod `.safetensors` files from `models/refmods-klein9/` with individual strengths (0.0–3.0) and repeat counts. |
|
| 43 |
+
| **`Apply Klein9 RefMods (FLUX.2)`** (`Klein9RefModApply`) | `model/conditioning/klein9` | Injects the loaded RefMod bundle into standard ComfyUI `CONDITIONING` (`reference_latents`). |
|
| 44 |
+
| **`Extract Klein9 RefMod (FLUX.2)`** (`Klein9RefModExtract`) | `model/conditioning/klein9` | In-graph VAE encode & token compression of input images directly into a saved `.safetensors` file in `models/refmods-klein9/`. |
|
| 45 |
+
| **`Load RefMod Folder (Images)`** (`Klein9RefModFolderLoader`) | `model/conditioning/klein9` | Batch loads an entire folder of reference images for extraction. |
|
| 46 |
+
|
| 47 |
+
---
|
| 48 |
+
|
| 49 |
+
## 🛠️ Graph Wiring
|
| 50 |
+
|
| 51 |
+
```text
|
| 52 |
+
[ CLIPTextEncode ] (Prompt)
|
| 53 |
+
│
|
| 54 |
+
▼
|
| 55 |
+
[ Apply Klein9 RefMods (FLUX.2) ] ◄── [ Load Klein9 RefMods (FLUX.2) ]
|
| 56 |
+
│ (conditioning out) (Selects models from models/refmods-klein9/)
|
| 57 |
+
▼
|
| 58 |
+
[ CFGGuider / SamplerCustomAdvanced ]
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
---
|
| 62 |
+
|
| 63 |
+
## 💻 CLI Extraction Tool
|
| 64 |
+
|
| 65 |
+
You can also pre-encode image datasets using the CLI:
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
python custom_nodes/ComfyUI-Flux2Klein9Mod/extract_klein9_mod.py \
|
| 69 |
+
--name fk9_aneta_v1_refmod \
|
| 70 |
+
--dataset-dir C:/Development/ai-toolkit/datasets/aneta \
|
| 71 |
+
--concept-type identity \
|
| 72 |
+
--token-budget 1024 \
|
| 73 |
+
--output-dir C:/Development/ComfyUI/models/refmods-klein9/
|
| 74 |
+
```
|
klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ComfyUI-Flux2Klein9Mod — No-training "RefMod" reference adapters for FLUX.2 & Klein9
|
| 3 |
+
|
| 4 |
+
FLUX.2 and Klein9 accept reference image tokens directly within the packed sequence.
|
| 5 |
+
RefMods compress reference datasets/images into compact, pre-encoded latents (.safetensors)
|
| 6 |
+
stored in models/refmods-klein9/.
|
| 7 |
+
|
| 8 |
+
Nodes:
|
| 9 |
+
Klein9RefModsLoader — Load 1-8 pre-extracted RefMods from models/refmods-klein9/
|
| 10 |
+
Klein9RefModApply — Inject RefMods bundle into standard ComfyUI CONDITIONING
|
| 11 |
+
Klein9RefModExtract — In-graph VAE encode & compression -> saved .safetensors in models/refmods-klein9/
|
| 12 |
+
Klein9RefModFolderLoader — Batch load reference images from a disk folder
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
__author__ = "malcolmrey"
|
| 16 |
+
__version__ = "1.0.0"
|
| 17 |
+
|
| 18 |
+
from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
| 19 |
+
|
| 20 |
+
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/common.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helpers for the Klein9 RefMod pack: media loading and models/refmods-klein9 folder."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from typing import List, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def refmods_klein9_dir() -> str:
|
| 14 |
+
"""ComfyUI models/refmods-klein9 — the mod storage folder for Flux2 / Klein9.
|
| 15 |
+
|
| 16 |
+
Sits next to loras/, unet/, checkpoints/, and refmods/.
|
| 17 |
+
"""
|
| 18 |
+
import folder_paths
|
| 19 |
+
d = os.path.join(folder_paths.models_dir, "refmods-klein9")
|
| 20 |
+
os.makedirs(d, exist_ok=True)
|
| 21 |
+
return d
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def list_media_files(folder: str) -> List[str]:
|
| 25 |
+
"""List image files directly under folder (top level only), sorted by name."""
|
| 26 |
+
images = []
|
| 27 |
+
if os.path.isdir(folder):
|
| 28 |
+
for fn in sorted(os.listdir(folder)):
|
| 29 |
+
ext = os.path.splitext(fn)[1].lower()
|
| 30 |
+
p = os.path.join(folder, fn)
|
| 31 |
+
if os.path.isfile(p) and ext in IMAGE_EXTS:
|
| 32 |
+
images.append(p)
|
| 33 |
+
return images
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_image_file(path: str, max_edge: Optional[int] = None) -> torch.Tensor:
|
| 37 |
+
"""Load one image file -> [1, H, W, 3] float32 in [0, 1]."""
|
| 38 |
+
import numpy as np
|
| 39 |
+
from PIL import Image
|
| 40 |
+
with Image.open(path) as img:
|
| 41 |
+
img = img.convert("RGB")
|
| 42 |
+
w, h = img.size
|
| 43 |
+
if max_edge is not None:
|
| 44 |
+
scale = min(1.0, max_edge / max(w, h))
|
| 45 |
+
if scale < 1.0:
|
| 46 |
+
img = img.resize((max(1, round(w * scale)), max(1, round(h * scale))),
|
| 47 |
+
Image.LANCZOS)
|
| 48 |
+
arr = torch.from_numpy(np.asarray(img).copy()).float() / 255.0
|
| 49 |
+
return arr.unsqueeze(0) # [1, H, W, 3]
|
klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/core.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
core.py — "RefMod" reference adapter engine for FLUX.2 and Klein9
|
| 3 |
+
|
| 4 |
+
FLUX.2 / Klein9 injects reference image tokens directly into the joint sequence:
|
| 5 |
+
the reference image is VAE-encoded, patchified (patch_size=2), and positioned on
|
| 6 |
+
the 2D RoPE coordinate grid alongside text tokens and noisy latent tokens.
|
| 7 |
+
|
| 8 |
+
Standard reference workflows encode raw high-resolution images live on every run,
|
| 9 |
+
which generates thousands of tokens (e.g. 1024x1024 -> 4096 tokens) per reference image,
|
| 10 |
+
causing high VRAM consumption and quadratic self-attention latency.
|
| 11 |
+
|
| 12 |
+
A Klein9 RefMod pre-encodes reference imagery once into a compact, pre-computed
|
| 13 |
+
latent adapter (.safetensors) stored in models/refmods-klein9/:
|
| 14 |
+
* The reference is VAE-encoded to its latent representation [B, C, H, W].
|
| 15 |
+
* Optionally, the latent is spatial-pooled/compressed to a targeted token budget
|
| 16 |
+
(e.g., 512, 1024, 2048 tokens, or native full resolution).
|
| 17 |
+
* At inference time, the pre-computed latents are injected into CONDITIONING
|
| 18 |
+
under the model's native reference_latents key instantly with zero VAE latency.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import math
|
| 25 |
+
import os
|
| 26 |
+
from dataclasses import dataclass, field
|
| 27 |
+
from typing import Dict, List, Optional, Tuple
|
| 28 |
+
|
| 29 |
+
import torch
|
| 30 |
+
import torch.nn.functional as F
|
| 31 |
+
from safetensors import safe_open
|
| 32 |
+
from safetensors.torch import load_file, save_file
|
| 33 |
+
|
| 34 |
+
META_KEY = "klein9_refmod_meta"
|
| 35 |
+
|
| 36 |
+
CONCEPT_TYPES = (
|
| 37 |
+
"identity", # a specific person/character face/body
|
| 38 |
+
"style", # artistic style, color grading, illustration aesthetic
|
| 39 |
+
"character", # fictional character, costume, anatomy
|
| 40 |
+
"clothing", # specific outfit, garment, textures
|
| 41 |
+
"background", # environment, lighting, backdrop plate
|
| 42 |
+
"generic", # mixed / multi-concept
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
TOKEN_BUDGETS = (
|
| 46 |
+
"native", # full uncompressed VAE resolution
|
| 47 |
+
"4096", # ~1024x1024 equivalent
|
| 48 |
+
"2048", # ~724x724 equivalent
|
| 49 |
+
"1024", # ~512x512 equivalent (fast & high fidelity)
|
| 50 |
+
"512", # ~362x362 equivalent (ultra lightweight)
|
| 51 |
+
"256", # ~256x256 equivalent
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class Klein9RefMod:
|
| 57 |
+
name: str
|
| 58 |
+
samples: torch.Tensor # [B, C, H, W]
|
| 59 |
+
concept_type: str = "identity"
|
| 60 |
+
mode: str = "encode" # "encode" (native) or "pooled"
|
| 61 |
+
resolution: int = 1024
|
| 62 |
+
token_budget: int = 1024
|
| 63 |
+
meta: Dict = field(default_factory=dict)
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def token_count(self) -> int:
|
| 67 |
+
"""Approximate patchified token count (assuming patch_size=2)."""
|
| 68 |
+
if self.samples.dim() == 4:
|
| 69 |
+
b, c, h, w = self.samples.shape
|
| 70 |
+
return (h // 2) * (w // 2) * b
|
| 71 |
+
return self.samples.numel() // (16 * 4)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _blur_latent(z: torch.Tensor, factor: int = 8) -> torch.Tensor:
|
| 75 |
+
"""Spatial low-pass filter (downsample then upsample) on the latent manifold.
|
| 76 |
+
|
| 77 |
+
Used when applying reference strength < 1.0. Mixing toward a blurred copy
|
| 78 |
+
preserves smooth latent correlations rather than injecting Gaussian noise artifacts.
|
| 79 |
+
"""
|
| 80 |
+
if z.dim() != 4:
|
| 81 |
+
return z
|
| 82 |
+
b, c, h, w = z.shape
|
| 83 |
+
sh, sw = max(1, h // factor), max(1, w // factor)
|
| 84 |
+
down = F.adaptive_avg_pool2d(z.float(), (sh, sw))
|
| 85 |
+
up = F.interpolate(down, size=(h, w), mode="bilinear", align_corners=False)
|
| 86 |
+
return up.to(z.dtype)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def pool_latent_to_budget(z: torch.Tensor, target_tokens: int, patch_size: int = 2) -> torch.Tensor:
|
| 90 |
+
"""Adaptively downsample latent spatial dimensions to match a target token budget."""
|
| 91 |
+
if z.dim() != 4:
|
| 92 |
+
return z
|
| 93 |
+
b, c, h, w = z.shape
|
| 94 |
+
current_tokens = (h // patch_size) * (w // patch_size)
|
| 95 |
+
if current_tokens <= target_tokens or target_tokens <= 0:
|
| 96 |
+
return z
|
| 97 |
+
|
| 98 |
+
aspect = w / max(1, h)
|
| 99 |
+
# target_tokens = (th / 2) * (tw / 2) = (th / 2) * (th * aspect / 2) = th^2 * aspect / 4
|
| 100 |
+
th = max(patch_size, int(round(math.sqrt((target_tokens * (patch_size ** 2)) / aspect))))
|
| 101 |
+
tw = max(patch_size, int(round(th * aspect)))
|
| 102 |
+
|
| 103 |
+
# Ensure divisible by patch_size
|
| 104 |
+
th = max(patch_size, (th // patch_size) * patch_size)
|
| 105 |
+
tw = max(patch_size, (tw // patch_size) * patch_size)
|
| 106 |
+
|
| 107 |
+
down = F.adaptive_avg_pool2d(z.float(), (th, tw))
|
| 108 |
+
return down.to(z.dtype)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def fit_token_budget(z: torch.Tensor, budget_str: str, patch_size: int = 2) -> torch.Tensor:
|
| 112 |
+
"""Pool or keep latent according to the specified token budget setting."""
|
| 113 |
+
if budget_str == "native" or not budget_str:
|
| 114 |
+
return z
|
| 115 |
+
try:
|
| 116 |
+
budget_int = int(budget_str)
|
| 117 |
+
return pool_latent_to_budget(z, budget_int, patch_size=patch_size)
|
| 118 |
+
except (ValueError, TypeError):
|
| 119 |
+
return z
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def read_refmod_meta(path_no_ext: str) -> Optional[Dict]:
|
| 123 |
+
"""Read metadata block from a .safetensors file without loading tensor payloads."""
|
| 124 |
+
path = path_no_ext if path_no_ext.endswith(".safetensors") else path_no_ext + ".safetensors"
|
| 125 |
+
if not os.path.isfile(path):
|
| 126 |
+
return None
|
| 127 |
+
try:
|
| 128 |
+
with safe_open(path, framework="pt", device="cpu") as f:
|
| 129 |
+
raw_meta = f.metadata()
|
| 130 |
+
if raw_meta and META_KEY in raw_meta:
|
| 131 |
+
try:
|
| 132 |
+
return json.loads(raw_meta[META_KEY])
|
| 133 |
+
except Exception:
|
| 134 |
+
pass
|
| 135 |
+
except Exception:
|
| 136 |
+
pass
|
| 137 |
+
return None
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def save_refmod(mod: Klein9RefMod, out_path: str) -> str:
|
| 141 |
+
"""Save a Klein9RefMod to a .safetensors file with embedded JSON metadata."""
|
| 142 |
+
if not out_path.endswith(".safetensors"):
|
| 143 |
+
out_path += ".safetensors"
|
| 144 |
+
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
| 145 |
+
|
| 146 |
+
header_meta = {
|
| 147 |
+
"name": mod.name,
|
| 148 |
+
"concept_type": mod.concept_type,
|
| 149 |
+
"mode": mod.mode,
|
| 150 |
+
"resolution": mod.resolution,
|
| 151 |
+
"token_budget": mod.token_budget,
|
| 152 |
+
"token_count": mod.token_count,
|
| 153 |
+
"channels": mod.samples.shape[1] if mod.samples.dim() >= 2 else 16,
|
| 154 |
+
"shape": list(mod.samples.shape),
|
| 155 |
+
"generator": "ComfyUI-Flux2Klein9Mod",
|
| 156 |
+
}
|
| 157 |
+
if mod.meta:
|
| 158 |
+
header_meta.update(mod.meta)
|
| 159 |
+
|
| 160 |
+
tensors = {
|
| 161 |
+
"samples": mod.samples.contiguous().to(torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16)
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
save_file(tensors, out_path, metadata={META_KEY: json.dumps(header_meta)})
|
| 165 |
+
return out_path
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def load_refmod(path: str, device: str = "cpu") -> Klein9RefMod:
|
| 169 |
+
"""Load a Klein9RefMod from a .safetensors file."""
|
| 170 |
+
if not path.endswith(".safetensors"):
|
| 171 |
+
path += ".safetensors"
|
| 172 |
+
if not os.path.isfile(path):
|
| 173 |
+
raise FileNotFoundError(f"Klein9 RefMod file not found: {path}")
|
| 174 |
+
|
| 175 |
+
meta = read_refmod_meta(path) or {}
|
| 176 |
+
tensors = load_file(path, device=device)
|
| 177 |
+
samples = tensors.get("samples")
|
| 178 |
+
if samples is None:
|
| 179 |
+
raise ValueError(f"Invalid RefMod: 'samples' tensor missing in {path}")
|
| 180 |
+
|
| 181 |
+
name = meta.get("name", os.path.splitext(os.path.basename(path))[0])
|
| 182 |
+
concept_type = meta.get("concept_type", "identity")
|
| 183 |
+
mode = meta.get("mode", "encode")
|
| 184 |
+
resolution = meta.get("resolution", 1024)
|
| 185 |
+
token_budget = meta.get("token_budget", 1024)
|
| 186 |
+
|
| 187 |
+
return Klein9RefMod(
|
| 188 |
+
name=name,
|
| 189 |
+
samples=samples,
|
| 190 |
+
concept_type=concept_type,
|
| 191 |
+
mode=mode,
|
| 192 |
+
resolution=resolution,
|
| 193 |
+
token_budget=token_budget,
|
| 194 |
+
meta=meta
|
| 195 |
+
)
|
klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/extract_klein9_mod.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
extract_klein9_mod.py — CLI tool to extract FLUX.2 / Klein9 RefMod (.safetensors) from reference images.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
python extract_klein9_mod.py \
|
| 7 |
+
--vae path/to/flux2_vae.safetensors \
|
| 8 |
+
--name fk9_aneta_v1_refmod \
|
| 9 |
+
--dataset-dir C:/Development/ai-toolkit/datasets/aneta \
|
| 10 |
+
--concept-type identity \
|
| 11 |
+
--token-budget 1024 \
|
| 12 |
+
--output-dir C:/Development/ComfyUI/models/refmods-klein9/
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import glob
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
# Ensure ComfyUI and custom_nodes in sys.path
|
| 22 |
+
COMFY_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 23 |
+
if COMFY_ROOT not in sys.path:
|
| 24 |
+
sys.path.insert(0, COMFY_ROOT)
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
from PIL import Image
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
import comfy.sd
|
| 31 |
+
import comfy.utils
|
| 32 |
+
import comfy.model_management
|
| 33 |
+
except ImportError:
|
| 34 |
+
print("[Warning] Running outside ComfyUI root; ensure ComfyUI dependencies are installed.")
|
| 35 |
+
|
| 36 |
+
from core import (
|
| 37 |
+
CONCEPT_TYPES,
|
| 38 |
+
TOKEN_BUDGETS,
|
| 39 |
+
Klein9RefMod,
|
| 40 |
+
fit_token_budget,
|
| 41 |
+
save_refmod,
|
| 42 |
+
)
|
| 43 |
+
from common import load_image_file, list_media_files, refmods_klein9_dir
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def main():
|
| 47 |
+
parser = argparse.ArgumentParser(description="Extract FLUX.2 / Klein9 RefMod reference adapter from images")
|
| 48 |
+
parser.add_argument("--vae", type=str, default=None, help="Path to FLUX.2 / Klein VAE .safetensors file")
|
| 49 |
+
parser.add_argument("--name", type=str, required=True, help="RefMod output name (e.g. fk9_aneta_v1_refmod)")
|
| 50 |
+
parser.add_argument("--dataset-dir", type=str, default=None, help="Directory containing reference images")
|
| 51 |
+
parser.add_argument("--images", nargs="+", default=None, help="Explicit list of image paths")
|
| 52 |
+
parser.add_argument("--concept-type", type=str, default="identity", choices=CONCEPT_TYPES, help="Mod concept type")
|
| 53 |
+
parser.add_argument("--token-budget", type=str, default="1024", choices=TOKEN_BUDGETS, help="Target token budget per image")
|
| 54 |
+
parser.add_argument("--resolution", type=int, default=1024, help="Max image edge resolution")
|
| 55 |
+
parser.add_argument("--max-images", type=int, default=16, help="Max images to encode from dataset")
|
| 56 |
+
parser.add_argument("--output-dir", type=str, default=None, help="Output folder (defaults to models/refmods-klein9/)")
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
|
| 59 |
+
# 1. Collect images
|
| 60 |
+
image_paths = []
|
| 61 |
+
if args.images:
|
| 62 |
+
image_paths.extend(args.images)
|
| 63 |
+
if args.dataset_dir:
|
| 64 |
+
image_paths.extend(list_media_files(args.dataset_dir))
|
| 65 |
+
|
| 66 |
+
if not image_paths:
|
| 67 |
+
print(f"[Error] No images found. Provide --dataset-dir or --images.")
|
| 68 |
+
sys.exit(1)
|
| 69 |
+
|
| 70 |
+
image_paths = image_paths[:args.max_images]
|
| 71 |
+
print(f"Found {len(image_paths)} reference images for RefMod '{args.name}'.")
|
| 72 |
+
|
| 73 |
+
# 2. Setup output path
|
| 74 |
+
out_dir = args.output_dir or refmods_klein9_dir()
|
| 75 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 76 |
+
out_path = os.path.join(out_dir, f"{args.name}.safetensors")
|
| 77 |
+
|
| 78 |
+
# 3. Load VAE
|
| 79 |
+
device = comfy.model_management.get_torch_device() if hasattr(comfy, "model_management") else torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 80 |
+
vae_path = args.vae
|
| 81 |
+
|
| 82 |
+
if not vae_path:
|
| 83 |
+
# Search for default Flux2 / Klein VAE in models/vae
|
| 84 |
+
default_vae_dir = os.path.join(COMFY_ROOT, "models", "vae")
|
| 85 |
+
candidates = glob.glob(os.path.join(default_vae_dir, "*flux*.safetensors")) + glob.glob(os.path.join(default_vae_dir, "*klein*.safetensors")) + glob.glob(os.path.join(default_vae_dir, "*.safetensors"))
|
| 86 |
+
if candidates:
|
| 87 |
+
vae_path = candidates[0]
|
| 88 |
+
print(f"Auto-selected VAE: {vae_path}")
|
| 89 |
+
else:
|
| 90 |
+
print("[Error] No VAE path provided and none found in models/vae/.")
|
| 91 |
+
sys.exit(1)
|
| 92 |
+
|
| 93 |
+
print(f"Loading VAE from {vae_path}...")
|
| 94 |
+
vae = comfy.sd.VAE(sd=comfy.utils.load_torch_file(vae_path))
|
| 95 |
+
|
| 96 |
+
# 4. Load and process images
|
| 97 |
+
print("Loading and preprocessing images...")
|
| 98 |
+
loaded_tensors = []
|
| 99 |
+
for p in image_paths:
|
| 100 |
+
t = load_image_file(p, max_edge=args.resolution)
|
| 101 |
+
loaded_tensors.append(t)
|
| 102 |
+
|
| 103 |
+
# 5. VAE Encode (One by one to avoid VRAM OOM)
|
| 104 |
+
print(f"Encoding {len(loaded_tensors)} images through VAE on {device}...")
|
| 105 |
+
encoded_latents = []
|
| 106 |
+
for idx, img_t in enumerate(loaded_tensors):
|
| 107 |
+
with torch.no_grad():
|
| 108 |
+
encoded = vae.encode(img_t[:, :, :, :3])
|
| 109 |
+
lat = encoded["samples"] if isinstance(encoded, dict) else encoded
|
| 110 |
+
# Token Budget Compression per image
|
| 111 |
+
if args.token_budget != "native":
|
| 112 |
+
lat = fit_token_budget(lat, args.token_budget, patch_size=2)
|
| 113 |
+
encoded_latents.append(lat)
|
| 114 |
+
|
| 115 |
+
samples = torch.cat(encoded_latents, dim=0)
|
| 116 |
+
|
| 117 |
+
# 7. Construct & Save RefMod
|
| 118 |
+
mod = Klein9RefMod(
|
| 119 |
+
name=args.name,
|
| 120 |
+
samples=samples,
|
| 121 |
+
concept_type=args.concept_type,
|
| 122 |
+
mode="pooled" if args.token_budget != "native" else "encode",
|
| 123 |
+
resolution=args.resolution,
|
| 124 |
+
token_budget=int(args.token_budget) if args.token_budget != "native" else samples.shape[-2] * samples.shape[-1] // 4,
|
| 125 |
+
meta={
|
| 126 |
+
"source_images_count": len(image_paths),
|
| 127 |
+
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 128 |
+
"vae_source": os.path.basename(vae_path)
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
final_path = save_refmod(mod, out_path)
|
| 133 |
+
file_size_kb = os.path.getsize(final_path) / 1024
|
| 134 |
+
print(f"\n=======================================================")
|
| 135 |
+
print(f"FLUX.2 / Klein9 RefMod Extracted Successfully!")
|
| 136 |
+
print(f"File: {final_path}")
|
| 137 |
+
print(f"Size: {file_size_kb:.1f} KB")
|
| 138 |
+
print(f"Latent Shape: {list(mod.samples.shape)}")
|
| 139 |
+
print(f"Tokens: {mod.token_count} tokens")
|
| 140 |
+
print(f"Concept Type: {mod.concept_type}")
|
| 141 |
+
print(f"=======================================================\n")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
main()
|
klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/nodes.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
nodes.py — ComfyUI nodes for FLUX.2 & Klein9 "RefMod" reference adapters
|
| 3 |
+
|
| 4 |
+
Nodes:
|
| 5 |
+
Klein9RefModsLoader — Load 1-8 pre-extracted RefMods from models/refmods-klein9/
|
| 6 |
+
Klein9RefModApply — Inject RefMods bundle into standard ComfyUI CONDITIONING
|
| 7 |
+
Klein9RefModExtract — In-graph VAE encode & compression -> saved .safetensors in models/refmods-klein9/
|
| 8 |
+
Klein9RefModFolderLoader — Batch load reference images from a disk folder
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import time
|
| 15 |
+
from typing import Dict, List, Optional, Tuple
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
|
| 20 |
+
import folder_paths
|
| 21 |
+
import node_helpers
|
| 22 |
+
from comfy_api.latest import io
|
| 23 |
+
|
| 24 |
+
from .common import (
|
| 25 |
+
list_media_files,
|
| 26 |
+
load_image_file,
|
| 27 |
+
refmods_klein9_dir,
|
| 28 |
+
)
|
| 29 |
+
from .core import (
|
| 30 |
+
CONCEPT_TYPES,
|
| 31 |
+
TOKEN_BUDGETS,
|
| 32 |
+
Klein9RefMod,
|
| 33 |
+
_blur_latent,
|
| 34 |
+
fit_token_budget,
|
| 35 |
+
load_refmod,
|
| 36 |
+
read_refmod_meta,
|
| 37 |
+
save_refmod,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# Register models/refmods-klein9 with ComfyUI's model path system
|
| 41 |
+
try:
|
| 42 |
+
folder_paths.add_model_folder_path("refmods-klein9", refmods_klein9_dir())
|
| 43 |
+
except Exception:
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
_MOD_CACHE: Dict[str, Klein9RefMod] = {}
|
| 47 |
+
_MOD_CACHE_MAX = 32
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _list_klein9_mod_names() -> List[str]:
|
| 51 |
+
"""List all .safetensors mod files available in models/refmods-klein9/."""
|
| 52 |
+
mods_dir = refmods_klein9_dir()
|
| 53 |
+
if not os.path.isdir(mods_dir):
|
| 54 |
+
return ["none"]
|
| 55 |
+
files = []
|
| 56 |
+
for fn in sorted(os.listdir(mods_dir)):
|
| 57 |
+
if fn.lower().endswith(".safetensors"):
|
| 58 |
+
files.append(os.path.splitext(fn)[0])
|
| 59 |
+
return ["none"] + files if files else ["none"]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _get_or_load_mod(mod_name: str) -> Optional[Klein9RefMod]:
|
| 63 |
+
"""Retrieve mod from in-memory cache or load from models/refmods-klein9/."""
|
| 64 |
+
if not mod_name or mod_name == "none":
|
| 65 |
+
return None
|
| 66 |
+
if mod_name in _MOD_CACHE:
|
| 67 |
+
return _MOD_CACHE[mod_name]
|
| 68 |
+
|
| 69 |
+
mods_dir = refmods_klein9_dir()
|
| 70 |
+
path = os.path.join(mods_dir, mod_name + ".safetensors")
|
| 71 |
+
if not os.path.isfile(path):
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
mod = load_refmod(path)
|
| 75 |
+
if len(_MOD_CACHE) >= _MOD_CACHE_MAX:
|
| 76 |
+
# Simple FIFO eviction
|
| 77 |
+
oldest_key = next(iter(_MOD_CACHE))
|
| 78 |
+
_MOD_CACHE.pop(oldest_key, None)
|
| 79 |
+
|
| 80 |
+
_MOD_CACHE[mod_name] = mod
|
| 81 |
+
return mod
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 85 |
+
# 1. Klein9RefModsLoader
|
| 86 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 87 |
+
|
| 88 |
+
class Klein9RefModsLoader:
|
| 89 |
+
"""Load up to 8 pre-encoded FLUX.2 / Klein9 RefMods with individual strength dials."""
|
| 90 |
+
|
| 91 |
+
@classmethod
|
| 92 |
+
def INPUT_TYPES(cls):
|
| 93 |
+
mod_choices = _list_klein9_mod_names()
|
| 94 |
+
inputs = {
|
| 95 |
+
"required": {
|
| 96 |
+
"mod_1": (mod_choices, {"default": mod_choices[0] if mod_choices else "none"}),
|
| 97 |
+
"strength_1": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 3.0, "step": 0.05}),
|
| 98 |
+
"copies_1": ("INT", {"default": 1, "min": 1, "max": 8, "step": 1}),
|
| 99 |
+
},
|
| 100 |
+
"optional": {}
|
| 101 |
+
}
|
| 102 |
+
for i in range(2, 9):
|
| 103 |
+
inputs["optional"][f"mod_{i}"] = (mod_choices, {"default": "none"})
|
| 104 |
+
inputs["optional"][f"strength_{i}"] = ("FLOAT", {"default": 1.0, "min": 0.0, "max": 3.0, "step": 0.05})
|
| 105 |
+
inputs["optional"][f"copies_{i}"] = ("INT", {"default": 1, "min": 1, "max": 8, "step": 1})
|
| 106 |
+
|
| 107 |
+
return inputs
|
| 108 |
+
|
| 109 |
+
RETURN_TYPES = ("KLEIN9_REFMODS", "STRING")
|
| 110 |
+
RETURN_NAMES = ("klein9_refmods", "prompt_hint")
|
| 111 |
+
FUNCTION = "load_mods"
|
| 112 |
+
CATEGORY = "model/conditioning/klein9"
|
| 113 |
+
|
| 114 |
+
def load_mods(self, **kwargs):
|
| 115 |
+
bundle = []
|
| 116 |
+
hint_parts = []
|
| 117 |
+
|
| 118 |
+
for i in range(1, 9):
|
| 119 |
+
mod_name = kwargs.get(f"mod_{i}", "none")
|
| 120 |
+
strength = float(kwargs.get(f"strength_{i}", 1.0))
|
| 121 |
+
copies = int(kwargs.get(f"copies_{i}", 1))
|
| 122 |
+
|
| 123 |
+
if mod_name and mod_name != "none":
|
| 124 |
+
mod = _get_or_load_mod(mod_name)
|
| 125 |
+
if mod is not None:
|
| 126 |
+
bundle.append((mod, strength, copies))
|
| 127 |
+
hint_parts.append(f"[{mod.concept_type}: {mod.name} @ {strength:.2f}x ({mod.token_count} tokens)]")
|
| 128 |
+
|
| 129 |
+
prompt_hint = " • ".join(hint_parts) if hint_parts else "No Klein9 RefMods loaded"
|
| 130 |
+
return (bundle, prompt_hint)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 134 |
+
# 2. Klein9RefModApply
|
| 135 |
+
# ════════════════════════════════════��══════════════════════════════════════
|
| 136 |
+
|
| 137 |
+
class Klein9RefModApply:
|
| 138 |
+
"""Inject pre-encoded Klein9 RefMod reference latents into standard ComfyUI CONDITIONING."""
|
| 139 |
+
|
| 140 |
+
@classmethod
|
| 141 |
+
def INPUT_TYPES(cls):
|
| 142 |
+
return {
|
| 143 |
+
"required": {
|
| 144 |
+
"conditioning": ("CONDITIONING",),
|
| 145 |
+
"klein9_refmods": ("KLEIN9_REFMODS",),
|
| 146 |
+
"retention": ([
|
| 147 |
+
"fully_preserved (1.0)",
|
| 148 |
+
"partially_preserved (0.7)",
|
| 149 |
+
"attribute_transfer (0.4)",
|
| 150 |
+
"weak_reference (0.2)",
|
| 151 |
+
"custom_multiplier",
|
| 152 |
+
], {"default": "fully_preserved (1.0)"}),
|
| 153 |
+
"custom_retention": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
|
| 154 |
+
"ref_method": (["default", "index", "uxo", "index_timestep_zero"], {"default": "default"}),
|
| 155 |
+
"blend_mode": (["manifold_blur", "direct_scale"], {"default": "manifold_blur"}),
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
RETURN_TYPES = ("CONDITIONING",)
|
| 160 |
+
RETURN_NAMES = ("conditioning",)
|
| 161 |
+
FUNCTION = "apply_mods"
|
| 162 |
+
CATEGORY = "model/conditioning/klein9"
|
| 163 |
+
|
| 164 |
+
def apply_mods(self, conditioning, klein9_refmods, retention, custom_retention=1.0,
|
| 165 |
+
ref_method="default", blend_mode="manifold_blur"):
|
| 166 |
+
if not klein9_refmods:
|
| 167 |
+
return (conditioning,)
|
| 168 |
+
|
| 169 |
+
# Parse master retention factor
|
| 170 |
+
if "1.0" in retention:
|
| 171 |
+
master_mult = 1.0
|
| 172 |
+
elif "0.7" in retention:
|
| 173 |
+
master_mult = 0.7
|
| 174 |
+
elif "0.4" in retention:
|
| 175 |
+
master_mult = 0.4
|
| 176 |
+
elif "0.2" in retention:
|
| 177 |
+
master_mult = 0.2
|
| 178 |
+
else:
|
| 179 |
+
master_mult = float(custom_retention)
|
| 180 |
+
|
| 181 |
+
extracted_latents = []
|
| 182 |
+
|
| 183 |
+
for mod, row_strength, copies in klein9_refmods:
|
| 184 |
+
effective_strength = float(row_strength) * master_mult
|
| 185 |
+
if effective_strength <= 0.001:
|
| 186 |
+
continue
|
| 187 |
+
|
| 188 |
+
raw_samples = mod.samples.clone() # [B, C, H, W]
|
| 189 |
+
|
| 190 |
+
# Apply strength weighting along latent manifold
|
| 191 |
+
if effective_strength < 0.999:
|
| 192 |
+
if blend_mode == "manifold_blur":
|
| 193 |
+
# Blur factor proportional to weakening
|
| 194 |
+
blur_factor = max(2, int(round(8.0 * (1.0 - effective_strength) + 2.0)))
|
| 195 |
+
blurred = _blur_latent(raw_samples, factor=blur_factor)
|
| 196 |
+
scaled_samples = (effective_strength * raw_samples) + ((1.0 - effective_strength) * blurred)
|
| 197 |
+
else:
|
| 198 |
+
scaled_samples = raw_samples * effective_strength
|
| 199 |
+
elif effective_strength > 1.001:
|
| 200 |
+
scaled_samples = raw_samples * effective_strength
|
| 201 |
+
else:
|
| 202 |
+
scaled_samples = raw_samples
|
| 203 |
+
|
| 204 |
+
# Append samples (unroll batch if multiple images inside one mod)
|
| 205 |
+
for _ in range(copies):
|
| 206 |
+
if scaled_samples.dim() == 4:
|
| 207 |
+
for b in range(scaled_samples.shape[0]):
|
| 208 |
+
extracted_latents.append(scaled_samples[b:b+1])
|
| 209 |
+
else:
|
| 210 |
+
extracted_latents.append(scaled_samples)
|
| 211 |
+
|
| 212 |
+
if not extracted_latents:
|
| 213 |
+
return (conditioning,)
|
| 214 |
+
|
| 215 |
+
# Inject into conditioning dictionary
|
| 216 |
+
cond_values = {"reference_latents": extracted_latents}
|
| 217 |
+
if ref_method != "default":
|
| 218 |
+
cond_values["reference_latents_method"] = ref_method
|
| 219 |
+
|
| 220 |
+
updated_cond = node_helpers.conditioning_set_values(conditioning, cond_values, append=True)
|
| 221 |
+
return (updated_cond,)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 225 |
+
# 3. Klein9RefModExtract
|
| 226 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 227 |
+
|
| 228 |
+
class Klein9RefModExtract:
|
| 229 |
+
"""Encode reference images with FLUX.2/Klein VAE and save pre-computed RefMod (.safetensors)."""
|
| 230 |
+
|
| 231 |
+
@classmethod
|
| 232 |
+
def INPUT_TYPES(cls):
|
| 233 |
+
return {
|
| 234 |
+
"required": {
|
| 235 |
+
"images": ("IMAGE",),
|
| 236 |
+
"vae": ("VAE",),
|
| 237 |
+
"mod_name": ("STRING", {"default": "fk9_character_v1_refmod"}),
|
| 238 |
+
"concept_type": (list(CONCEPT_TYPES), {"default": "identity"}),
|
| 239 |
+
"token_budget": (list(TOKEN_BUDGETS), {"default": "1024"}),
|
| 240 |
+
"mode": (["encode", "pooled"], {"default": "encode"}),
|
| 241 |
+
},
|
| 242 |
+
"optional": {
|
| 243 |
+
"save_to_disk": ("BOOLEAN", {"default": True}),
|
| 244 |
+
"overwrite": ("BOOLEAN", {"default": True}),
|
| 245 |
+
}
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
RETURN_TYPES = ("KLEIN9_REFMODS", "LATENT", "STRING")
|
| 249 |
+
RETURN_NAMES = ("klein9_refmods", "latent", "saved_path")
|
| 250 |
+
FUNCTION = "extract_mod"
|
| 251 |
+
CATEGORY = "model/conditioning/klein9"
|
| 252 |
+
|
| 253 |
+
def extract_mod(self, images, vae, mod_name, concept_type="identity",
|
| 254 |
+
token_budget="1024", mode="encode", save_to_disk=True, overwrite=True):
|
| 255 |
+
clean_name = mod_name.strip()
|
| 256 |
+
if not clean_name:
|
| 257 |
+
clean_name = f"fk9_refmod_{int(time.time())}"
|
| 258 |
+
|
| 259 |
+
# 1. VAE Encode
|
| 260 |
+
# images is [B, H, W, 3] in [0, 1]
|
| 261 |
+
latent_dict = vae.encode(images[:, :, :, :3])
|
| 262 |
+
samples = latent_dict["samples"] # [B, C, H, W]
|
| 263 |
+
|
| 264 |
+
# 2. Token Budget Compression / Pooling
|
| 265 |
+
if mode == "pooled" or token_budget != "native":
|
| 266 |
+
samples = fit_token_budget(samples, token_budget, patch_size=2)
|
| 267 |
+
|
| 268 |
+
mod = Klein9RefMod(
|
| 269 |
+
name=clean_name,
|
| 270 |
+
samples=samples,
|
| 271 |
+
concept_type=concept_type,
|
| 272 |
+
mode=mode,
|
| 273 |
+
resolution=max(images.shape[1], images.shape[2]),
|
| 274 |
+
token_budget=int(token_budget) if token_budget != "native" else samples.shape[-2] * samples.shape[-1] // 4,
|
| 275 |
+
meta={"extracted_with": "Klein9RefModExtract", "source_batch_size": images.shape[0]}
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
saved_path = ""
|
| 279 |
+
if save_to_disk:
|
| 280 |
+
out_dir = refmods_klein9_dir()
|
| 281 |
+
target_path = os.path.join(out_dir, f"{clean_name}.safetensors")
|
| 282 |
+
if os.path.exists(target_path) and not overwrite:
|
| 283 |
+
target_path = os.path.join(out_dir, f"{clean_name}_{int(time.time())}.safetensors")
|
| 284 |
+
|
| 285 |
+
saved_path = save_refmod(mod, target_path)
|
| 286 |
+
# Update cache
|
| 287 |
+
_MOD_CACHE[clean_name] = mod
|
| 288 |
+
print(f"[Klein9RefModExtract] Successfully saved RefMod to {saved_path} ({mod.token_count} tokens)")
|
| 289 |
+
|
| 290 |
+
bundle = [(mod, 1.0, 1)]
|
| 291 |
+
return (bundle, {"samples": samples}, saved_path)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 295 |
+
# 4. Klein9RefModFolderLoader
|
| 296 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 297 |
+
|
| 298 |
+
class Klein9RefModFolderLoader:
|
| 299 |
+
"""Load an entire folder of reference stills as a batch for RefMod extraction."""
|
| 300 |
+
|
| 301 |
+
@classmethod
|
| 302 |
+
def INPUT_TYPES(cls):
|
| 303 |
+
return {
|
| 304 |
+
"required": {
|
| 305 |
+
"folder_path": ("STRING", {"default": "C:/Development/ai-toolkit/datasets/aneta"}),
|
| 306 |
+
"max_images": ("INT", {"default": 16, "min": 1, "max": 128, "step": 1}),
|
| 307 |
+
"max_edge": ("INT", {"default": 1024, "min": 256, "max": 2048, "step": 64}),
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
RETURN_TYPES = ("IMAGE", "INT")
|
| 312 |
+
RETURN_NAMES = ("images", "count")
|
| 313 |
+
FUNCTION = "load_folder"
|
| 314 |
+
CATEGORY = "model/conditioning/klein9"
|
| 315 |
+
|
| 316 |
+
def load_folder(self, folder_path, max_images=16, max_edge=1024):
|
| 317 |
+
image_paths = list_media_files(folder_path)
|
| 318 |
+
if not image_paths:
|
| 319 |
+
raise ValueError(f"No image files found in folder: {folder_path}")
|
| 320 |
+
|
| 321 |
+
image_paths = image_paths[:max_images]
|
| 322 |
+
loaded_tensors = []
|
| 323 |
+
for p in image_paths:
|
| 324 |
+
t = load_image_file(p, max_edge=max_edge)
|
| 325 |
+
loaded_tensors.append(t)
|
| 326 |
+
|
| 327 |
+
# Pad / batch images if dimensions vary
|
| 328 |
+
max_h = max(t.shape[1] for t in loaded_tensors)
|
| 329 |
+
max_w = max(t.shape[2] for t in loaded_tensors)
|
| 330 |
+
|
| 331 |
+
padded = []
|
| 332 |
+
for t in loaded_tensors:
|
| 333 |
+
h, w = t.shape[1], t.shape[2]
|
| 334 |
+
if h != max_h or w != max_w:
|
| 335 |
+
pad_h = max_h - h
|
| 336 |
+
pad_w = max_w - w
|
| 337 |
+
t_pad = F.pad(t.permute(0, 3, 1, 2), (0, pad_w, 0, pad_h), mode="replicate").permute(0, 2, 3, 1)
|
| 338 |
+
padded.append(t_pad)
|
| 339 |
+
else:
|
| 340 |
+
padded.append(t)
|
| 341 |
+
|
| 342 |
+
batch = torch.cat(padded, dim=0)
|
| 343 |
+
return (batch, len(padded))
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 347 |
+
# Class & Display Mappings
|
| 348 |
+
# ═══════════════════════════════════════════════════════════════════════════
|
| 349 |
+
|
| 350 |
+
NODE_CLASS_MAPPINGS = {
|
| 351 |
+
"Klein9RefModsLoader": Klein9RefModsLoader,
|
| 352 |
+
"Klein9RefModApply": Klein9RefModApply,
|
| 353 |
+
"Klein9RefModExtract": Klein9RefModExtract,
|
| 354 |
+
"Klein9RefModFolderLoader": Klein9RefModFolderLoader,
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 358 |
+
"Klein9RefModsLoader": "Load Klein9 RefMods (FLUX.2)",
|
| 359 |
+
"Klein9RefModApply": "Apply Klein9 RefMods (FLUX.2)",
|
| 360 |
+
"Klein9RefModExtract": "Extract Klein9 RefMod (FLUX.2)",
|
| 361 |
+
"Klein9RefModFolderLoader": "Load RefMod Folder (Images)",
|
| 362 |
+
}
|
klein9/comfyui/custom_nodes/ComfyUI-Flux2Klein9Mod/requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.0.0
|
| 2 |
+
safetensors>=0.4.0
|
| 3 |
+
Pillow>=9.0.0
|
| 4 |
+
numpy
|
klein9/docs/examples/Flux2-Klein9-AlisonBrie-5Col-Comparison-Grid.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-BrettCooper-5Col-Comparison-Grid.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-Gosia-5Col-Comparison-Grid.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-JodieFoster-5Col-Comparison-Grid.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-OliviaWilde-5Col-Comparison-Grid.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-AlisonBrie-Run1_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-AlisonBrie-Run2_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-AlisonBrie-Run3_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-BrettCooper-Run1_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-BrettCooper-Run2_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-BrettCooper-Run3_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-JodieFoster-Run1_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-JodieFoster-Run2_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-JodieFoster-Run3_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-OliviaWilde-Run1_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-OliviaWilde-Run2_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-OliviaWilde-Run3_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-RebeccaFerguson-Run1_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-RebeccaFerguson-Run2_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-RebeccaFerguson-Run3_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-SydneySweeney-Run1_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-SydneySweeney-Run2_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-PureLoRA10-SydneySweeney-Run3_00001_.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-RebeccaFerguson-5Col-Comparison-Grid.png
ADDED
|
Git LFS Details
|
klein9/docs/examples/Flux2-Klein9-SydneySweeney-5Col-Comparison-Grid.png
ADDED
|
Git LFS Details
|