Image-to-Image
Diffusion Single File
Safetensors
English
moss-image
tile
controlnet
lllite
image-restoration
comfyui
adapter
Instructions to use Xabsurd/MOSS-Image-Tile-Control with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusion Single File
How to use Xabsurd/MOSS-Image-Tile-Control with Diffusion Single File:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Add optional Color Guide and update nodes to v0.1.3
Browse filesRecommend updating for reference color preservation. Document decoder-feedback setup, parameters, extra VAE cost and possible loss of perceived sharpness. Synchronize node sources, ZIP and checksums; preserve all model weights and existing examples.
- ComfyUI-MOSS-LLLite.zip +2 -2
- ComfyUI-MOSS-LLLite/README.md +83 -0
- ComfyUI-MOSS-LLLite/__init__.py +4 -2
- ComfyUI-MOSS-LLLite/color_guide.py +115 -0
- ComfyUI-MOSS-LLLite/lllite_model.py +9 -1
- ComfyUI-MOSS-LLLite/lllite_nodes.py +59 -3
- ComfyUI-MOSS-LLLite/pyproject.toml +1 -1
- ComfyUI-MOSS-LLLite/tests/test_lllite_nodes.py +171 -0
- README.md +41 -3
- RESEARCH_REPORT.md +17 -0
- SHA256SUMS.txt +1 -1
ComfyUI-MOSS-LLLite.zip
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:752e77a44c7a7283cc31d31511fa890e2ff4ad38c80ae9f5393956574715e4ee
|
| 3 |
+
size 37824
|
ComfyUI-MOSS-LLLite/README.md
CHANGED
|
@@ -49,6 +49,89 @@ this controller's strength is zero.
|
|
| 49 |
The controller does not merge weights into the backbone. It uses ComfyUI's
|
| 50 |
ModelPatcher, additional-model loading, and block replacement interfaces.
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
## Compatibility and limitations
|
| 53 |
|
| 54 |
- Supports ordinary MOSS-Image generation. MOSS-Edit reference images and cached
|
|
|
|
| 49 |
The controller does not merge weights into the backbone. It uses ComfyUI's
|
| 50 |
ModelPatcher, additional-model loading, and block replacement interfaces.
|
| 51 |
|
| 52 |
+
## Experimental color guide
|
| 53 |
+
|
| 54 |
+
**Update recommended if preserving reference colors matters to your workflow.**
|
| 55 |
+
Existing MOSS-LLLite weights remain compatible; no model download is needed.
|
| 56 |
+
For a Git installation, run `git pull` in `custom_nodes/ComfyUI-MOSS-LLLite`,
|
| 57 |
+
then restart ComfyUI and refresh the browser. For a manual installation, replace
|
| 58 |
+
the node folder with the latest package before restarting.
|
| 59 |
+
|
| 60 |
+
**Apply MOSS Color Guide** corrects the final sampled latent using the colors
|
| 61 |
+
actually decoded by the supplied Flux2 VAE. It measures coarse RGB errors,
|
| 62 |
+
probes three calibrated color directions, and updates only those directions.
|
| 63 |
+
Local comparisons preserve generated texture substantially better than the
|
| 64 |
+
full-channel Reference Anchor. Brightness, contrast and some detail can still
|
| 65 |
+
change; exact RGB preservation is not guaranteed. This is inference color
|
| 66 |
+
compensation, not a repaired or retrained LLLite checkpoint. Texture can remain
|
| 67 |
+
visibly intact while reduced local contrast makes the image look slightly less
|
| 68 |
+
sharp. Compare both the overall image and native-size detail crops.
|
| 69 |
+
|
| 70 |
+
1. Resize the reference to the sampling resolution, in multiples of 16.
|
| 71 |
+
2. Connect this image to `image`, and **flux2-vae** to `vae`.
|
| 72 |
+
3. Connect **Apply MOSS-LLLite** to the guide's `model`, then the guide to the
|
| 73 |
+
sampler. Keep **Reference Anchor** disabled. Try strength `1`, grid `8`,
|
| 74 |
+
iterations `2`; reduce strength for a partial color correction.
|
| 75 |
+
4. Decode with the same VAE using ordinary **VAE Decode**. Tiled decoding can
|
| 76 |
+
introduce separate drift after correction.
|
| 77 |
+
|
| 78 |
+
| Parameter | Meaning | Starting point |
|
| 79 |
+
| --- | --- | --- |
|
| 80 |
+
| `strength` | Amount of color correction, independent of LLLite strength; `0` disables it | `1.0` for stronger color retention; try `0.8` if the result looks softer |
|
| 81 |
+
| `iterations` | Number of decoder-feedback correction rounds; more rounds cost more time | `2`; try `3` only for remaining color error |
|
| 82 |
+
| `grid_size` | Coarse color measurement grid, normally `grid_size × grid_size`; not image tiles | `8`; try `16` for local color shifts or small subjects on large canvases |
|
| 83 |
+
|
| 84 |
+
The guide is disabled by default. Strength `0` returns its input model
|
| 85 |
+
unchanged and skips calibration. Its strength is independent of LLLite: both
|
| 86 |
+
must be disabled to remove both reference constraints. Higher strength is not
|
| 87 |
+
always better. For small subjects on large canvases, inspect local color and
|
| 88 |
+
try grid `16`; a full-frame average can hide a local failure.
|
| 89 |
+
|
| 90 |
+
This costs additional time: calibration uses six small VAE encodes, followed
|
| 91 |
+
by `1 + 4 × iterations` full VAE decodes after sampling. In local private tests,
|
| 92 |
+
two iterations added about 3 seconds at 1.5 MP and 38 seconds at 9.5 MP; timings
|
| 93 |
+
depend on hardware, decoder settings and offloading. Increase to three iterations
|
| 94 |
+
only if the remaining color shift justifies the cost.
|
| 95 |
+
|
| 96 |
+
No additional weights are required. RGB is used to measure error; the correction
|
| 97 |
+
changes the latent, not the final decoded RGB pixels. For tiled sampling, use
|
| 98 |
+
the current tile image, not a full-frame reference to a smaller tile sampler.
|
| 99 |
+
|
| 100 |
+
## Experimental reference anchor
|
| 101 |
+
|
| 102 |
+
**Apply MOSS Reference Anchor** adds an explicit reference constraint during
|
| 103 |
+
denoising. It constrains low-frequency latent features, including colors and
|
| 104 |
+
coarse structure. It can strongly suppress newly generated texture and make
|
| 105 |
+
an upscaled image look as soft as its reference. It is disabled by default
|
| 106 |
+
and is **not recommended for detail enhancement**. This is a sampling
|
| 107 |
+
constraint, not an RGB Color Match operation or a newly trained LLLite model.
|
| 108 |
+
Existing MOSS Tile checkpoints can be used with it.
|
| 109 |
+
|
| 110 |
+
1. Resize the reference image to the final sampling resolution and encode it
|
| 111 |
+
with the **Flux2 VAE** using **VAE Encode**.
|
| 112 |
+
2. Connect that `LATENT` to the anchor's `reference` input and the sampler's
|
| 113 |
+
`latent_image` input. Their spatial dimensions must match.
|
| 114 |
+
3. Connect the model after **Apply MOSS-LLLite** to the anchor, then connect the
|
| 115 |
+
anchor's output model to the sampler. Strength `0` leaves the input model
|
| 116 |
+
unchanged. Enable it only if keeping the reference matters more than new detail.
|
| 117 |
+
4. Decode with ordinary **VAE Decode** when memory permits. Tiled VAE decoding
|
| 118 |
+
can introduce a separate color difference after sampling.
|
| 119 |
+
|
| 120 |
+
Higher anchor strength keeps the reference more closely. A larger grid also
|
| 121 |
+
preserves finer reference structure, reducing freedom to redraw it. The anchor
|
| 122 |
+
is independent of LLLite strength: disable both to remove both constraints.
|
| 123 |
+
At anchor strength `0`, this node returns its input model unchanged.
|
| 124 |
+
|
| 125 |
+
For a small subject inside a large, multi-megapixel canvas, try grid size `16`
|
| 126 |
+
or `32`. A coarse grid can improve the background while missing a local color
|
| 127 |
+
shift. Larger grids do not resolve the texture tradeoff. Inspect native-size
|
| 128 |
+
texture crops as well as the overall image; color error and SSIM alone cannot
|
| 129 |
+
measure detail enhancement.
|
| 130 |
+
|
| 131 |
+
Strong style LoRAs can reduce color following even when the Tile controller
|
| 132 |
+
holds geometry well. For restoration, compare a model without the style LoRA
|
| 133 |
+
in the refinement stage; its appearance is already present in the reference.
|
| 134 |
+
|
| 135 |
## Compatibility and limitations
|
| 136 |
|
| 137 |
- Supports ordinary MOSS-Image generation. MOSS-Edit reference images and cached
|
ComfyUI-MOSS-LLLite/__init__.py
CHANGED
|
@@ -1,12 +1,14 @@
|
|
| 1 |
from comfy_api.latest import ComfyExtension
|
| 2 |
|
| 3 |
from .nodes import MossTileControlLoader, MossTileControlApply
|
| 4 |
-
from .lllite_nodes import MossLLLiteLoader, MossLLLiteApply
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
class MossLLLiteExtension(ComfyExtension):
|
| 8 |
async def get_node_list(self):
|
| 9 |
-
return [MossTileControlLoader, MossTileControlApply, MossLLLiteLoader, MossLLLiteApply
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
async def comfy_entrypoint():
|
|
|
|
| 1 |
from comfy_api.latest import ComfyExtension
|
| 2 |
|
| 3 |
from .nodes import MossTileControlLoader, MossTileControlApply
|
| 4 |
+
from .lllite_nodes import MossLLLiteLoader, MossLLLiteApply, MossReferenceAnchorApply
|
| 5 |
+
from .color_guide import MossColorGuideApply
|
| 6 |
|
| 7 |
|
| 8 |
class MossLLLiteExtension(ComfyExtension):
|
| 9 |
async def get_node_list(self):
|
| 10 |
+
return [MossTileControlLoader, MossTileControlApply, MossLLLiteLoader, MossLLLiteApply, MossReferenceAnchorApply,
|
| 11 |
+
MossColorGuideApply]
|
| 12 |
|
| 13 |
|
| 14 |
async def comfy_entrypoint():
|
ComfyUI-MOSS-LLLite/color_guide.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Final latent color correction measured through the supplied Flux2 VAE."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
import comfy.ldm.moss_image.model
|
| 7 |
+
import comfy.model_management
|
| 8 |
+
import comfy.patcher_extension
|
| 9 |
+
from comfy_api.latest import io
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def calibrate_color_directions(vae, image):
|
| 13 |
+
pixels = F.interpolate(image[..., :3].movedim(-1, 1).float(), size=(256, 256), mode='area').movedim(1, -1)
|
| 14 |
+
axes = []
|
| 15 |
+
for direction in ((.1, -.1 * .2126 / .7152, 0.), (0., -.1 * .0722 / .7152, .1), (.1, .1, .1)):
|
| 16 |
+
shift = pixels.new_tensor(direction)
|
| 17 |
+
plus = vae.encode((pixels + shift).clamp(0, 1)).float().cpu()
|
| 18 |
+
minus = vae.encode((pixels - shift).clamp(0, 1)).float().cpu()
|
| 19 |
+
delta = (plus - minus).mean((-2, -1)).reshape(image.shape[0], 32, 4).mean(2)
|
| 20 |
+
axes.append(delta)
|
| 21 |
+
axes = torch.stack(axes, dim=-1)
|
| 22 |
+
return axes / axes.norm(dim=-2, keepdim=True).clamp_min(1e-6)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MossColorGuide:
|
| 26 |
+
def __init__(self, vae, image, directions, strength, grid_size, iterations):
|
| 27 |
+
self.vae = vae
|
| 28 |
+
self.image_shape = tuple(image.shape[:3])
|
| 29 |
+
self.grid = (min(grid_size, image.shape[1] // 16), min(grid_size, image.shape[2] // 16))
|
| 30 |
+
self.target = F.adaptive_avg_pool2d(image[..., :3].movedim(-1, 1).float(), self.grid).cpu()
|
| 31 |
+
self.directions = directions.float().cpu().clone()
|
| 32 |
+
self.strength, self.iterations = strength, iterations
|
| 33 |
+
|
| 34 |
+
def move(self, latent, coefficients):
|
| 35 |
+
delta = torch.einsum('bkhw,bck->bchw', coefficients, self.directions)
|
| 36 |
+
# Apply the same correction to each of the four packed spatial phases.
|
| 37 |
+
delta = delta[:, :, None].expand(-1, -1, 4, -1, -1).flatten(1, 2)
|
| 38 |
+
return latent + F.interpolate(delta, size=latent.shape[-2:], mode='bilinear', align_corners=False)
|
| 39 |
+
|
| 40 |
+
def decode_colors(self, latent):
|
| 41 |
+
comfy.model_management.throw_exception_if_processing_interrupted()
|
| 42 |
+
image = self.vae.decode(latent).float().cpu().clamp(0, 1)
|
| 43 |
+
return F.adaptive_avg_pool2d(image.movedim(-1, 1), self.grid)
|
| 44 |
+
|
| 45 |
+
def correct(self, samples):
|
| 46 |
+
if self.strength == 0:
|
| 47 |
+
return samples
|
| 48 |
+
if samples.ndim != 4 or samples.shape[1] != 128 or (samples.shape[-2] * 16, samples.shape[-1] * 16) != self.image_shape[1:]:
|
| 49 |
+
raise ValueError('MOSS color guide needs its image at the sampling resolution')
|
| 50 |
+
if self.image_shape[0] not in (1, samples.shape[0]):
|
| 51 |
+
raise ValueError('MOSS color guide needs one reference image or one per output image')
|
| 52 |
+
latent = samples.float().cpu()
|
| 53 |
+
current = self.decode_colors(latent)
|
| 54 |
+
target = self.target if self.strength == 1 else torch.lerp(current, self.target, self.strength)
|
| 55 |
+
identity = torch.eye(3)
|
| 56 |
+
for _ in range(self.iterations):
|
| 57 |
+
derivatives = []
|
| 58 |
+
for index in range(3):
|
| 59 |
+
coefficients = latent.new_zeros((samples.shape[0], 3, *self.grid))
|
| 60 |
+
coefficients[:, index] = .5
|
| 61 |
+
colors = self.decode_colors(self.move(latent, coefficients))
|
| 62 |
+
derivatives.append((colors - current) / .5)
|
| 63 |
+
jacobian = torch.stack(derivatives, dim=-1).movedim(1, -2)
|
| 64 |
+
error = (target - current).movedim(1, -1)[..., None]
|
| 65 |
+
normal = jacobian.transpose(-1, -2) @ jacobian
|
| 66 |
+
ridge = normal.diagonal(dim1=-2, dim2=-1).mean(-1)[..., None, None] * .02 + 1e-6
|
| 67 |
+
coefficients = torch.linalg.solve(normal + identity * ridge, jacobian.transpose(-1, -2) @ error).squeeze(-1)
|
| 68 |
+
coefficients *= 2 / coefficients.norm(dim=-1, keepdim=True).clamp_min(2)
|
| 69 |
+
latent = self.move(latent, coefficients.movedim(-1, 1) * .8)
|
| 70 |
+
current = self.decode_colors(latent)
|
| 71 |
+
return latent.to(device=samples.device, dtype=samples.dtype)
|
| 72 |
+
|
| 73 |
+
def __call__(self, executor, *args, **kwargs):
|
| 74 |
+
return self.correct(executor(*args, **kwargs))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class MossColorGuideApply(io.ComfyNode):
|
| 78 |
+
@classmethod
|
| 79 |
+
def define_schema(cls):
|
| 80 |
+
return io.Schema(
|
| 81 |
+
node_id='MossColorGuideApply', display_name='Apply MOSS Color Guide', category='MOSS-LLLite',
|
| 82 |
+
description='Experimental final latent color correction using actual VAE-decoded colors. '
|
| 83 |
+
'Keeps generated texture better than Reference Anchor in local tests. '
|
| 84 |
+
'May reduce local contrast and perceived sharpness. '
|
| 85 |
+
'Adds multiple full VAE decodes. Use the same Flux2 VAE and final-resolution reference image. '
|
| 86 |
+
'This is inference compensation, not a retrained LLLite; independent of LLLite strength.',
|
| 87 |
+
inputs=[io.Model.Input('model'), io.Image.Input('image', optional=True), io.Vae.Input('vae', optional=True),
|
| 88 |
+
io.Float.Input('strength', default=0.0, min=0.0, max=1.0, step=0.05,
|
| 89 |
+
tooltip='Color correction amount, independent of LLLite. 0 disables it; try 0.8 if 1 looks softer.'),
|
| 90 |
+
io.Int.Input('grid_size', default=8, min=1, max=32, step=1, advanced=True,
|
| 91 |
+
tooltip='Coarse color measurement grid, not image tiles. Try 16 for local color shifts on large canvases.'),
|
| 92 |
+
io.Int.Input('iterations', default=2, min=1, max=3, step=1, advanced=True,
|
| 93 |
+
tooltip='Decoder-feedback correction rounds. More rounds add full VAE decodes; start with 2.')],
|
| 94 |
+
outputs=[io.Model.Output()],
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
@classmethod
|
| 98 |
+
def execute(cls, model, image=None, vae=None, strength=0.0, grid_size=8, iterations=2):
|
| 99 |
+
if strength == 0:
|
| 100 |
+
return io.NodeOutput(model)
|
| 101 |
+
if not 0 < strength <= 1 or grid_size < 1 or not 1 <= iterations <= 3:
|
| 102 |
+
raise ValueError('MOSS color guide needs strength in (0, 1], a positive grid size and 1-3 iterations')
|
| 103 |
+
if not isinstance(model.get_model_object('diffusion_model'), comfy.ldm.moss_image.model.MOSSImage):
|
| 104 |
+
raise ValueError('MOSS color guide requires a MOSS-Image backbone')
|
| 105 |
+
if image is None or vae is None:
|
| 106 |
+
raise ValueError('Connect a reference image and the Flux2 VAE to enable MOSS color guide')
|
| 107 |
+
if vae.latent_channels != 128:
|
| 108 |
+
raise ValueError('MOSS color guide requires the 128-channel Flux2 VAE')
|
| 109 |
+
if image.ndim != 4 or image.shape[-1] < 3 or min(image.shape[1:3]) < 16 or any(size % 16 for size in image.shape[1:3]):
|
| 110 |
+
raise ValueError('MOSS color guide needs an RGB image at the sampling resolution, in multiples of 16')
|
| 111 |
+
directions = calibrate_color_directions(vae, image)
|
| 112 |
+
result = model.clone()
|
| 113 |
+
result.add_wrapper(comfy.patcher_extension.WrappersMP.OUTER_SAMPLE,
|
| 114 |
+
MossColorGuide(vae, image, directions, strength, grid_size, iterations))
|
| 115 |
+
return io.NodeOutput(result)
|
ComfyUI-MOSS-LLLite/lllite_model.py
CHANGED
|
@@ -56,9 +56,17 @@ def config_from_metadata(metadata):
|
|
| 56 |
return config
|
| 57 |
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
def apply_image_control(module, tokens, condition, strength):
|
| 60 |
count = condition.shape[1]
|
| 61 |
-
|
|
|
|
| 62 |
return torch.cat((image, tokens[:, count:]), dim=1)
|
| 63 |
|
| 64 |
|
|
|
|
| 56 |
return config
|
| 57 |
|
| 58 |
|
| 59 |
+
def control_autocast(tensor):
|
| 60 |
+
# The CUDA trainer uses AMP: GroupNorm/LayerNorm keep FP32 activations.
|
| 61 |
+
if tensor.device.type == 'cuda' and tensor.dtype in (torch.float16, torch.bfloat16):
|
| 62 |
+
return torch.autocast('cuda', dtype=tensor.dtype)
|
| 63 |
+
return nullcontext()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
def apply_image_control(module, tokens, condition, strength):
|
| 67 |
count = condition.shape[1]
|
| 68 |
+
with control_autocast(tokens):
|
| 69 |
+
image = module(tokens[:, :count], condition, strength)
|
| 70 |
return torch.cat((image, tokens[:, count:]), dim=1)
|
| 71 |
|
| 72 |
|
ComfyUI-MOSS-LLLite/lllite_nodes.py
CHANGED
|
@@ -14,7 +14,7 @@ import comfy.patcher_extension
|
|
| 14 |
import comfy.utils
|
| 15 |
from comfy_api.latest import io
|
| 16 |
|
| 17 |
-
from .lllite_model import MossLLLiteControl, PREFIX, config_from_metadata, controlled_moss_block
|
| 18 |
|
| 19 |
LLLiteType = io.Custom('MOSS_LLLITE_CONTROL')
|
| 20 |
CONTROL_KEY = 'moss_lllite'
|
|
@@ -59,9 +59,12 @@ class MossLLLitePatch:
|
|
| 59 |
raise ValueError('MOSS LLLite currently supports image generation, without MOSS-Edit reference tokens')
|
| 60 |
image = comfy.utils.common_upscale(self.image.movedim(-1, 1), x.shape[-1] * 16, x.shape[-2] * 16,
|
| 61 |
'bicubic', 'center').clamp(0, 1)
|
|
|
|
|
|
|
| 62 |
# Preserve encoder batch shape: BF16 convolution rounding depends on it.
|
| 63 |
-
image = comfy.utils.repeat_to_batch_size(image
|
| 64 |
-
|
|
|
|
| 65 |
mask = kwargs.get('context_attention_bias')
|
| 66 |
if mask is not None:
|
| 67 |
mask = F.pad(mask, (x.shape[-2] * x.shape[-1], 0))[:, None, None]
|
|
@@ -135,3 +138,56 @@ class MossLLLiteApply(io.ComfyNode):
|
|
| 135 |
'dit', 'single_block', index)
|
| 136 |
result.set_additional_models(CONTROL_KEY, result.get_additional_models_with_key(CONTROL_KEY) + [control])
|
| 137 |
return io.NodeOutput(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
import comfy.utils
|
| 15 |
from comfy_api.latest import io
|
| 16 |
|
| 17 |
+
from .lllite_model import MossLLLiteControl, PREFIX, config_from_metadata, control_autocast, controlled_moss_block
|
| 18 |
|
| 19 |
LLLiteType = io.Custom('MOSS_LLLITE_CONTROL')
|
| 20 |
CONTROL_KEY = 'moss_lllite'
|
|
|
|
| 59 |
raise ValueError('MOSS LLLite currently supports image generation, without MOSS-Edit reference tokens')
|
| 60 |
image = comfy.utils.common_upscale(self.image.movedim(-1, 1), x.shape[-1] * 16, x.shape[-2] * 16,
|
| 61 |
'bicubic', 'center').clamp(0, 1)
|
| 62 |
+
amp = x.device.type == 'cuda' and x.dtype in (torch.float16, torch.bfloat16)
|
| 63 |
+
image = (image.float() * 2 - 1).to(device=x.device, dtype=torch.float32 if amp else x.dtype)
|
| 64 |
# Preserve encoder batch shape: BF16 convolution rounding depends on it.
|
| 65 |
+
image = comfy.utils.repeat_to_batch_size(image, x.shape[0])
|
| 66 |
+
with control_autocast(x):
|
| 67 |
+
condition = self.control.model.conditioner(image)
|
| 68 |
mask = kwargs.get('context_attention_bias')
|
| 69 |
if mask is not None:
|
| 70 |
mask = F.pad(mask, (x.shape[-2] * x.shape[-1], 0))[:, None, None]
|
|
|
|
| 138 |
'dit', 'single_block', index)
|
| 139 |
result.set_additional_models(CONTROL_KEY, result.get_additional_models_with_key(CONTROL_KEY) + [control])
|
| 140 |
return io.NodeOutput(result)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class MossReferenceAnchor:
|
| 144 |
+
def __init__(self, reference, strength, grid_size):
|
| 145 |
+
self.reference = reference.to(device='cpu').clone()
|
| 146 |
+
self.strength, self.grid_size = strength, grid_size
|
| 147 |
+
|
| 148 |
+
def __call__(self, args):
|
| 149 |
+
denoised = args['denoised']
|
| 150 |
+
if self.strength == 0:
|
| 151 |
+
return denoised
|
| 152 |
+
if denoised.shape[1:] != self.reference.shape[1:]:
|
| 153 |
+
raise ValueError('MOSS reference anchor needs a reference latent at the sampling resolution')
|
| 154 |
+
if self.reference.shape[0] not in (1, denoised.shape[0]):
|
| 155 |
+
raise ValueError('MOSS reference anchor needs one reference image or one per output image')
|
| 156 |
+
target = self.reference.to(device=denoised.device, dtype=denoised.dtype)
|
| 157 |
+
grid = (min(self.grid_size, denoised.shape[-2]), min(self.grid_size, denoised.shape[-1]))
|
| 158 |
+
difference = F.adaptive_avg_pool2d(target - denoised, grid)
|
| 159 |
+
difference = F.interpolate(difference, size=denoised.shape[-2:], mode='bilinear', align_corners=False)
|
| 160 |
+
return denoised + difference * self.strength
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class MossReferenceAnchorApply(io.ComfyNode):
|
| 164 |
+
@classmethod
|
| 165 |
+
def define_schema(cls):
|
| 166 |
+
return io.Schema(
|
| 167 |
+
node_id='MossReferenceAnchorApply', display_name='Apply MOSS Reference Anchor', category='MOSS-LLLite',
|
| 168 |
+
description='Experimental sampling constraint for reference colors and coarse structure. '
|
| 169 |
+
'Can strongly suppress generated texture and sharpening; disabled by default. '
|
| 170 |
+
'Encode the control image with the Flux2 VAE at the sampling resolution. '
|
| 171 |
+
'This is independent of LLLite strength; disable both controls to keep the input model unchanged.',
|
| 172 |
+
inputs=[io.Model.Input('model'), io.Latent.Input('reference'),
|
| 173 |
+
io.Float.Input('strength', default=0.0, min=0.0, max=1.0, step=0.05),
|
| 174 |
+
io.Int.Input('grid_size', default=8, min=1, max=32, step=1, advanced=True,
|
| 175 |
+
tooltip='More cells preserve finer reference structure as well as color.')],
|
| 176 |
+
outputs=[io.Model.Output()],
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
@classmethod
|
| 180 |
+
def execute(cls, model, reference, strength=0.0, grid_size=8):
|
| 181 |
+
if strength == 0:
|
| 182 |
+
return io.NodeOutput(model)
|
| 183 |
+
if not 0 < strength <= 1 or grid_size < 1:
|
| 184 |
+
raise ValueError('MOSS reference anchor needs strength in (0, 1] and a positive grid size')
|
| 185 |
+
if not isinstance(model.get_model_object('diffusion_model'), comfy.ldm.moss_image.model.MOSSImage):
|
| 186 |
+
raise ValueError('MOSS reference anchor requires a MOSS-Image backbone')
|
| 187 |
+
samples = reference['samples']
|
| 188 |
+
if samples.ndim != 4 or samples.shape[1] != 128:
|
| 189 |
+
raise ValueError('MOSS reference anchor requires a 128-channel Flux2 image latent')
|
| 190 |
+
samples = model.get_model_object('latent_format').process_in(samples)
|
| 191 |
+
result = model.clone()
|
| 192 |
+
result.set_model_sampler_post_cfg_function(MossReferenceAnchor(samples, strength, grid_size))
|
| 193 |
+
return io.NodeOutput(result)
|
ComfyUI-MOSS-LLLite/pyproject.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
[project]
|
| 2 |
name = "comfyui-moss-lllite"
|
| 3 |
-
version = "0.1.
|
| 4 |
description = "Anima-style LLLite control for MOSS-Image in ComfyUI"
|
| 5 |
readme = "README.md"
|
| 6 |
license = { file = "LICENSE" }
|
|
|
|
| 1 |
[project]
|
| 2 |
name = "comfyui-moss-lllite"
|
| 3 |
+
version = "0.1.3"
|
| 4 |
description = "Anima-style LLLite control for MOSS-Image in ComfyUI"
|
| 5 |
readme = "README.md"
|
| 6 |
license = { file = "LICENSE" }
|
ComfyUI-MOSS-LLLite/tests/test_lllite_nodes.py
CHANGED
|
@@ -2,6 +2,7 @@ import importlib.util
|
|
| 2 |
from pathlib import Path
|
| 3 |
import sys
|
| 4 |
import tempfile
|
|
|
|
| 5 |
import unittest
|
| 6 |
from unittest.mock import patch
|
| 7 |
|
|
@@ -12,10 +13,12 @@ comfy.cli_args.args.cpu = True
|
|
| 12 |
import comfy.model_management
|
| 13 |
import comfy.model_patcher
|
| 14 |
import comfy.model_sampling
|
|
|
|
| 15 |
import comfy.ldm.moss_image.model as moss
|
| 16 |
import comfy.ops
|
| 17 |
import safetensors.torch
|
| 18 |
import torch
|
|
|
|
| 19 |
from torch import nn
|
| 20 |
|
| 21 |
PACKAGE = Path(__file__).resolve().parents[1]
|
|
@@ -25,6 +28,7 @@ sys.modules[spec.name] = package
|
|
| 25 |
spec.loader.exec_module(package)
|
| 26 |
nodes = sys.modules[spec.name + '.lllite_nodes']
|
| 27 |
architecture = sys.modules[spec.name + '.lllite_model']
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
def fixture(fused=False):
|
|
@@ -44,6 +48,20 @@ def fixture(fused=False):
|
|
| 44 |
return model, holder, torch.rand(1, 64, 64, 3)
|
| 45 |
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
class NodeTests(unittest.TestCase):
|
| 48 |
def setUp(self):
|
| 49 |
torch.manual_seed(21)
|
|
@@ -54,6 +72,112 @@ class NodeTests(unittest.TestCase):
|
|
| 54 |
self.assertIs(nodes.MossLLLiteApply.execute(model, control, image, 0).result[0], model)
|
| 55 |
self.assertIs(nodes.MossLLLiteApply.execute(model, control, image, 1, .8, .2).result[0], model)
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
def test_real_block_matches_original_at_zero_and_changes_at_nonzero(self):
|
| 58 |
# Native CPU attention and differentiable norm path, without kitchen CUDA kernels.
|
| 59 |
with patch.object(comfy.model_management, 'in_training', True):
|
|
@@ -92,6 +216,53 @@ class NodeTests(unittest.TestCase):
|
|
| 92 |
wrapper(executor, x, torch.tensor([.8]), context, {'sigmas': torch.tensor([.8])})
|
| 93 |
self.assertNotIn(nodes.CONTROL_KEY, observed)
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
def test_fused_projection_rows_bias_and_gradients(self):
|
| 96 |
projection = nn.Linear(32, 96)
|
| 97 |
inputs = [torch.randn(2, 19, 32, requires_grad=True) for _ in range(3)]
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
import sys
|
| 4 |
import tempfile
|
| 5 |
+
from types import SimpleNamespace
|
| 6 |
import unittest
|
| 7 |
from unittest.mock import patch
|
| 8 |
|
|
|
|
| 13 |
import comfy.model_management
|
| 14 |
import comfy.model_patcher
|
| 15 |
import comfy.model_sampling
|
| 16 |
+
import comfy.latent_formats
|
| 17 |
import comfy.ldm.moss_image.model as moss
|
| 18 |
import comfy.ops
|
| 19 |
import safetensors.torch
|
| 20 |
import torch
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
from torch import nn
|
| 23 |
|
| 24 |
PACKAGE = Path(__file__).resolve().parents[1]
|
|
|
|
| 28 |
spec.loader.exec_module(package)
|
| 29 |
nodes = sys.modules[spec.name + '.lllite_nodes']
|
| 30 |
architecture = sys.modules[spec.name + '.lllite_model']
|
| 31 |
+
color_guide = sys.modules[spec.name + '.color_guide']
|
| 32 |
|
| 33 |
|
| 34 |
def fixture(fused=False):
|
|
|
|
| 48 |
return model, holder, torch.rand(1, 64, 64, 3)
|
| 49 |
|
| 50 |
|
| 51 |
+
class LinearColorVAE:
|
| 52 |
+
latent_channels = 128
|
| 53 |
+
def __init__(self):
|
| 54 |
+
self.inputs = []
|
| 55 |
+
def encode(self, pixels):
|
| 56 |
+
self.inputs.append(pixels.clone())
|
| 57 |
+
channels = F.pad(pixels.mean((1, 2)), (0, 29))
|
| 58 |
+
return channels.repeat_interleave(4, dim=1)[:, :, None, None].expand(-1, -1, 16, 16)
|
| 59 |
+
def decode(self, samples):
|
| 60 |
+
b, _, h, w = samples.shape
|
| 61 |
+
colors = samples.reshape(b, 32, 4, h, w).mean(2)[:, :3]
|
| 62 |
+
return F.interpolate(colors, scale_factor=16, mode='nearest').movedim(1, -1)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
class NodeTests(unittest.TestCase):
|
| 66 |
def setUp(self):
|
| 67 |
torch.manual_seed(21)
|
|
|
|
| 72 |
self.assertIs(nodes.MossLLLiteApply.execute(model, control, image, 0).result[0], model)
|
| 73 |
self.assertIs(nodes.MossLLLiteApply.execute(model, control, image, 1, .8, .2).result[0], model)
|
| 74 |
|
| 75 |
+
def test_reference_anchor_zero_returns_original_without_adding_hooks(self):
|
| 76 |
+
model, _, _ = fixture()
|
| 77 |
+
before = model.model_options.copy()
|
| 78 |
+
self.assertIs(nodes.MossReferenceAnchorApply.execute(model, {}, 0).result[0], model)
|
| 79 |
+
self.assertIs(nodes.MossReferenceAnchorApply.execute(model, {}).result[0], model)
|
| 80 |
+
self.assertEqual(model.model_options, before)
|
| 81 |
+
|
| 82 |
+
def test_reference_anchor_corrects_constant_bias_and_preserves_fine_variation(self):
|
| 83 |
+
reference = torch.zeros(1, 128, 16, 24)
|
| 84 |
+
checkerboard = ((torch.arange(16)[:, None] + torch.arange(24)[None, :]) % 2).float() * 2 - 1
|
| 85 |
+
detail = checkerboard[None, None].expand(2, 128, -1, -1) * .1
|
| 86 |
+
bias = torch.linspace(-.5, .5, 128)[None, :, None, None]
|
| 87 |
+
anchor = nodes.MossReferenceAnchor(reference, 1, 4)
|
| 88 |
+
result = anchor({'denoised': detail + bias})
|
| 89 |
+
torch.testing.assert_close(result, detail, atol=1e-7, rtol=1e-6)
|
| 90 |
+
zero = nodes.MossReferenceAnchor(reference, 0, 4)
|
| 91 |
+
self.assertIs(zero({'denoised': detail}), detail)
|
| 92 |
+
|
| 93 |
+
def test_reference_anchor_clones_model_reference_and_preserves_existing_hooks(self):
|
| 94 |
+
model, _, _ = fixture()
|
| 95 |
+
model.model.latent_format = comfy.latent_formats.Flux2()
|
| 96 |
+
previous = lambda args: args['denoised']
|
| 97 |
+
model.set_model_sampler_post_cfg_function(previous)
|
| 98 |
+
reference = torch.randn(1, 128, 16, 24)
|
| 99 |
+
saved = reference.clone()
|
| 100 |
+
result = nodes.MossReferenceAnchorApply.execute(model, {'samples': reference}, .5, 4).result[0]
|
| 101 |
+
self.assertIsNot(result, model)
|
| 102 |
+
self.assertEqual(len(model.model_options['sampler_post_cfg_function']), 1)
|
| 103 |
+
hooks = result.model_options['sampler_post_cfg_function']
|
| 104 |
+
self.assertEqual(len(hooks), 2)
|
| 105 |
+
self.assertIs(hooks[0], previous)
|
| 106 |
+
reference.fill_(100)
|
| 107 |
+
self.assertTrue(torch.equal(hooks[-1].reference, saved))
|
| 108 |
+
self.assertEqual(hooks[-1].reference.device.type, 'cpu')
|
| 109 |
+
|
| 110 |
+
def test_reference_anchor_rejects_incompatible_latents_and_sampling_shapes(self):
|
| 111 |
+
model, _, _ = fixture()
|
| 112 |
+
model.model.latent_format = comfy.latent_formats.Flux2()
|
| 113 |
+
with self.assertRaisesRegex(ValueError, '128-channel'):
|
| 114 |
+
nodes.MossReferenceAnchorApply.execute(model, {'samples': torch.zeros(1, 16, 8, 8)}, .5)
|
| 115 |
+
anchor = nodes.MossReferenceAnchor(torch.zeros(2, 128, 8, 8), .5, 4)
|
| 116 |
+
with self.assertRaisesRegex(ValueError, 'sampling resolution'):
|
| 117 |
+
anchor({'denoised': torch.zeros(2, 128, 8, 12)})
|
| 118 |
+
with self.assertRaisesRegex(ValueError, 'per output image'):
|
| 119 |
+
anchor({'denoised': torch.zeros(3, 128, 8, 8)})
|
| 120 |
+
|
| 121 |
+
def test_color_guide_zero_skips_calibration_and_keeps_input_model(self):
|
| 122 |
+
model, _, _ = fixture()
|
| 123 |
+
self.assertIs(color_guide.MossColorGuideApply.execute(model).result[0], model)
|
| 124 |
+
with self.assertRaisesRegex(ValueError, 'Connect a reference image'):
|
| 125 |
+
color_guide.MossColorGuideApply.execute(model, strength=.5)
|
| 126 |
+
|
| 127 |
+
def test_color_feedback_corrects_palette_and_preserves_other_latent_features(self):
|
| 128 |
+
vae = LinearColorVAE()
|
| 129 |
+
image = torch.full((1, 64, 64, 3), .5)
|
| 130 |
+
directions = color_guide.calibrate_color_directions(vae, image)
|
| 131 |
+
samples = torch.full((2, 32, 4, 4, 4), .2)
|
| 132 |
+
samples[:, 3:] = .7
|
| 133 |
+
samples += torch.tensor([-.03, .03, -.03, .03])[None, None, :, None, None]
|
| 134 |
+
samples = samples.flatten(1, 2)
|
| 135 |
+
guide = color_guide.MossColorGuide(vae, image, directions, 1, 4, 2)
|
| 136 |
+
result = guide(lambda: samples)
|
| 137 |
+
actual = result.reshape(2, 32, 4, 4, 4)
|
| 138 |
+
torch.testing.assert_close(actual[:, :3].mean(2), torch.full((2, 3, 4, 4), .5), atol=.03, rtol=0)
|
| 139 |
+
self.assertTrue(torch.equal(result[:, 12:], samples[:, 12:]))
|
| 140 |
+
torch.testing.assert_close(actual[:, :, 0] - actual[:, :, 1], torch.full((2, 32, 4, 4), -.06), atol=1e-7, rtol=1e-6)
|
| 141 |
+
weak = color_guide.MossColorGuide(vae, image, directions, .5, 4, 2).correct(samples)
|
| 142 |
+
self.assertLess(float(weak[:, :12].mean()), float(result[:, :12].mean()))
|
| 143 |
+
self.assertGreater(float(weak[:, :12].mean()), float(samples[:, :12].mean()))
|
| 144 |
+
zero = color_guide.MossColorGuide(None, image, directions, 0, 4, 2)
|
| 145 |
+
self.assertIs(zero.correct(samples), samples)
|
| 146 |
+
|
| 147 |
+
def test_color_guide_calibrates_per_image_and_keeps_existing_hooks(self):
|
| 148 |
+
model, _, _ = fixture()
|
| 149 |
+
previous = lambda args: args['denoised']
|
| 150 |
+
model.set_model_sampler_post_cfg_function(previous)
|
| 151 |
+
vae = LinearColorVAE()
|
| 152 |
+
image = torch.full((2, 64, 64, 3), .5)
|
| 153 |
+
result = color_guide.MossColorGuideApply.execute(model, image, vae, .5, 2).result[0]
|
| 154 |
+
self.assertIsNot(result, model)
|
| 155 |
+
self.assertEqual(model.model_options['sampler_post_cfg_function'], [previous])
|
| 156 |
+
self.assertEqual(result.model_options['sampler_post_cfg_function'], [previous])
|
| 157 |
+
kind = nodes.comfy.patcher_extension.WrappersMP.OUTER_SAMPLE
|
| 158 |
+
self.assertFalse(model.get_all_wrappers(kind))
|
| 159 |
+
wrapper, = result.get_all_wrappers(kind)
|
| 160 |
+
image.fill_(100)
|
| 161 |
+
torch.testing.assert_close(wrapper.target, torch.full((2, 3, 2, 2), .5))
|
| 162 |
+
self.assertEqual(wrapper.directions.device.type, 'cpu')
|
| 163 |
+
torch.testing.assert_close(wrapper.directions.norm(dim=-2), torch.ones(2, 3))
|
| 164 |
+
self.assertEqual(len(vae.inputs), 6)
|
| 165 |
+
weights = torch.tensor([.2126, .7152, .0722])
|
| 166 |
+
for pixels in vae.inputs[:4]:
|
| 167 |
+
self.assertEqual(pixels.shape, (2, 256, 256, 3))
|
| 168 |
+
torch.testing.assert_close(pixels @ weights, torch.full((2, 256, 256), .5))
|
| 169 |
+
|
| 170 |
+
def test_color_guide_rejects_misaligned_images_and_sampling_shapes(self):
|
| 171 |
+
model, _, _ = fixture()
|
| 172 |
+
vae = SimpleNamespace(latent_channels=128)
|
| 173 |
+
with self.assertRaisesRegex(ValueError, 'multiples of 16'):
|
| 174 |
+
color_guide.MossColorGuideApply.execute(model, torch.zeros(1, 65, 64, 3), vae, .5)
|
| 175 |
+
guide = color_guide.MossColorGuide(None, torch.zeros(2, 64, 64, 3), torch.zeros(2, 32, 3), .5, 4, 2)
|
| 176 |
+
with self.assertRaisesRegex(ValueError, 'sampling resolution'):
|
| 177 |
+
guide.correct(torch.zeros(2, 128, 4, 6))
|
| 178 |
+
with self.assertRaisesRegex(ValueError, 'per output image'):
|
| 179 |
+
guide.correct(torch.zeros(3, 128, 4, 4))
|
| 180 |
+
|
| 181 |
def test_real_block_matches_original_at_zero_and_changes_at_nonzero(self):
|
| 182 |
# Native CPU attention and differentiable norm path, without kitchen CUDA kernels.
|
| 183 |
with patch.object(comfy.model_management, 'in_training', True):
|
|
|
|
| 216 |
wrapper(executor, x, torch.tensor([.8]), context, {'sigmas': torch.tensor([.8])})
|
| 217 |
self.assertNotIn(nodes.CONTROL_KEY, observed)
|
| 218 |
|
| 219 |
+
def test_rgb_normalization_matches_training_before_bfloat16_cast(self):
|
| 220 |
+
model, control, _ = fixture()
|
| 221 |
+
image = torch.arange(256, dtype=torch.float32).view(1, 1, 256, 1).expand(1, 256, 256, 3) / 255
|
| 222 |
+
patcher = nodes.MossLLLiteApply.execute(model, control, image).result[0]
|
| 223 |
+
wrapper = patcher.get_all_wrappers(comfy.patcher_extension.WrappersMP.DIFFUSION_MODEL)[0]
|
| 224 |
+
x = torch.zeros(2, 128, 16, 16, dtype=torch.bfloat16)
|
| 225 |
+
with patch.object(control.model.conditioner, 'forward', return_value=torch.zeros(2, 256, 8)) as encode:
|
| 226 |
+
wrapper(lambda *args, **kwargs: x, x, torch.tensor([.5]), None, {})
|
| 227 |
+
expected = (image.movedim(-1, 1) * 2 - 1).to(torch.bfloat16).repeat(2, 1, 1, 1)
|
| 228 |
+
self.assertTrue(torch.equal(encode.call_args.args[0], expected))
|
| 229 |
+
|
| 230 |
+
@unittest.skipUnless(torch.cuda.is_available(), 'CUDA required for trainer AMP parity')
|
| 231 |
+
def test_cuda_conditioning_and_adapter_match_training_arithmetic(self):
|
| 232 |
+
_, holder, _ = fixture()
|
| 233 |
+
training = holder.model.to(device='cuda', dtype=torch.bfloat16)
|
| 234 |
+
control = architecture.MossLLLiteControl(
|
| 235 |
+
**training.config, operations=comfy.ops.manual_cast, device='cuda', dtype=torch.bfloat16)
|
| 236 |
+
control.load_state_dict(training.state_dict())
|
| 237 |
+
holder = comfy.model_patcher.ModelPatcher(control, load_device=torch.device('cuda'),
|
| 238 |
+
offload_device=torch.device('cpu'))
|
| 239 |
+
image = torch.rand(1, 64, 96, 3)
|
| 240 |
+
wrapper = nodes.MossLLLitePatch(holder, image, 1, float('inf'), 0)
|
| 241 |
+
observed = {}
|
| 242 |
+
|
| 243 |
+
def executor(x, timestep, context, options, **kwargs):
|
| 244 |
+
self.assertFalse(torch.is_autocast_enabled('cuda'))
|
| 245 |
+
observed.update(options)
|
| 246 |
+
return x
|
| 247 |
+
|
| 248 |
+
x = torch.randn(2, 128, 4, 6, device='cuda', dtype=torch.bfloat16)
|
| 249 |
+
wrapper(executor, x, torch.tensor([.5], device='cuda'), None, {})
|
| 250 |
+
actual = observed[nodes.CONTROL_KEY][wrapper][0]
|
| 251 |
+
pixels = (image.movedim(-1, 1) * 2 - 1).cuda().repeat(2, 1, 1, 1)
|
| 252 |
+
with torch.autocast('cuda', dtype=torch.bfloat16):
|
| 253 |
+
expected = training.conditioner(pixels)
|
| 254 |
+
self.assertEqual(actual.dtype, torch.float32)
|
| 255 |
+
torch.testing.assert_close(actual, expected, atol=0, rtol=0)
|
| 256 |
+
tokens = torch.randn(2, 27, 32, device='cuda', dtype=torch.bfloat16)
|
| 257 |
+
for target in architecture.TARGETS:
|
| 258 |
+
with torch.autocast('cuda', dtype=torch.bfloat16):
|
| 259 |
+
image_tokens = training.blocks[0][target](tokens[:, :24], expected, .25)
|
| 260 |
+
reference = torch.cat((image_tokens, tokens[:, 24:]), dim=1)
|
| 261 |
+
result = architecture.apply_image_control(control.blocks[0][target], tokens, actual, .25)
|
| 262 |
+
torch.testing.assert_close(result, reference, atol=0, rtol=0)
|
| 263 |
+
self.assertTrue(torch.equal(result[:, 24:], tokens[:, 24:]))
|
| 264 |
+
self.assertFalse(torch.is_autocast_enabled('cuda'))
|
| 265 |
+
|
| 266 |
def test_fused_projection_rows_bias_and_gradients(self):
|
| 267 |
projection = nn.Linear(32, 96)
|
| 268 |
inputs = [torch.randn(2, 19, 32, requires_grad=True) for _ in range(3)]
|
README.md
CHANGED
|
@@ -33,6 +33,43 @@ of the original information.
|
|
| 33 |
|
| 34 |
If you would like to support this project: [Ko-fi](https://ko-fi.com/xabsurd).
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
## Which version should I use?
|
| 37 |
|
| 38 |
| Version | Best use | Observed behavior | Relative sampling speed | Setup |
|
|
@@ -182,9 +219,10 @@ different load/apply nodes.
|
|
| 182 |
are currently unsupported by the LLLite nodes.
|
| 183 |
- V1, beta3, beta2, and Anima LLLite weight files are not interchangeable. Remove
|
| 184 |
old beta2 concat Tile LoRAs when switching to V1 or beta3.
|
| 185 |
-
-
|
| 186 |
-
|
| 187 |
-
|
|
|
|
| 188 |
- Fine detail may be invented or changed. Evaluate results when exact identity,
|
| 189 |
text, patterns, or faithful document reconstruction matters.
|
| 190 |
- The prompt, base model, sampling settings, quantization, and other LoRAs affect
|
|
|
|
| 33 |
|
| 34 |
If you would like to support this project: [Ko-fi](https://ko-fi.com/xabsurd).
|
| 35 |
|
| 36 |
+
## Color preservation update
|
| 37 |
+
|
| 38 |
+
**If preserving the reference image's colors matters to you, updating to
|
| 39 |
+
[ComfyUI-MOSS-LLLite v0.1.3](https://github.com/X-absurd/ComfyUI-MOSS-LLLite)
|
| 40 |
+
or later is recommended.** The update adds the optional experimental
|
| 41 |
+
**Apply MOSS Color Guide** node. Existing model weights remain compatible;
|
| 42 |
+
there is no need to download V1 again.
|
| 43 |
+
|
| 44 |
+
The guide uses actual Flux2 VAE-decoded colors as feedback to correct the final
|
| 45 |
+
sampled latent. It can reduce color drift while retaining generated texture
|
| 46 |
+
better than the experimental Reference Anchor in local tests. It is inference
|
| 47 |
+
color compensation, not a retrained checkpoint or a guarantee of exact colors.
|
| 48 |
+
**Brightness and local contrast can change, and the result may look slightly
|
| 49 |
+
less sharp even when fine texture remains visible.** It also adds VAE work and
|
| 50 |
+
increases processing time.
|
| 51 |
+
|
| 52 |
+
1. Update the custom nodes from [GitHub](https://github.com/X-absurd/ComfyUI-MOSS-LLLite),
|
| 53 |
+
or replace your installation with the updated [ZIP](ComfyUI-MOSS-LLLite.zip).
|
| 54 |
+
Restart ComfyUI and refresh the browser.
|
| 55 |
+
2. Connect **Apply MOSS-LLLite → Apply MOSS Color Guide → sampler**.
|
| 56 |
+
Give the guide the reference `IMAGE` at the sampling resolution (dimensions
|
| 57 |
+
must be multiples of 16) and the same **Flux2 VAE** used for decoding.
|
| 58 |
+
3. Start with `strength = 1.0`, `iterations = 2`, `grid_size = 8`.
|
| 59 |
+
If it looks softer, try `strength = 0.8`. For local color drift on large
|
| 60 |
+
images, try `grid_size = 16`. The guide's strength is independent of LLLite.
|
| 61 |
+
4. Keep **Reference Anchor** disabled. Use ordinary **VAE Decode** with the
|
| 62 |
+
same VAE; tiled decoding can introduce a separate color shift. For tiled
|
| 63 |
+
sampling, supply the current tile's reference image to its sampler.
|
| 64 |
+
|
| 65 |
+
The guide is disabled by default (`strength = 0`), leaving its input model
|
| 66 |
+
unchanged. Two iterations require nine additional full VAE decodes after
|
| 67 |
+
sampling, plus six small calibration encodes. Enable it when the color benefit
|
| 68 |
+
justifies the extra time and possible contrast change. See the
|
| 69 |
+
[node documentation](https://github.com/X-absurd/ComfyUI-MOSS-LLLite#experimental-color-guide)
|
| 70 |
+
for parameter details and limitations. Existing examples below predate this
|
| 71 |
+
optional guide and do not demonstrate its effect.
|
| 72 |
+
|
| 73 |
## Which version should I use?
|
| 74 |
|
| 75 |
| Version | Best use | Observed behavior | Relative sampling speed | Setup |
|
|
|
|
| 219 |
are currently unsupported by the LLLite nodes.
|
| 220 |
- V1, beta3, beta2, and Anima LLLite weight files are not interchangeable. Remove
|
| 221 |
old beta2 concat Tile LoRAs when switching to V1 or beta3.
|
| 222 |
+
- Color, contrast, or saturation shifts can still occur. For stronger reference
|
| 223 |
+
color retention, update the nodes and try the optional **Apply MOSS Color Guide**
|
| 224 |
+
described above. **Color Match** remains an optional alternative using the
|
| 225 |
+
original image as the color reference.
|
| 226 |
- Fine detail may be invented or changed. Evaluate results when exact identity,
|
| 227 |
text, patterns, or faithful document reconstruction matters.
|
| 228 |
- The prompt, base model, sampling settings, quantization, and other LoRAs affect
|
RESEARCH_REPORT.md
CHANGED
|
@@ -93,6 +93,23 @@ A separate attempt to reduce RGB encoder batch computation was rejected because
|
|
| 93 |
it changed BF16 numerical results. Preserving generation results constrained
|
| 94 |
optimization decisions, rather than runtime alone.
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
## 6. Conclusions and limits
|
| 97 |
|
| 98 |
The released options offer distinct trade-offs: **beta2 prioritizes preservation,
|
|
|
|
| 93 |
it changed BF16 numerical results. Preserving generation results constrained
|
| 94 |
optimization decisions, rather than runtime alone.
|
| 95 |
|
| 96 |
+
### Optional decoder-feedback color guide
|
| 97 |
+
|
| 98 |
+
Node version 0.1.3 adds **Apply MOSS Color Guide**, an optional inference color
|
| 99 |
+
compensation step that works with existing weights. After sampling, it measures
|
| 100 |
+
coarse RGB errors through the actual Flux2 VAE decoder and iteratively adjusts
|
| 101 |
+
three calibrated latent directions. It does not retrain or repair the learned
|
| 102 |
+
LLLite color response. Strong style LoRAs and the sampling/decoding path can also
|
| 103 |
+
affect the palette.
|
| 104 |
+
|
| 105 |
+
The earlier Reference Anchor constrains all latent channels and can strongly
|
| 106 |
+
suppress generated texture. Decoder feedback retained texture better in local
|
| 107 |
+
comparisons, but can still change brightness and local contrast: visible texture
|
| 108 |
+
may remain while perceived sharpness decreases. Exact color preservation is not
|
| 109 |
+
guaranteed. It adds six small calibration encodes and `1 + 4 × iterations` full
|
| 110 |
+
VAE decodes, making it an optional quality/time trade-off rather than the default.
|
| 111 |
+
See the [model card](README.md#color-preservation-update) for setup and limitations.
|
| 112 |
+
|
| 113 |
## 6. Conclusions and limits
|
| 114 |
|
| 115 |
The released options offer distinct trade-offs: **beta2 prioritizes preservation,
|
SHA256SUMS.txt
CHANGED
|
@@ -2,4 +2,4 @@
|
|
| 2 |
45d81afa8b5afbac9b8813106d195d9778013c7b10f8c535db80e7da96eacd0c beta3/epoch1/adapter_model.safetensors
|
| 3 |
e2d4de5d18cba07cd94d999c0d60ad6849676991a996f69f7a9b3b2b192164d8 beta3/epoch2/adapter_model.safetensors
|
| 4 |
1dc931f3f5533fd96768c64886d87537e7bd19f4f16c1893fb40a459758ae601 V1/MOSS-LLLite-Tile-V1.safetensors
|
| 5 |
-
|
|
|
|
| 2 |
45d81afa8b5afbac9b8813106d195d9778013c7b10f8c535db80e7da96eacd0c beta3/epoch1/adapter_model.safetensors
|
| 3 |
e2d4de5d18cba07cd94d999c0d60ad6849676991a996f69f7a9b3b2b192164d8 beta3/epoch2/adapter_model.safetensors
|
| 4 |
1dc931f3f5533fd96768c64886d87537e7bd19f4f16c1893fb40a459758ae601 V1/MOSS-LLLite-Tile-V1.safetensors
|
| 5 |
+
752e77a44c7a7283cc31d31511fa890e2ff4ad38c80ae9f5393956574715e4ee ComfyUI-MOSS-LLLite.zip
|