# SPDX-License-Identifier: GPL-3.0-only # Copyright 2026 Data Archetype """ComfyUI nodes for dflow_2b. A graph is: DFlow Loader -> DFlow Text Encode (or Layout Encode) -> DFlow Guider; DFlow Sampler -> DFlow Time Schedule; DFlow Empty Latent; then the stock RandomNoise, SamplerCustomAdvanced, VAEDecode and SaveImage nodes. Every default is the release's default preset (``dflow.inference.GenerationSettings``). """ from __future__ import annotations from dataclasses import replace from enum import StrEnum from pathlib import Path from typing import Protocol import comfy.model_management import torch from torch import Tensor from ..dflow.guidance import ( SELF_ATTENTION_GAIN_MAX, SELF_ATTENTION_GAIN_MIN, SUFFIX_CAPTION_BIAS_MAX, SUFFIX_CAPTION_BIAS_MIN, BezierPdgCurve, CfgGuidance, ConstantPdgScale, EndpointCurveKind, EndpointPdgCurve, GuidanceSettings, PdgGuidance, PdgMode, PdgScaleSchedule, ProjectedGuidance, ProjectionMode, RampPdgScale, SparseMiddleSteps, SparseStepSchedule, StepWindow, ) from ..dflow.inference import ( DEFAULT_HEIGHT, DEFAULT_WIDTH, GenerationSettings, SamplingSettings, ) from ..dflow.layout import compile_layout, is_compiled_layout, is_uncompiled_layout from ..dflow.prompt_emphasis import EmphasisMapping, EmphasisSettings from ..dflow.schedules import ScheduleKind, TimeSchedule from ..dflow.solvers import Solver from ..dflow.vae import LATENT_CHANNELS, LATENT_STRIDE from .loader import load_model, release_location from .preview import build_model_patcher from .sampling import DFlowGuider from .types import ( DFlowConditioning, DFlowLatent, DFlowModelHandle, DFlowSamplerSpec, DFlowTextEncoderHandle, DFlowWeightSource, PdgCurveChoice, ScheduleBinding, ) from .vae import DFlowVaeAdapter type InputTypes = dict[str, dict[str, tuple[object, ...]]] CATEGORY = "DFlow" MAX_BATCH = 16 MAX_SIDE = 8192 MAX_STEP_INDEX = 9999 OPEN_STOP_STEP = -1 """A stop step of -1 runs a guidance window to the last step.""" # Release defaults, read from the package so the nodes cannot drift from it. _GENERATION = GenerationSettings() _SAMPLING: SamplingSettings = _GENERATION.sampling _GUIDANCE: GuidanceSettings = _GENERATION.guidance _PDG = PdgGuidance() _PDG_SCALE = ConstantPdgScale().scale _EMPHASIS = EmphasisSettings() _ENDPOINT = EndpointPdgCurve() _RAMP = RampPdgScale() _BEZIER = BezierPdgCurve() _PROJECTION = ProjectedGuidance() _SPARSE = SparseMiddleSteps() _CFG_SCALE = 4.0 def _choices[E: StrEnum]( members: type[E], default: E, tooltip: str ) -> tuple[object, ...]: """A combo input listing an enum's values.""" return ( [member.value for member in members], {"default": default.value, "tooltip": tooltip}, ) def _float( default: float, low: float, high: float, step: float, tooltip: str ) -> tuple[object, ...]: """A FLOAT input.""" return ( "FLOAT", { "default": default, "min": low, "max": high, "step": step, "round": False, "tooltip": tooltip, }, ) def _int(default: int, low: int, high: int, tooltip: str) -> tuple[object, ...]: """An INT input.""" return ( "INT", {"default": default, "min": low, "max": high, "step": 1, "tooltip": tooltip}, ) def _bool(default: bool, tooltip: str) -> tuple[object, ...]: """A BOOLEAN input.""" return ("BOOLEAN", {"default": default, "tooltip": tooltip}) def _side(default: int, tooltip: str) -> tuple[object, ...]: """An image side in pixels, a multiple of 16.""" return ( "INT", { "default": default, "min": LATENT_STRIDE, "max": MAX_SIDE, "step": LATENT_STRIDE, "tooltip": tooltip, }, ) def _window(start: int, stop: int) -> StepWindow: """A guidance step window; ``stop`` -1 is open-ended. Raises: ValueError: For a stop below -1 or before the start. """ if stop < OPEN_STOP_STEP: raise ValueError(f"A stop step must be -1 or a step index, got {stop}.") return StepWindow(start, None if stop == OPEN_STOP_STEP else stop) def _latent_size(latent: DFlowLatent) -> tuple[int, int]: """``(width, height)`` in pixels of a dflow latent. Raises: ValueError: If the latent does not have 96 channels. """ samples = latent["samples"] if samples.ndim != 4 or int(samples.shape[1]) != LATENT_CHANNELS: raise ValueError( f"Expected a dflow latent [batch, {LATENT_CHANNELS}, height, width] " f"(DFlow Empty Latent); got {tuple(samples.shape)}." ) return int(samples.shape[3]) * LATENT_STRIDE, int(samples.shape[2]) * LATENT_STRIDE def _encode( encoder: DFlowTextEncoderHandle, prompts: tuple[str, ...], emphasis: EmphasisSettings | None, layout_size: tuple[int, int] | None, ) -> DFlowConditioning: """Encode and refine a prompt batch (as ``DFlowEngine.prepare_texts``); ``layout_size`` is the size a layout was compiled for, if any.""" engine = encoder.model.engine with torch.inference_mode(): text = engine.model.prepare_text( engine.text_encoder.encode(list(prompts), emphasis=emphasis) ) return DFlowConditioning( model=encoder.model, prompts=prompts, text=text, emphasis=emphasis, layout_size=layout_size, ) def _cfg( enabled: bool, scale: float, window: StepWindow, pdg: PdgGuidance | None ) -> CfgGuidance: """CFG settings; the scale is kept when CFG or a CFG-using PDG mode runs.""" needed = enabled or (pdg is not None and pdg.mode.uses_cfg) return CfgGuidance(enabled=enabled, scale=scale if needed else None, window=window) def _dflow_guider(guider: object) -> DFlowGuider: """The dflow guider behind a GUIDER input. Raises: TypeError: For a guider of another node pack. """ match guider: case DFlowGuider(): return guider case _: raise TypeError( f"Expected the guider of DFlow Guider, got {type(guider).__name__}." ) def _dflow_sampler(sampler: object) -> DFlowSamplerSpec: """The dflow sampler behind a SAMPLER input. Raises: TypeError: For a sampler of another node pack. """ match sampler: case DFlowSamplerSpec(): return sampler case _: raise TypeError( f"Expected the sampler of DFlow Sampler, got {type(sampler).__name__}." ) class DFlowLoader: """Load the dflow_2b denoiser, text encoder and dinac3_96 autoencoder.""" DESCRIPTION = ( "bundled reads the weights in this node folder; local_dir another " "release folder; hub a Hugging Face repository at a revision. The " "autoencoder downloads from data-archetype/dinac3_96 on first use. " "compile_model compiles the blocks (30 to 45 seconds on first use)." ) RETURN_TYPES = ("DFLOW_MODEL", "DFLOW_TEXT_ENCODER", "VAE") RETURN_NAMES = ("model", "text_encoder", "vae") FUNCTION = "load" CATEGORY = CATEGORY @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """Source, its location fields, compile switch and cache directory.""" return { "required": { "source": _choices( DFlowWeightSource, DFlowWeightSource.BUNDLED, "Where the weights are read from.", ), "local_dir": ( "STRING", {"default": "", "tooltip": "Release folder (local_dir only)."}, ), "repository": ( "STRING", { "default": "data-archetype/dflow_2b", "tooltip": "Hugging Face repository (hub only).", }, ), "revision": ( "STRING", { "default": "", "tooltip": "Hub revision, such as a release tag (v0.21); " "empty for main.", }, ), "compile_model": _bool(True, "torch.compile the model (faster)."), "cache_dir": ( "STRING", {"default": "", "tooltip": "Hugging Face cache; empty: default."}, ), } } def load( self, *, source: str, local_dir: str, repository: str, revision: str, compile_model: bool, cache_dir: str, ) -> tuple[DFlowModelHandle, DFlowTextEncoderHandle, DFlowVaeAdapter]: """Load the release onto ComfyUI's torch device.""" device = comfy.model_management.get_torch_device() model = load_model( release_location( DFlowWeightSource(source), local_dir=local_dir, repository=repository ), device=device, compile_model=compile_model, revision=revision.strip() or None, cache_dir=Path(cache_dir.strip()).expanduser() if cache_dir.strip() else None, ) return ( model, DFlowTextEncoderHandle(model), DFlowVaeAdapter(model.components.vae, device=device), ) class DFlowTextEncode: """Encode a prompt with the bundled text encoder.""" DESCRIPTION = ( "Plain prompts and compiled layout prompts. (phrase:weight) markup " "weights a phrase when emphasis is on; quoted text is spelled out " "character by character. Compiled layout prompts are encoded as " "written; use DFlow Layout Encode for stored layouts and MOSS drafts." ) RETURN_TYPES = ("DFLOW_CONDITIONING",) RETURN_NAMES = ("conditioning",) FUNCTION = "encode" CATEGORY = f"{CATEGORY}/conditioning" @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """Text, batch size and the prompt-emphasis settings.""" return { "required": { "text_encoder": ("DFLOW_TEXT_ENCODER",), "text": ("STRING", {"default": "", "multiline": True}), "batch_size": _int(1, 1, MAX_BATCH, "Copies of the prompt."), "emphasis": _bool(True, "Apply (phrase:weight) markup."), "emphasis_mapping": _choices( EmphasisMapping, _EMPHASIS.mapping, "Weight to attention-bias mapping for weights above 0.", ), "emphasis_strength": _float( _EMPHASIS.strength, 0.0, 4.0, 0.05, "Multiplier on every weight." ), "emphasis_encoder": _bool( _EMPHASIS.encoder, "Also weight inside the text encoder." ), } } def encode( self, *, text_encoder: DFlowTextEncoderHandle, text: str, batch_size: int, emphasis: bool, emphasis_mapping: str, emphasis_strength: float, emphasis_encoder: bool, ) -> tuple[DFlowConditioning]: """Encode ``batch_size`` copies of the prompt. Raises: ValueError: For a stored layout or MOSS draft (they need the image size). """ if is_uncompiled_layout(text): raise ValueError( "This layout (a stored layout or a MOSS draft) must be compiled " "at the image size; use DFlow Layout Encode." ) settings = ( EmphasisSettings( mapping=EmphasisMapping(emphasis_mapping), strength=emphasis_strength, encoder=emphasis_encoder, ) if emphasis else None ) return (_encode(text_encoder, (text,) * batch_size, settings, None),) class DFlowLayoutEncode: """Compile a layout (stored, compiled or MOSS-Image) at the image size and encode it.""" DESCRIPTION = ( "Takes a stored layout (summary, frame, items with box_2d on a 0-1000 " "grid), a MOSS-Image layout prompt or a MOSS-Image editable draft, " "and compiles it at width x height; a full-canvas panel is added " "first when the layout has none. width and height must match the " "latent; the guider checks it." ) RETURN_TYPES = ("DFLOW_CONDITIONING",) RETURN_NAMES = ("conditioning",) FUNCTION = "encode" CATEGORY = f"{CATEGORY}/conditioning" @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """Layout JSON, image size and batch size.""" return { "required": { "text_encoder": ("DFLOW_TEXT_ENCODER",), "layout_json": ("STRING", {"default": "", "multiline": True}), "width": _side(DEFAULT_WIDTH, "Image width the layout is for."), "height": _side(DEFAULT_HEIGHT, "Image height the layout is for."), "batch_size": _int(1, 1, MAX_BATCH, "Copies of the prompt."), } } def encode( self, *, text_encoder: DFlowTextEncoderHandle, layout_json: str, width: int, height: int, batch_size: int, ) -> tuple[DFlowConditioning]: """Compile the layout at the image size and encode the result. Raises: ValueError: If the text is not a layout, or for a malformed layout. """ if not is_compiled_layout(layout_json): raise ValueError( "layout_json is not a layout (a JSON object with summary and " "items); use DFlow Text Encode for plain prompts." ) compiled = compile_layout(layout_json, width, height) return (_encode(text_encoder, (compiled,) * batch_size, None, (width, height)),) class DFlowGuiderNode: """Path-drop guidance (PDG), CFG and the self-attention gain.""" DESCRIPTION = ( "PDG compares the model with a copy that skips its middle layers. The " "optional negative is read by CFG and the contrastive PDG modes; " "without it they use the learned null text. The PDG reference reads " "the prompt with a negative attention bias in its last six layers " "(pdg_suffix_caption_bias). Step windows count solver steps from 0; a " "stop step of -1 runs to the end." ) RETURN_TYPES = ("GUIDER",) RETURN_NAMES = ("guider",) FUNCTION = "build" CATEGORY = f"{CATEGORY}/sampling" @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """PDG, CFG, windows, the PDG suffix caption bias and the gain; defaults are the release preset.""" return { "required": { "model": ("DFLOW_MODEL",), "positive": ("DFLOW_CONDITIONING",), "pdg_enabled": _bool(_GUIDANCE.pdg is not None, "Path-drop guidance."), "pdg_mode": _choices(PdgMode, _PDG.mode, "PDG reference policy."), "pdg_scale": _float( _PDG_SCALE, 0.0, 30.0, 0.05, "PDG scale (1: none)." ), "pdg_start_step": _int(0, 0, MAX_STEP_INDEX, "First PDG step."), "pdg_stop_step": _int( OPEN_STOP_STEP, OPEN_STOP_STEP, MAX_STEP_INDEX, "Last PDG step." ), "pdg_suffix_caption_bias": _float( _PDG.suffix_caption_bias, SUFFIX_CAPTION_BIAS_MIN, SUFFIX_CAPTION_BIAS_MAX, 0.25, "Attention-logit bias on the prompt's keys in the suffix layers " "of the PDG reference (0: none).", ), "cfg_enabled": _bool( _GUIDANCE.cfg.enabled, "Classifier-free guidance." ), "cfg_scale": _float( _CFG_SCALE, 0.0, 30.0, 0.05, "CFG scale; also the CFG modes'." ), "cfg_start_step": _int(0, 0, MAX_STEP_INDEX, "First CFG step."), "cfg_stop_step": _int( OPEN_STOP_STEP, OPEN_STOP_STEP, MAX_STEP_INDEX, "Last CFG step." ), "self_attention_gain": _float( _GUIDANCE.self_attention_gain, SELF_ATTENTION_GAIN_MIN, SELF_ATTENTION_GAIN_MAX, 0.005, "Image self-attention logit gain of the main pass.", ), }, "optional": {"negative": ("DFLOW_CONDITIONING",)}, } def build( self, *, model: DFlowModelHandle, positive: DFlowConditioning, pdg_enabled: bool, pdg_mode: str, pdg_scale: float, pdg_start_step: int, pdg_stop_step: int, pdg_suffix_caption_bias: float, cfg_enabled: bool, cfg_scale: float, cfg_start_step: int, cfg_stop_step: int, self_attention_gain: float, negative: DFlowConditioning | None = None, ) -> tuple[DFlowGuider]: """Build the guider.""" pdg = ( PdgGuidance( mode=PdgMode(pdg_mode), scale=ConstantPdgScale(pdg_scale), window=_window(pdg_start_step, pdg_stop_step), suffix_caption_bias=pdg_suffix_caption_bias, ) if pdg_enabled else None ) guidance = GuidanceSettings( pdg=pdg, cfg=_cfg( cfg_enabled, cfg_scale, _window(cfg_start_step, cfg_stop_step), pdg ), self_attention_gain=self_attention_gain, ) return (_guider(model, positive, negative, guidance),) def _guider( model: DFlowModelHandle, positive: DFlowConditioning, negative: DFlowConditioning | None, guidance: GuidanceSettings, ) -> DFlowGuider: """A guider with the model's preview patcher.""" return DFlowGuider( model=model, positive=positive, negative=negative, guidance=guidance, model_patcher=build_model_patcher(model.preview, device=model.device), ) class DFlowGuiderAdvanced: """Extra guidance controls on top of a DFlow Guider.""" DESCRIPTION = ( "pdg_curve replaces the constant PDG scale: ramp goes from " "ramp_start_scale to ramp_end_scale over the first ramp_length of the " "schedule; the endpoint curves go from curve_noisy_scale to " "curve_clean_scale; bezier is 1 + bezier_multiplier times a fitted " "curve. Projected guidance (APG) and rescale tame over-saturation and " "exclude each other. Sparse middle steps run the main pass with one " "token per 2x2 group through the middle layers (faster)." ) RETURN_TYPES = ("GUIDER",) RETURN_NAMES = ("guider",) FUNCTION = "build" CATEGORY = f"{CATEGORY}/sampling" @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """Curve, APG, rescale, sparse-step and guidance-gain controls.""" return { "required": { "guider": ("GUIDER",), "guidance_self_attention_gain": _float( _GUIDANCE.guidance_self_attention_gain, SELF_ATTENTION_GAIN_MIN, SELF_ATTENTION_GAIN_MAX, 0.005, "Self-attention gain of the guidance passes.", ), "pdg_curve": _choices( PdgCurveChoice, PdgCurveChoice.CONSTANT, "PDG scale schedule." ), "curve_noisy_scale": _float( _ENDPOINT.noisy_scale, 0.0, 30.0, 0.05, "Scale at the first step." ), "curve_clean_scale": _float( _ENDPOINT.clean_scale, 0.0, 30.0, 0.05, "Scale at the last step." ), "curve_power": _float(_ENDPOINT.power, 0.01, 20.0, 0.05, "power."), "s_curve_knee": _float( _ENDPOINT.s_curve_knee, 0.0, 1.0, 0.01, "s_curve midpoint." ), "s_curve_sharpness": _float( _ENDPOINT.s_curve_sharpness, 0.01, 50.0, 0.1, "s_curve slope." ), "ramp_start_scale": _float( _RAMP.start_scale, 0.0, 30.0, 0.05, "Ramp scale at the noisy end." ), "ramp_end_scale": _float( _RAMP.end_scale, 0.0, 30.0, 0.05, "Ramp scale after the ramp." ), "ramp_length": _float( _RAMP.length, 0.01, 1.0, 0.01, "Fraction of the schedule." ), "bezier_multiplier": _float( _BEZIER.multiplier, 0.0, 30.0, 0.05, "Bezier curve height." ), "projection": _choices( ProjectionMode, _PROJECTION.mode, "Projected guidance (APG)." ), "projection_parallel_weight": _float( _PROJECTION.parallel_weight, 0.0, 1.0, 0.01, "APG parallel part." ), "projection_first_band": _int( _PROJECTION.first_band, 0, 4, "per_band: first projected band." ), "rescale": _float( _GUIDANCE.rescale, 0.0, 1.0, 0.01, "Guidance rescale (0: off)." ), "sparse_middle_percent": _float( _SPARSE.percent, 0.0, 100.0, 1.0, "Percent of sparse steps." ), "sparse_middle_schedule": _choices( SparseStepSchedule, _SPARSE.schedule, "Which steps are sparse." ), } } def build( self, *, guider: object, guidance_self_attention_gain: float, pdg_curve: str, curve_noisy_scale: float, curve_clean_scale: float, curve_power: float, s_curve_knee: float, s_curve_sharpness: float, ramp_start_scale: float, ramp_end_scale: float, ramp_length: float, bezier_multiplier: float, projection: str, projection_parallel_weight: float, projection_first_band: int, rescale: float, sparse_middle_percent: float, sparse_middle_schedule: str, ) -> tuple[DFlowGuider]: """Return the input guider with these settings applied. Raises: TypeError: For a guider of another node pack. ValueError: For a PDG curve with PDG off, or invalid settings. """ base = _dflow_guider(guider) curve = PdgCurveChoice(pdg_curve) endpoint = EndpointPdgCurve( kind=EndpointCurveKind.POWER, noisy_scale=curve_noisy_scale, clean_scale=curve_clean_scale, power=curve_power, s_curve_knee=s_curve_knee, s_curve_sharpness=s_curve_sharpness, ) ramp = RampPdgScale(ramp_start_scale, ramp_end_scale, ramp_length) settings = replace( base.guidance, pdg=_with_curve( base.guidance.pdg, curve, endpoint, ramp, bezier_multiplier ), guidance_self_attention_gain=guidance_self_attention_gain, projection=ProjectedGuidance( mode=ProjectionMode(projection), parallel_weight=projection_parallel_weight, first_band=projection_first_band, ), rescale=rescale, sparse_middle=SparseMiddleSteps( percent=sparse_middle_percent, schedule=SparseStepSchedule(sparse_middle_schedule), ), ) return (base.with_guidance(settings),) def _with_curve( pdg: PdgGuidance | None, curve: PdgCurveChoice, endpoint: EndpointPdgCurve, ramp: RampPdgScale, bezier_multiplier: float, ) -> PdgGuidance | None: """``pdg`` with its scale schedule replaced by the chosen curve. Raises: ValueError: For a curve other than constant while PDG is off. """ if pdg is None: if curve is not PdgCurveChoice.CONSTANT: raise ValueError(f"pdg_curve {curve.value} needs PDG on in the guider.") return None scale: PdgScaleSchedule match curve: case PdgCurveChoice.CONSTANT: scale = pdg.scale case PdgCurveChoice.RAMP: scale = ramp case ( PdgCurveChoice.LINEAR | PdgCurveChoice.LINEAR_LOGSNR | PdgCurveChoice.POWER | PdgCurveChoice.S_CURVE ): scale = replace(endpoint, kind=EndpointCurveKind(curve.value)) case PdgCurveChoice.BEZIER: scale = BezierPdgCurve(multiplier=bezier_multiplier) case _ as unreachable: raise ValueError(f"Unsupported PDG curve: {unreachable}") return replace(pdg, scale=scale) class DFlowSampler: """Choose dflow's solver and its noise scale.""" DESCRIPTION = ( "noise_scale multiplies the injected noise of the stochastic solvers " "(eta for dpmpp_2m_sde); deterministic solvers ignore it. Connect it " "to DFlow Time Schedule, whose sampler output goes to " "SamplerCustomAdvanced." ) RETURN_TYPES = ("SAMPLER",) RETURN_NAMES = ("sampler",) FUNCTION = "build" CATEGORY = f"{CATEGORY}/sampling" @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """Solver and noise scale.""" return { "required": { "solver": _choices(Solver, _SAMPLING.solver, "Numerical solver."), "noise_scale": _float( _SAMPLING.noise_scale, 0.0, 10.0, 0.05, "SDE noise multiplier." ), } } def build(self, *, solver: str, noise_scale: float) -> tuple[DFlowSamplerSpec]: """The sampler, not yet paired with a schedule.""" return (DFlowSamplerSpec(Solver(solver), noise_scale, binding=None),) def _schedule_inputs(steps_min: int) -> dict[str, tuple[object, ...]]: """Inputs shared by the schedule nodes.""" schedule = _SAMPLING.schedule return { "sampler": ("SAMPLER",), "latent": ("LATENT",), "schedule": _choices(ScheduleKind, schedule.kind, "Step spacing."), "steps": _int(schedule.steps, steps_min, 1000, "Solver steps."), "base_log_snr_shift": _float( _SAMPLING.base_log_snr_shift, -20.0, 20.0, 0.05, "Size-free shift." ), "resolution_shift": _bool( _SAMPLING.resolution_shift, "Add the trained image-size shift." ), "beta_mean": _float(schedule.beta_mean, 0.01, 0.99, 0.01, "custom_beta."), "beta_concentration": _float( schedule.beta_concentration, 0.01, 100.0, 0.05, "custom_beta." ), } def _full_schedule( sampler: object, latent: DFlowLatent, schedule: TimeSchedule, base_log_snr_shift: float, resolution_shift: bool, ) -> tuple[Tensor, DFlowSamplerSpec]: """The full CPU schedule for the latent's size and the bound sampler. The schedule is computed on the model's device, as the package does, then copied to the CPU. """ spec = _dflow_sampler(sampler) width, height = _latent_size(latent) sampling = SamplingSettings( solver=spec.solver, noise_scale=spec.noise_scale, schedule=schedule, base_log_snr_shift=base_log_snr_shift, resolution_shift=resolution_shift, ) device = comfy.model_management.get_torch_device() sigmas = sampling.timesteps(width, height, device).cpu() binding = ScheduleBinding( schedule=schedule, log_snr_shift=sampling.log_snr_shift(width, height), width=width, height=height, ) return sigmas, spec.bound(binding) class DFlowTimeSchedule: """Build dflow's timestep schedule for the latent's size.""" DESCRIPTION = ( "Connect both outputs to SamplerCustomAdvanced. The shift moves steps " "toward the noisy end; with resolution_shift the trained image-size " "term -ln(width*height/256^2) is added (capped at 0)." ) RETURN_TYPES = ("SIGMAS", "SAMPLER") RETURN_NAMES = ("sigmas", "sampler") FUNCTION = "build" CATEGORY = f"{CATEGORY}/sampling" @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """Sampler, latent, schedule family, steps and shift.""" return {"required": _schedule_inputs(steps_min=1)} def build( self, *, sampler: object, latent: DFlowLatent, schedule: str, steps: int, base_log_snr_shift: float, resolution_shift: bool, beta_mean: float, beta_concentration: float, ) -> tuple[Tensor, DFlowSamplerSpec]: """The schedule and the sampler paired with it.""" return _full_schedule( sampler, latent, TimeSchedule(ScheduleKind(schedule), steps, beta_mean, beta_concentration), base_log_snr_shift, resolution_shift, ) class DFlowEmptyLatent: """An empty 96-channel dflow latent.""" RETURN_TYPES = ("LATENT",) RETURN_NAMES = ("latent",) FUNCTION = "create" CATEGORY = f"{CATEGORY}/latent" @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """Image size and batch size.""" return { "required": { "width": _side(_GENERATION.width, "Image width (multiple of 16)."), "height": _side(_GENERATION.height, "Image height (multiple of 16)."), "batch_size": _int(1, 1, MAX_BATCH, "Images per run."), } } def create(self, *, width: int, height: int, batch_size: int) -> tuple[DFlowLatent]: """Zeros ``[batch, 96, height / 16, width / 16]`` on the CPU. Raises: ValueError: For a side that is not a multiple of 16. """ for name, value in (("width", width), ("height", height)): if value <= 0 or value % LATENT_STRIDE: raise ValueError( f"{name} must be a positive multiple of {LATENT_STRIDE}, " f"got {value}." ) samples = torch.zeros( ( batch_size, LATENT_CHANNELS, height // LATENT_STRIDE, width // LATENT_STRIDE, ), dtype=torch.float32, device="cpu", ) return ({"samples": samples, "downscale_ratio_spacial": LATENT_STRIDE},) class ComfyNodeClass(Protocol): """What ComfyUI reads from a node class (beyond its declared constants).""" @classmethod def INPUT_TYPES(cls) -> InputTypes: # noqa: N802 (ComfyUI API) """The node's inputs.""" ... NODE_CLASS_MAPPINGS: dict[str, type[ComfyNodeClass]] = { "DFlowLoader": DFlowLoader, "DFlowTextEncode": DFlowTextEncode, "DFlowLayoutEncode": DFlowLayoutEncode, "DFlowGuider": DFlowGuiderNode, "DFlowGuiderAdvanced": DFlowGuiderAdvanced, "DFlowSampler": DFlowSampler, "DFlowTimeSchedule": DFlowTimeSchedule, "DFlowEmptyLatent": DFlowEmptyLatent, } NODE_DISPLAY_NAME_MAPPINGS: dict[str, str] = { "DFlowLoader": "DFlow Loader", "DFlowTextEncode": "DFlow Text Encode", "DFlowLayoutEncode": "DFlow Layout Encode", "DFlowGuider": "DFlow Guider", "DFlowGuiderAdvanced": "DFlow Guider Advanced", "DFlowSampler": "DFlow Sampler", "DFlowTimeSchedule": "DFlow Time Schedule", "DFlowEmptyLatent": "DFlow Empty Latent", }