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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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
# 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",
}