File size: 3,003 Bytes
6daffc2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | # SPDX-License-Identifier: GPL-3.0-only
# Copyright 2026 Data Archetype
"""The dinac3_96 autoencoder behind ComfyUI's VAE interface.
Stock ``VAEDecode`` and ``VAEEncode`` call ``decode(latents)`` and
``encode(pixels)``; ComfyUI images are ``[B, H, W, C]`` floats in ``[0, 1]``.
"""
from __future__ import annotations
import comfy.model_management
import torch
from torch import Tensor
from ..dflow.vae import LATENT_CHANNELS, LATENT_STRIDE, DFlowVae
_RGB_CHANNELS = 3
class DFlowVaeAdapter:
"""``DFlowVae`` with ComfyUI's decode/encode conventions."""
latent_channels = LATENT_CHANNELS
latent_dim = 2
def __init__(self, vae: DFlowVae, *, device: torch.device) -> None:
"""Wrap a loaded autoencoder that runs on ``device``."""
self.vae = vae
self.device = device
def decode(self, latents: Tensor) -> Tensor:
"""Decode ``[B, 96, h, w]`` latents to ``[B, 16h, 16w, 3]`` images.
Raises:
ValueError: If the latents do not have 96 channels.
"""
if latents.ndim != 4 or int(latents.shape[1]) != LATENT_CHANNELS:
raise ValueError(
f"dflow latents have shape [batch, {LATENT_CHANNELS}, height, "
f"width]; got {tuple(latents.shape)}. Use the dflow VAE only with "
"dflow latents."
)
device_latents = latents.to(device=self.device, dtype=torch.float32)
rgb = self.vae.decode(
device_latents.contiguous(memory_format=torch.channels_last)
).clamp(-1.0, 1.0)
images = rgb.add(1.0).mul(0.5).movedim(1, -1)
return images.to(comfy.model_management.intermediate_device())
def encode(self, pixels: Tensor) -> Tensor:
"""Encode ``[B, H, W, C]`` images (RGB first) to ``[B, 96, H/16, W/16]``.
Raises:
ValueError: If the image has fewer than three channels, or a side
is not a multiple of 16.
"""
if pixels.ndim != 4 or int(pixels.shape[-1]) < _RGB_CHANNELS:
raise ValueError(
f"ComfyUI images have shape [batch, height, width, channels>=3]; "
f"got {tuple(pixels.shape)}."
)
images = (
pixels[..., :_RGB_CHANNELS]
.movedim(-1, 1)
.to(device=self.device, dtype=torch.float32)
.mul(2.0)
.sub(1.0)
.contiguous(memory_format=torch.channels_last)
)
latents = self.vae.encode(images)
return latents.to(comfy.model_management.intermediate_device())
@staticmethod
def spacial_compression_decode() -> int:
"""Pixels per latent along each side."""
return LATENT_STRIDE
@staticmethod
def spacial_compression_encode() -> int:
"""Pixels per latent along each side."""
return LATENT_STRIDE
@staticmethod
def temporal_compression_decode() -> None:
"""Image-only autoencoder: no temporal axis."""
return None
|